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

header('Content-Type: application/json; charset=utf-8');
header('Strict-Transport-Security: max-age=31536000');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization, AR-REAL-IP');
header('Access-Control-Allow-Credentials: true');

$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
header('Access-Control-Allow-Origin: ' . $origin);
header('vary: Origin');

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

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

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

if ($_SERVER['REQUEST_METHOD'] != 'GET') {
    
    if (isset($shonupost['language']) && isset($shonupost['random']) && isset($shonupost['signature']) && isset($shonupost['timestamp'])) {
        
        // Get raw values for signature validation
        $language = $shonupost['language'];
        $random = $shonupost['random'];
        $signature = $shonupost['signature'];
        $timestamp = $shonupost['timestamp'];
        
        // Try different signature formats to match client
        $signature_valid = false;
        $shonustr = '';
        $shonusign = '';
        
        // Format 1: json_encode() - Most reliable
        $temp_array1 = [
            'language' => $language,
            'random' => $random
        ];
        $shonustr1 = json_encode($temp_array1);
        $shonusign1 = strtoupper(md5($shonustr1));
        
        if($shonusign1 == $signature) {
            $signature_valid = true;
            $shonustr = $shonustr1;
            $shonusign = $shonusign1;
        }
        
        // Format 2: No quotes around language (if numeric)
        if(!$signature_valid && is_numeric($language)) {
            $shonustr2 = '{"language":' . $language . ',"random":"' . $random . '"}';
            $shonusign2 = strtoupper(md5($shonustr2));
            
            if($shonusign2 == $signature) {
                $signature_valid = true;
                $shonustr = $shonustr2;
                $shonusign = $shonusign2;
            }
        }
        
        // Format 3: With spaces after colons
        if(!$signature_valid) {
            $shonustr3 = '{"language": "' . $language . '", "random": "' . $random . '"}';
            $shonusign3 = strtoupper(md5($shonustr3));
            
            if($shonusign3 == $signature) {
                $signature_valid = true;
                $shonustr = $shonustr3;
                $shonusign = $shonusign3;
            }
        }
        
        // Format 4: With quotes around language (string format)
        if(!$signature_valid) {
            $shonustr4 = '{"language":"' . $language . '","random":"' . $random . '"}';
            $shonusign4 = strtoupper(md5($shonustr4));
            
            if($shonusign4 == $signature) {
                $signature_valid = true;
                $shonustr = $shonustr4;
                $shonusign = $shonusign4;
            }
        }
        
        // Format 5: Without outer quotes (rare)
        if(!$signature_valid) {
            $shonustr5 = '{language:' . $language . ',random:' . $random . '}';
            $shonusign5 = strtoupper(md5($shonustr5));
            
            if($shonusign5 == $signature) {
                $signature_valid = true;
                $shonustr = $shonustr5;
                $shonusign = $shonusign5;
            }
        }
        
        // Debug logging - Remove in production
        error_log("=== MD5 SIGNATURE DEBUG ===");
        error_log("Client MD5: " . $signature);
        error_log("Format 1 (json_encode): " . $shonusign1 . " - " . ($shonusign1 == $signature ? 'MATCH' : 'NO'));
        if(isset($shonusign2)) error_log("Format 2 (no quotes): " . $shonusign2 . " - " . ($shonusign2 == $signature ? 'MATCH' : 'NO'));
        if(isset($shonusign3)) error_log("Format 3 (with spaces): " . $shonusign3 . " - " . ($shonusign3 == $signature ? 'MATCH' : 'NO'));
        if(isset($shonusign4)) error_log("Format 4 (with quotes): " . $shonusign4 . " - " . ($shonusign4 == $signature ? 'MATCH' : 'NO'));
        if(isset($shonusign5)) error_log("Format 5 (no outer quotes): " . $shonusign5 . " - " . ($shonusign5 == $signature ? 'MATCH' : 'NO'));
        error_log("============================");
        
        if($signature_valid) {
            
            // NOW sanitize values for database use (after signature validation)
            $language_db = mysqli_real_escape_string($conn, htmlspecialchars($language));
            $random_db = mysqli_real_escape_string($conn, htmlspecialchars($random));
            $timestamp_db = mysqli_real_escape_string($conn, htmlspecialchars($timestamp));
            
            // Check if Authorization header exists
            if(!isset($_SERVER['HTTP_AUTHORIZATION'])) {
                $res['code'] = 4;
                $res['msg'] = 'Authorization header missing';
                $res['msgCode'] = 2;
                http_response_code(401);
                echo json_encode($res);
                exit;
            }
            
            $bearer = explode(" ", $_SERVER['HTTP_AUTHORIZATION']);
            
            if(count($bearer) < 2) {
                $res['code'] = 4;
                $res['msg'] = 'Invalid authorization format';
                $res['msgCode'] = 2;
                http_response_code(401);
                echo json_encode($res);
                exit;
            }
            
            $author = $bearer[1];
            
            // Check if token is empty
            if(empty($author)) {
                $res['code'] = 4;
                $res['msg'] = 'Empty token';
                $res['msgCode'] = 2;
                http_response_code(401);
                echo json_encode($res);
                exit;
            }
            
            $is_jwt_valid = is_jwt_valid($author);
            $data_auth = json_decode($is_jwt_valid, true);
            
            if($data_auth && isset($data_auth['status'])) {
                
                if($data_auth['status'] === 'Success') {
                    
                    // Check if payload has expire field
                    if(isset($data_auth['payload']['expire'])) {
                        
                        if($data_auth['payload']['expire'] >= time()){
                            
                            // Token is valid and not expired
                            $data = null;
                            
                            // TODO: Add your logic here to check multiple sessions
                            // For now, it's returning that user is logged in elsewhere
                            
                            $res['data'] = $data;
                            $res['code'] = 12;
                            $res['msg'] = 'Your account is already logged in elsewhere';
                            $res['msgCode'] = 22;
                            http_response_code(200);
                            echo json_encode($res);
                        }
                        else{
                            $res['code'] = 4;
                            $res['msg'] = 'Login has expired';
                            $res['msgCode'] = 10;
                            http_response_code(401);
                            echo json_encode($res);
                        }
                    }
                    else {
                        $res['code'] = 4;
                        $res['msg'] = 'Invalid token payload - missing expire';
                        $res['msgCode'] = 2;
                        http_response_code(401);
                        echo json_encode($res);
                    }
                }
                else{
                    // JWT validation failed with specific reason
                    $error_msg = is_string($data_auth['payload']) ? $data_auth['payload'] : 'No operation permission';
                    
                    $res['code'] = 4;
                    $res['msg'] = $error_msg;
                    $res['msgCode'] = 2;
                    http_response_code(401);
                    echo json_encode($res);
                }
            }
            else{
                $res['code'] = 4;
                $res['msg'] = 'Invalid JWT validation response';
                $res['msgCode'] = 2;
                http_response_code(401);
                echo json_encode($res);
            }
        }
        else{
            $res['code'] = 5;
            $res['msg'] = 'Wrong signature';
            $res['msgCode'] = 3;
            
            // Add debug info - Remove in production
            $res['debug'] = [
                'client_md5' => $signature,
                'attempts' => [
                    'json_encode' => $shonusign1 ?? null,
                    'no_quotes' => $shonusign2 ?? null,
                    'with_spaces' => $shonusign3 ?? null,
                    'with_quotes' => $shonusign4 ?? null,
                    'no_outer_quotes' => $shonusign5 ?? null,
                ],
                'language_value' => $language,
                'language_type' => gettype($language),
                'random_value' => $random
            ];
            
            http_response_code(200);
            echo json_encode($res);
        }
    }
    else{
        $missing_params = [];
        if(!isset($shonupost['language'])) $missing_params[] = 'language';
        if(!isset($shonupost['random'])) $missing_params[] = 'random';
        if(!isset($shonupost['signature'])) $missing_params[] = 'signature';
        if(!isset($shonupost['timestamp'])) $missing_params[] = 'timestamp';
        
        $res['code'] = 7;
        $res['msg'] = 'Param is Invalid';
        $res['msgCode'] = 6;
        $res['missing_params'] = $missing_params;
        http_response_code(200);
        echo json_encode($res);
    }
} 
else {        
    http_response_code(405);
    echo json_encode($res);
}
?>