<?php

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

function generateUniqueCode($con) {
    while (true) {
        $letters = substr(str_shuffle("ABCDEFGHJKLMNPQRSTUVWXYZ"), 0, 2); // Excluded I, O for clarity
        $numbers = substr(str_shuffle("23456789"), 0, 3); // Excluded 0, 1 for clarity
        $code = $letters . $numbers;

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

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

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

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

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

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

    if ($existingInvite['isInstall'] == 1) {
        jsonError($existingInvite['inviteCode']);
    } else {
        // تحديث الدعوة الحالية
        $updateSql = "UPDATE `invites` SET `driverId` = :driverId, `expirationTime` = :expirationTime, `createdAt` = NOW() WHERE `id` = :id";
        $updateStmt = $con->prepare($updateSql);
        $expirationTime = date('Y-m-d H:i:s', strtotime('+24 hours'));
        $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('+24 hours'));

    $sql = "INSERT INTO `invites` (`driverId`, `inviterDriverPhone`, `inviteCode`, `expirationTime`, `createdAt`, `isInstall`) 
            VALUES (:driverId, :inviterDriverPhone, :inviteCode, :expirationTime, NOW(), 0)";
    $stmt = $con->prepare($sql);
    $stmt->bindParam(':driverId', $driverId, PDO::PARAM_INT);
    $stmt->bindParam(':inviterDriverPhone', $inviterDriverPhoneEncrypted, 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());
    }
}
?>