<?php
// loginWalletAdmin.php (Modified for Intaleq Admin Integration)
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;

include "functions.php";

// --- استدعاء المفاتيح ---
$secretKey = getenv('SECRET_KEY');
$allowed1 = getenv('allowedWallet1');
$allowed2 = getenv('allowedWallet2');
$passwordnewpassenger = getenv('passwordnewpassenger');
$issuer = 'Tripz-Wallet';  
$allowedAudiences = array_filter([$allowed1, $allowed2]);

// --- إعداد رؤوس CORS ---
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *"); // Allow all for admin app or specify domain
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Device-FP");

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

// --- التحقق من المفاتيح ---
if (empty($secretKey) || empty($passwordnewpassenger) || empty($allowedAudiences)) {
    http_response_code(500);
    die(json_encode(['error' => 'Server configuration error']));
}

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

    if (empty($id) || empty($password) || empty($audience) || empty($fingerPrint)) {
        http_response_code(400);
        die(json_encode(['error' => 'Missing required parameters.']));
    }

    if (!in_array($audience, $allowedAudiences)) {
        http_response_code(403);
        die(json_encode(['error' => 'Invalid audience']));
    }

    // --- الاتصال بقاعدة البيانات ---
    $dbuser = getenv('USER');
    $dbpass = getenv('PASS');
    $dbname = getenv('dbname');
    $dsn = "mysql:host=localhost;dbname=$dbname;charset=utf8mb4";

    $con = new PDO($dsn, $dbuser, $dbpass, [
        PDO::ATTR_EMULATE_PREPARES => false,
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]);

    // --- التحقق من الهوية ---
    // تعديل: البحث باستخدام المعرف (id) أو البصمة (fingerprint)
    $stmt = $con->prepare("SELECT * FROM `adminUser` WHERE `username` = ? OR `device_number` = ? LIMIT 1");
    $stmt->execute([$id, $fingerPrint]);
    $user = $stmt->fetch();

    if (!$user) {
        // إذا لم يكن موجوداً، نتحقق من كلمة السر العامة للأدمن كخيار أخير
        if ($id === 'admin' && $password === $passwordnewpassenger) {
            // السماح بالدخول كأدمن عام
        } else {
            http_response_code(403);
            echo json_encode(['error' => 'User not found']);
            exit;
        }
    }

    // --- إنشاء JWT ---
    $payload = [
        'user_id'     => $id,
        'fingerPrint' => $fingerPrint,
        'exp'         => time() + 3600, // زيادة وقت الصلاحية لـ ساعة
        '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,
        'expires_in' => 3600
    ]);
    http_response_code(200);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Unexpected error occurred: ' . $e->getMessage()]);
}
