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

$inviterDriverPhone = filterRequest("inviterDriverPhone");

if (empty($inviterDriverPhone)) {
    jsonError("Invalid or missing inviter phone.");
    exit;
}

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

    // ✅ الآن الاستعلام نظيف وطبيعي جداً لأن قاعدة البيانات تم إصلاحها
    $fetchSql = "SELECT
        i.`id`,
        i.`driverId`,
        i.`inviterDriverPhone`,
        i.`createdAt`,
        i.`inviteCode`,
        i.`isInstall`,
        i.`isGiftToken`,
        i.`expirationTime`,
        dt.token
    FROM `invites` i
    LEFT JOIN `driverToken` dt ON dt.captain_id = i.driverId
    WHERE i.`inviterDriverPhone` = :inviterDriverPhone 
        AND i.`expirationTime` > NOW()";

    $fetchStmt = $con->prepare($fetchSql);
    $fetchStmt->bindParam(':inviterDriverPhone', $inviterDriverPhoneEncrypted);
    $fetchStmt->execute();

    if ($fetchStmt->rowCount() > 0) {
        $invite = $fetchStmt->fetch(PDO::FETCH_ASSOC);

        // فك التشفير
        $invite['inviterDriverPhone'] = $encryptionHelper->decryptData($invite['inviterDriverPhone']);
        if (!empty($invite['token'])) {
            $invite['token'] = $encryptionHelper->decryptData($invite['token']);
        }

        // التحديث
        $updateSql = "UPDATE `invites` SET `isInstall` = 1 WHERE `id` = :id";
        $updateStmt = $con->prepare($updateSql);
        $updateStmt->bindParam(':id', $invite['id'], PDO::PARAM_INT);
        $updateStmt->execute();

        printSuccess("Record found and updated successfully.", $invite);
    } else {
        jsonError("No records found.");
    }

} catch (PDOException $e) {
    error_log("DB Error: " . $e->getMessage());
    jsonError("Database error: " . $e->getMessage());
}
?>