<?php 
include "../../conn.php";

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization');
header('Access-Control-Allow-Credentials: true');
$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
header('Access-Control-Allow-Origin: ' . $origin);

date_default_timezone_set("Asia/Kolkata");
$shnunc = date("Y-m-d H:i:s");

// JWT Verify Function with DEBUG
function is_jwt_valid_debug($jwt, $secret = 'bdgshonuuncensored') {
    $res = [
        'status' => 'Failed',
        'payload' => [],
        'debug' => ''
    ];

    // Check if token has 3 parts
    $tokenParts = explode('.', $jwt);
    if (count($tokenParts) != 3) {
        $res['debug'] = 'Token does not have 3 parts. Count: ' . count($tokenParts);
        return json_encode($res);
    }

    // Decode parts
    $header = json_decode(base64_decode(strtr($tokenParts[0], '-_', '+/')), true);
    $payload = json_decode(base64_decode(strtr($tokenParts[1], '-_', '+/')), true);
    $signature_provided = $tokenParts[2];

    // Generate signature
    $base64_header = rtrim(strtr(base64_encode(json_encode($header)), '+/', '-_'), '=');
    $base64_payload = rtrim(strtr(base64_encode(json_encode($payload)), '+/', '-_'), '=');
    $signature = hash_hmac('SHA256', "$base64_header.$base64_payload", $secret, true);
    $base64_signature = rtrim(strtr(base64_encode($signature), '+/', '-_'), '=');

    // Debug info
    $res['debug'] = [
        'header' => $header,
        'payload' => $payload,
        'signature_provided' => substr($signature_provided, 0, 20) . '...',
        'signature_calculated' => substr($base64_signature, 0, 20) . '...',
        'match' => ($base64_signature === $signature_provided)
    ];

    if ($base64_signature === $signature_provided) {
        $res['status'] = 'Success';
        $res['payload'] = $payload;
    }

    return json_encode($res);
}

$res = [
    'code' => 11,
    'msg' => 'Method not allowed',
    'msgCode' => 12,
    'serviceNowTime' => $shnunc,
];

if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    http_response_code(405);
    echo json_encode($res);
    exit;
}

$shonubody = file_get_contents("php://input");
$shonupost = json_decode($shonubody, true);

// Get Authorization header
$authHeader = isset($_SERVER['HTTP_AUTHORIZATION']) ? $_SERVER['HTTP_AUTHORIZATION'] : '';

if (empty($authHeader)) {
    echo json_encode([
        'code' => 4,
        'msg' => 'Auth Header Missing',
        'received_headers' => getallheaders()
    ]);
    exit;
}

// Extract token
$bearer = explode(" ", $authHeader);
if (count($bearer) < 2) {
    echo json_encode([
        'code' => 4,
        'msg' => 'Invalid Auth Format',
        'auth_header' => $authHeader
    ]);
    exit;
}

$token = $bearer[1];

// DEBUG: Check token
$jwtCheck = is_jwt_valid_debug($token);
$jwtData = json_decode($jwtCheck, true);

// Return debug info
echo json_encode([
    'code' => 0,
    'msg' => 'Debug Info',
    'token_received' => substr($token, 0, 50) . '...',
    'jwt_status' => $jwtData['status'],
    'jwt_payload' => $jwtData['payload'] ?? null,
    'debug_info' => $jwtData['debug'] ?? null
]);
?>