<?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 - Check for existence
//$secretKey = getenv('SECRET_KEY');
$secretKey = trim(file_get_contents('/home/intaleq-wallet/.secret_key'));
$allowed1 = getenv('allowed1');
$allowed2 = getenv('allowed2');

// $allowed1 = getenv('allowedWallet1');
// $allowed2 = getenv('allowedWallet2');

$issuer = 'Tripz-Wallet';  // You might want to put this in the .env file too
$allowedAudiences = [$allowed1, $allowed2];
$passwordnewpassenger = getenv('passwordnewpassenger');  // Hashed password

// include "connect.php";
include "functions.php";


// Validate that required environment variables are set
if (!$secretKey || !$passwordnewpassenger || empty($allowedAudiences)) {
    error_log("Missing required environment variables.");
    http_response_code(500);
    exit(json_encode(['error' => 'Server configuration error: Missing environment variables.']));
}

// CORS Headers - Be specific in production
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: https://wallet.sefer.live");  // Replace * with your Flutter app's origin
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

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

try {
    $id = filterRequest('id') ?? '';
    $password = filterRequest('password') ?? '';
    $audience = filterRequest('aud') ?? '';
    $dbname = getenv('dbname');
    // Input validation - More specific
    if (empty($id)) {
        throw new InvalidArgumentException("ID is required.");
    }
    if (empty($password)) {
        throw new InvalidArgumentException("Password is required.");
    }
    if (empty($audience)) {
        throw new InvalidArgumentException("Audience is required.");
    }
    if (!in_array($audience, $allowedAudiences)) {
        http_response_code(400); // Bad Request
        exit(json_encode(['error' => 'Invalid audience']));
    }

$fingerPrint = filterRequest('fingerPrint') ?? '';

if (empty($fingerPrint)) {
    throw new InvalidArgumentException("Device fingerprint is required.");
}
$dbuser = getenv('USER');    // Get DB user here, consistent naming
$dbpass = getenv('PASS');    // Get DB password here
 if (password_verify($password, $passwordnewpassenger)) {
// Fetch token data from the database
$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,
        PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES UTF8"
    ];
    $con = new PDO($dsn, $dbuser, $dbpass, $options);
    $sql = "SELECT `id`, `token`, `passengerID`, `fingerPrint` FROM `tokens` WHERE `passengerID` = :passengerID";
    $stmt = $con->prepare($sql);
    $stmt->bindParam(':passengerID', $id, PDO::PARAM_STR);
    $stmt->execute();
    $tokenData = $stmt->fetch(PDO::FETCH_ASSOC);



  /*

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

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

$jwt = JWT::encode($payload, $secretKey, 'HS256');
$hmac = hash_hmac('sha256', $id, getenv('SECRET_KEY_HMAC'));

        echo json_encode([
            'status' => 'success',
            'jwt' => $jwt,
            'hmac' => $hmac,
            // 'refresh_token' => $refreshToken,
            'expires_in' => 300
        ]);
        http_response_code(200);

 }else{
     echo 'fffff';
 }

} catch (InvalidArgumentException $e) {
    // Handle input validation errors
    http_response_code(400); // Bad Request - Client-side error
  //  error_log("Input validation error: " . $e->getMessage());  // Log for debugging
    echo json_encode(['error' => $e->getMessage()]);  // Specific error message
} catch (Exception $e) {
    // Handle other exceptions (e.g., JWT encoding errors)
    http_response_code(500); // Internal Server Error
  //  error_log("Server error: " . $e->getMessage()); // Log for debugging
    echo json_encode(['error' => 'An unexpected error occurred.']); // Generic message
}