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

$phoneNumber = filterRequest("phone_number");
$otp = filterRequest("otp");

if (empty($phoneNumber) || empty($otp)) {
    jsonError("Phone number and OTP are required.");
    exit();
}

$phoneNumber_encrypted = $encryptionHelper->encryptData($phoneNumber);
$otp_encrypted = $encryptionHelper->encryptData($otp);

try {
    $stmt = $con->prepare("
        SELECT * FROM token_verification_driver 
        WHERE phone_number = ? AND token = ?
    ");
    $stmt->execute([$phoneNumber_encrypted, $otp_encrypted]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($result) {
        $expiration_time = strtotime($result['expiration_time']);

        if (time() <= $expiration_time) {
            $con->prepare("UPDATE token_verification_driver SET verified = 1 WHERE id = ?")
                ->execute([$result['id']]);

            $driverStmt = $con->prepare("SELECT id FROM driver WHERE phone = ?");
            $driverStmt->execute([$phoneNumber_encrypted]);
            $driver = $driverStmt->fetch(PDO::FETCH_ASSOC);

            if ($driver) {
                $driverID = $driver['id'];
                $newToken = filterRequest("token");
                $fingerPrint = filterRequest("fingerPrint");

                if ($newToken && $fingerPrint) {
                    $tokenEncrypted = $encryptionHelper->encryptData($newToken);

                    $checkTokenStmt = $con->prepare("SELECT id FROM driverToken WHERE captain_id = ?");
                    $checkTokenStmt->execute([$driverID]);

                    if ($checkTokenStmt->rowCount() > 0) {
                        $con->prepare("UPDATE driverToken SET token = ?, fingerPrint = ? WHERE captain_id = ?")
                            ->execute([$tokenEncrypted, $fingerPrint, $driverID]);
                    } else {
                        $con->prepare("INSERT INTO driverToken (token, fingerPrint, captain_id, created_at) VALUES (?, ?, ?, NOW())")
                            ->execute([$tokenEncrypted, $fingerPrint, $driverID]);
                    }

                    $response = [
                        "message" => "Driver token verified and updated.",
                        "isRegistered" => true,
                        "driverID" => $driverID
                    ];
                    jsonSuccess($response);

                } else {
                    jsonError("Token or fingerprint missing.");
                }

            } else {
                printSuccess([
                    "message" => "Phone verified, but driver not found.",
                    "isRegistered" => false
                ]);
            }

        } else {
            jsonError("OTP expired. Request a new one.");
        }

    } else {
        jsonError("Invalid OTP.");
    }

} catch (PDOException $e) {
    jsonError("Database error occurred.");
}