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

function generateUniqueCode($con, $length = 7) {
    while (true) {
        $letters = substr(str_shuffle("ABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 4);
        $numbers = substr(str_shuffle("0123456789"), 0, 3);
        $code = $letters . $numbers;

        $stmt = $con->prepare("SELECT COUNT(*) FROM invitesToPassengers WHERE inviteCode = ?");
        $stmt->execute([$code]);

        if ($stmt->fetchColumn() == 0) {
            return $code;
        }
    }
}

$driverId = filterRequest("driverId");
$inviterPassengerPhone = filterRequest("inviterPassengerPhone");

if (!$driverId || !$inviterPassengerPhone) {
    jsonError("Missing required parameters: driverId or inviterPassengerPhone");
}

// 🔐 تشفير رقم الهاتف
$inviterPassengerPhoneEncrypted = $encryptionHelper->encryptData($inviterPassengerPhone);

// التحقق من وجود الرقم مسبقًا
$checkSql = "SELECT `id`, `inviteCode`, `isInstall`, `isGiftToken` FROM `invitesToPassengers` WHERE `inviterPassengerPhone` = :inviterPassengerPhone";
$checkStmt = $con->prepare($checkSql);
$checkStmt->bindParam(':inviterPassengerPhone', $inviterPassengerPhoneEncrypted, PDO::PARAM_STR);
$checkStmt->execute();

if ($checkStmt->rowCount() > 0) {
    $existingInvite = $checkStmt->fetch(PDO::FETCH_ASSOC);

    if ($existingInvite['isInstall'] == 1 || $existingInvite['isGiftToken'] == 1) {
        printFailure([
            "message" => "Invite code already used or gift token already applied",
            "inviteCode" => $existingInvite['inviteCode']
        ]);
    } else {
        // تحديث الدعوة
        $updateSql = "UPDATE `invitesToPassengers` SET `driverId` = :driverId, `expirationTime` = :expirationTime, `createdAt` = NOW() WHERE `id` = :id";
        $updateStmt = $con->prepare($updateSql);
        $expirationTime = date('Y-m-d H:i:s', strtotime('+1 hour'));
        $updateStmt->bindParam(':driverId', $driverId, PDO::PARAM_INT);
        $updateStmt->bindParam(':expirationTime', $expirationTime);
        $updateStmt->bindParam(':id', $existingInvite['id'], PDO::PARAM_INT);

        try {
            $updateStmt->execute();
            printSuccess([
                "message" => "Invite updated successfully",
                "inviteId" => $existingInvite['id'],
                "inviteCode" => $existingInvite['inviteCode'],
                "expirationTime" => $expirationTime
            ]);
        } catch (PDOException $e) {
            jsonError("Database error: " . $e->getMessage());
        }
    }
} else {
    // إنشاء دعوة جديدة
    $inviteCode = generateUniqueCode($con);
    $expirationTime = date('Y-m-d H:i:s', strtotime('+4 hour'));

    $sql = "INSERT INTO `invitesToPassengers` 
            (`driverId`, `inviterPassengerPhone`, `inviteCode`, `expirationTime`, `createdAt`, `isInstall`, `isGiftToken`) 
            VALUES 
            (:driverId, :inviterPassengerPhone, :inviteCode, :expirationTime, NOW(), 0, 0)";
    
    $stmt = $con->prepare($sql);
    $stmt->bindParam(':driverId', $driverId, PDO::PARAM_INT);
    $stmt->bindParam(':inviterPassengerPhone', $inviterPassengerPhoneEncrypted, PDO::PARAM_STR);
    $stmt->bindParam(':inviteCode', $inviteCode);
    $stmt->bindParam(':expirationTime', $expirationTime);

    try {
        $stmt->execute();
        if ($stmt->rowCount() > 0) {
            $insertedID = $con->lastInsertId();
            printSuccess([
                "message" => "Invite created successfully",
                "inviteId" => $insertedID,
                "inviteCode" => $inviteCode,
                "expirationTime" => $expirationTime
            ]);
        } else {
            jsonError("Failed to save invite data");
        }
    } catch (PDOException $e) {
        jsonError("Database error: " . $e->getMessage());
    }
}
?>