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

$phone_number = filterRequest("phone_number");
$token_code = filterRequest("token");

// Check if the phone number and token code match
$sql = "SELECT
    `id`,
    `phone_number`,
    `token`,
    `expiration_time`,
    `verified`,
    `created_at`
FROM
    `phone_verification_passenger`
WHERE
    `phone_number` = :phone_number AND `token` = :token_code";

$stmt = $con->prepare($sql);

// Log the parameters used in the SQL query for debugging
error_log("Executing SELECT SQL: " . $sql . " with phone_number=" . $phone_number . " and token_code=" . $token_code);

$stmt->bindParam(':phone_number', $phone_number, PDO::PARAM_STR);
$stmt->bindParam(':token_code', $token_code, PDO::PARAM_STR);

if ($stmt->execute()) {
    $result = $stmt->fetch();

    if ($result) {
        // Update the verified status
        $sql = "UPDATE `phone_verification_passenger` SET `verified` = 1 WHERE `phone_number` = :phone_number";
        $stmt = $con->prepare($sql);

        // Log the update query execution
        error_log("Executing UPDATE SQL: " . $sql . " with phone_number=" . $phone_number);

        $stmt->bindParam(':phone_number', $phone_number, PDO::PARAM_STR);
        
        if ($stmt->execute()) {
            jsonSuccess(null, "Your phone number has been verified.");
        } else {
            // Log if the update query fails
            error_log("Error executing UPDATE SQL: " . implode(", ", $stmt->errorInfo()));
            jsonError("An error occurred while verifying your phone number. Please try again.");
        }

    } else {
        // Log if no matching record was found
        error_log("No matching record found for phone_number=" . $phone_number . " and token_code=" . $token_code);
        jsonError("Your phone number could not be verified. Please try again.");
    }

} else {
    // Log if the select query fails
    error_log("Error executing SELECT SQL: " . implode(", ", $stmt->errorInfo()));
    jsonError("An error occurred while verifying your phone number. Please try again.");
}
?>