<?php

require_once __DIR__ . '/../../connect.php';

$token        = filterRequest("token");       // نص عادي ➜ سيتم تشفيره
$captain_id   = filterRequest("captain_id");  // ID
$fingerPrint  = filterRequest("fingerPrint"); // مشفّر مسبقًا من Flutter

// تشفير التوكن فقط
$tokenEncrypted = $encryptionHelper->encryptData($token);

// التحقق مما إذا كان السجل موجودًا
$sqlCheck = "SELECT * FROM `driverToken` WHERE `captain_id` = :captain_id";
$stmtCheck = $con->prepare($sqlCheck);
$stmtCheck->bindParam(':captain_id', $captain_id);
$stmtCheck->execute();

$result = $stmtCheck->fetch(PDO::FETCH_ASSOC);

if ($result) {
    // تحديث السجل
    $sqlUpdate = "UPDATE `driverToken` SET `token` = :token, `fingerPrint` = :fingerPrint WHERE `captain_id` = :captain_id";
    $stmtUpdate = $con->prepare($sqlUpdate);
    $stmtUpdate->bindParam(':token', $tokenEncrypted);
    $stmtUpdate->bindParam(':fingerPrint', $fingerPrint); // بدون إعادة تشفير
    $stmtUpdate->bindParam(':captain_id', $captain_id);
    $stmtUpdate->execute();

    jsonSuccess(null, "Token updated successfully");

} else {
    // إدخال سجل جديد
    $sqlInsert = "INSERT INTO `driverToken` (`token`, `captain_id`, `fingerPrint`) VALUES (:token, :captain_id, :fingerPrint)";
    $stmtInsert = $con->prepare($sqlInsert);
    $stmtInsert->bindParam(':token', $tokenEncrypted);
    $stmtInsert->bindParam(':captain_id', $captain_id);
    $stmtInsert->bindParam(':fingerPrint', $fingerPrint); // بدون إعادة تشفير
    $stmtInsert->execute();

    if ($stmtInsert->rowCount() > 0) {
        jsonSuccess(null, "Token inserted successfully");
    } else {
        jsonError("Failed to insert token");
    }
}
?>