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

$inviteCode = filterRequest("inviteCode");

if (empty($inviteCode)) {
    jsonError("Invalid or missing invite code.");
    exit;
}

try {
    $checkSql = "SELECT `id`, `expirationTime`, `driverId` FROM `invites` 
                 WHERE `inviteCode` = :inviteCode 
                 AND `isInstall` = 0 
                 AND `expirationTime` > NOW()";
    
    $checkStmt = $con->prepare($checkSql);
    $checkStmt->bindParam(':inviteCode', $inviteCode);
    $checkStmt->execute();
    
    if ($checkStmt->rowCount() > 0) {
        $invite = $checkStmt->fetch(PDO::FETCH_ASSOC);

        $updateSql = "UPDATE `invites` SET `isInstall` = 1 WHERE `id` = :id";
        $updateStmt = $con->prepare($updateSql);
        $updateStmt->bindParam(':id', $invite['id'], PDO::PARAM_INT);
        $updateStmt->execute();

        if ($updateStmt->rowCount() > 0) {
            printSuccess([
                "message" => "Invite code successfully used and marked as installed.",
                "driverId" => $invite['driverId'],
                "expirationTime" => $invite['expirationTime']
            ]);
        } else {
            jsonError("Failed to update the invite record.");
        }
    } else {
        jsonError("Invalid invite code, already installed, or expired.");
    }
} catch (PDOException $e) {
    jsonError("Database error: " . $e->getMessage());
}
?>