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

function normalize_phone($s) { return preg_replace('/\D+/', '', (string)$s); }

$id    = filterRequest("id");     // أو
$phone = filterRequest("phone");  // أحدهما مطلوب
$reason= filterRequest("reason"); // اختياري
$exp   = filterRequest("expires_at"); // اختياري Y-m-d H:i:s

if (empty($id) && empty($phone)) { jsonError("Provide id or phone"); exit; }

try {
    $con->beginTransaction();

    // احضر السجل
    if (!empty($id)) {
        $sel = $con->prepare("SELECT id, phone FROM passengers WHERE id = :id LIMIT 1");
        $sel->execute(['id' => $id]);
    } else {
        $sel = $con->prepare("SELECT id, phone FROM passengers WHERE phone = :ph LIMIT 1");
        $sel->execute(['ph' => $phone]);
    }
    $p = $sel->fetch(PDO::FETCH_ASSOC);
    if (!$p) { throw new Exception("Passenger not found"); }

    $phRaw = $p['phone'];
    $phNorm= normalize_phone($phRaw);

    // أدخِل/حدّث في البلاك ليست
    $ins = $con->prepare("
        INSERT INTO passenger_blacklist (phone, phone_normalized, reason, expires_at)
        VALUES (:ph, :phn, :r, :exp)
        ON DUPLICATE KEY UPDATE reason = VALUES(reason), expires_at = VALUES(expires_at)
    ");
    $ins->execute([
        'ph'  => $phRaw,
        'phn' => $phNorm,
        'r'   => $reason ?: 'Deleted & blacklisted',
        'exp' => $exp ?: null
    ]);

    // حذف فعلي
    $del = $con->prepare("DELETE FROM passengers WHERE id = :id");
    $del->execute(['id' => $p['id']]);

    $con->commit();
    jsonSuccess(null, "Passenger deleted and blacklisted");
} catch (Throwable $e) {
    $con->rollBack();
    jsonError("Failed: ".$e->getMessage());
}