<?php

require_once realpath(__DIR__ . '/../vendor/autoload.php');
require_once 'load_env.php';
$env_file = '/home/intaleq-wallet/env/.env';
loadEnvironment($env_file);

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

// Retrieve environment variables
//$secretKey = getenv('SECRET_KEY');
$secretKey = trim(file_get_contents('/home/intaleq-wallet/.secret_key'));
$allowed1 = getenv('allowedWallet1');
$allowed2 = getenv('allowedWallet2');
$issuer = 'Tripz-Wallet';  
$allowedAudiences = array_filter([$allowed1, $allowed2]);  
$passwordnewpassenger = getenv('passwordnewpassenger');

include "functions.php";

// Validate environment variables
if (empty($secretKey) || empty($passwordnewpassenger) || empty($allowedAudiences)) {
    http_response_code(500);
    die(json_encode(['error' => 'Server configuration error: Missing environment variables.']));
}

// CORS Headers
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: https://walletintaleq.intaleq.xyz");  
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

try {
    $id = filterRequest('id') ?? '';
    $password = filterRequest('password') ?? '';
    $audience = filterRequest('aud') ?? '';
    $fingerPrint = filterRequest('fingerPrint');

    // Input validation
    if (empty($id) || empty($password) || empty($audience) || empty($fingerPrint)) {
        die(json_encode(['error' => 'Missing required parameters.']));
    }
    if (!in_array($audience, $allowedAudiences)) {
        http_response_code(400);
        die(json_encode(['error' => 'Invalid audience']));
    }
 /*
    // Database connection
    $dbuser = getenv('USER');
    $dbpass = getenv('PASS');
    $dbname = getenv('dbname');  
    $dsn = "mysql:host=localhost;dbname=$dbname;charset=utf8mb4";
    $options = [
        PDO::ATTR_EMULATE_PREPARES => false,
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ];
    $con = new PDO($dsn, $dbuser, $dbpass, $options);

    // Fetch token data from database
    $stmt = $con->prepare("SELECT `id`, `token`, `captain_id`, `fingerPrint` FROM `driverToken` WHERE `captain_id` = :captain_id");
    $stmt->bindParam(':captain_id', $id, PDO::PARAM_STR);
    $stmt->execute();
    $tokenData = $stmt->fetch(PDO::FETCH_ASSOC);

 
// 1) يجب وجود سجل
			if (!$tokenData) {
			    http_response_code(403);
 			   die(json_encode(['error' => 'No token record found for this user.']));
			}

  if (empty($tokenData['fingerPrint']) || !hash_equals($tokenData['fingerPrint'], $fingerPrint)) {
    http_response_code(403);
    die(json_encode(['error' => 'Device fingerprint verification failed']));
}

    */

    // JWT Payload
    $payload = [
        'user_id' => $id,
        'fingerPrint' => $fingerPrint,
        'exp' => time() + 60,
        'iat' => time(),
        'iss' => $issuer,
        'aud' => $audience
    ];


    // Ensure secret key is valid before encoding
    if (empty($secretKey)) {
        throw new Exception("SECRET_KEY is empty.");
    }

    // Encode JWT
    $jwt = JWT::encode($payload, $secretKey, 'HS256');
    $hmac = hash_hmac('sha256', $id, getenv('SECRET_KEY_HMAC'));
    echo json_encode([
        'status' => 'success',
        'jwt' => $jwt,
        'hmac' => $hmac,
        'expires_in' => 60
    ]);
    http_response_code(200);

} catch (Exception $e) {
    http_response_code(500);
    echo "🔥 Server error: " . $e->getMessage() . "\n";
    echo json_encode(['error' => 'An unexpected error occurred.']);
}