<?php
// ═══════════════════════════════════════════════════════════════
// update_fingerprint_admin.php — تحديث بصمة واحدة (للترحيل)
// ───────────────────────────────────────────────────────────────
// ⚠️ يُستخدم فقط أثناء عملية الترحيل ثم يُحذف
// ═══════════════════════════════════════════════════════════════


require_once __DIR__ . '/../get_connect.php';

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: https://intaleqapp.com');
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;
}

// ── التحقق من admin_key ────────────────────────────────────────
$adminKey         = filterRequest('admin_key') ?? '';
$expectedAdminKey = getenv('MIGRATION_ADMIN_KEY');

if (empty($adminKey) || !hash_equals($expectedAdminKey, $adminKey)) {
    http_response_code(403);
    echo json_encode(['error' => 'Forbidden']);
    exit;
}

try {
    $passengerID = filterRequest('passengerID') ?? '';
    $fingerprint = filterRequest('fingerprint') ?? '';

    if (empty($passengerID) || empty($fingerprint)) {
        http_response_code(400);
        echo json_encode(['error' => 'Missing parameters']);
        exit;
    }

    $stmt = $con->prepare('
        UPDATE tokens
        SET fingerPrint = :fp
        WHERE passengerID = :pid
    ');
    $stmt->execute([
        ':fp'  => $fingerprint,
        ':pid' => $passengerID,
    ]);

    $affected = $stmt->rowCount();

    echo json_encode([
        'status'   => 'success',
        'affected' => $affected,
    ]);
    http_response_code(200);

} catch (Exception $e) {
    error_log('❌ [update_fingerprint_admin] ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['error' => 'Server error']);
}