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

$phone_number = filterRequest("phone_number");
$token_code = filterRequest("token_code");
$expiration_time = filterRequest("expiration_time"); // Assuming this is a timestamp

// Check if the phone number already exists
$sql = "SELECT * FROM `phone_verification_passenger` WHERE `phone_number` = '$phone_number'";
$stmt = $con->prepare($sql);
$stmt->execute();

$rowCount = $stmt->rowCount();

if ($rowCount > 0) {
    // The phone number already exists, so update the data
    $sql = "UPDATE `phone_verification_passenger` SET `token_code` = '$token_code', `expiration_time` = DATE_ADD(NOW(), INTERVAL 5 MINUTE) WHERE `phone_number` = '$phone_number'";
    $stmt = $con->prepare($sql);
    $stmt->execute();

    if ($stmt->rowCount() > 0) {
        // The update was successful
        jsonSuccess($message = "Phone verification data updated successfully");
    } else {
        // The update was unsuccessful
        jsonError($message = "Failed to update phone verification data");
    }
} else {
    // The phone number does not exist, so insert the data
   $sql = "INSERT INTO `phone_verification_passenger` (`phone_number`, `token_code`, `expiration_time`, `is_verified`, `created_at`) VALUES ('$phone_number', '$token_code', DATE_ADD(NOW(), INTERVAL 5 MINUTE), 0, NOW())";
    $stmt = $con->prepare($sql);
    $stmt->execute();

    if ($stmt->rowCount() > 0) {
        // The insertion was successful
        jsonSuccess($message = "Phone verification data saved successfully");
    } else {
        // The insertion was unsuccessful
        jsonError($message = "Failed to save phone verification data");
    }
}
?>