<?php
/**
 * PACK BEACON – SECURE API AUTH MIDDLEWARE
 * Path: /api-secure/auth-secure.php
 *
 * การใช้งาน:
 *   require_once __DIR__ . '/config-secure.php';
 *   require_once __DIR__ . '/auth-secure.php';
 *
 *   list($raw, $input) = require_secure_json();
 *
 *   // จากนั้น $input คือ array ของ JSON ที่ส่งมา
 *   // เช่น $user_id = intval($input['user_id'] ?? 0);
 */

require_once __DIR__ . '/config-secure.php';

/**
 * ดึง Header แบบปลอดภัย (รองรับทั้ง Apache / Nginx / PHP-FPM)
 */
function get_request_headers_safe() {
    if (function_exists('getallheaders')) {
        return getallheaders();
    }

    $headers = [];
    foreach ($_SERVER as $name => $value) {
        if (substr($name, 0, 5) == 'HTTP_') {
            $key = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))));
            $headers[$key] = $value;
        }
    }
    return $headers;
}

/**
 * Middleware หลัก: ตรวจ Token + Timestamp + Signature
 * และคืนค่า [ $raw_body, $json_array ]
 */
function require_secure_json() {
    $headers = get_request_headers_safe();

    // อ่านค่า Header ตามที่ตกลงกัน
    $client_token     = $headers['X-API-TOKEN']    ?? ($headers['x-api-token']    ?? '');
    $client_timestamp = $headers['X-TIMESTAMP']    ?? ($headers['x-timestamp']    ?? '');
    $client_signature = $headers['X-SIGNATURE']    ?? ($headers['x-signature']    ?? '');

    $client_timestamp = intval($client_timestamp);

    // อ่าน raw body
    $raw = get_raw_post();

    // ตรวจสอบลายเซ็น/เวลา/token
    $verify = verify_signature($client_token, $client_timestamp, $client_signature, $raw);

    if ($verify !== true) {
        http_response_code(401);
        api_json([
            "status"  => "error",
            "message" => $verify
        ]);
    }

    // แปลง JSON → array
    $data = [];
    if (!empty($raw)) {
        $data = json_decode($raw, true);
        if (!is_array($data)) {
            http_response_code(400);
            api_json([
                "status"  => "error",
                "message" => "Invalid JSON body"
            ]);
        }
    }

    return [$raw, $data];
}

/**
 * Helper: Require ว่าต้องเป็น Method ตามที่กำหนด
 * เช่น require_method('POST');
 */
function require_method($method) {
    if (strtoupper($_SERVER['REQUEST_METHOD']) !== strtoupper($method)) {
        http_response_code(405);
        api_json([
            "status"  => "error",
            "message" => "Method not allowed. Use " . strtoupper($method)
        ]);
    }
}

/**
 * Helper: ดึง IP ผู้เรียกใช้งาน (เก็บลง logs ได้)
 */
function get_client_ip() {
    $ip_keys = [
        'HTTP_CLIENT_IP', 
        'HTTP_X_FORWARDED_FOR', 
        'HTTP_X_FORWARDED', 
        'HTTP_X_CLUSTER_CLIENT_IP', 
        'HTTP_FORWARDED_FOR', 
        'HTTP_FORWARDED', 
        'REMOTE_ADDR'
    ];
    foreach ($ip_keys as $key) {
        if (!empty($_SERVER[$key])) {
            $ips = explode(',', $_SERVER[$key]);
            return trim($ips[0]);
        }
    }
    return '0.0.0.0';
}
