<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/functions.php';

date_default_timezone_set('Asia/Ho_Chi_Minh');
$now = date('Y-m-d H:i:s');
$log_file = __DIR__ . '/cron.log';

function write_log($message) {
    global $log_file;
    $timestamp = date('Y-m-d H:i:s');
    $log_dir = __DIR__;
    if (!file_exists($log_dir)) mkdir($log_dir, 0777, true);
    file_put_contents($log_file, "[$timestamp] " . $message . "\n", FILE_APPEND | LOCK_EX);
    if (!file_exists($log_file)) {
        error_log("Cannot create log file at $log_file");
    }
}

write_log("Cron job started.");

$stmt = $conn->prepare("SELECT * FROM service_appointments WHERE status = 'pending' AND appointment_datetime <= ?");
if ($stmt === false) {
    write_log("Prepare failed: " . $conn->error);
    die("Database error: " . $conn->error);
}
$stmt->bind_param("s", $now);
$stmt->execute();
$appointments_to_send = $stmt->get_result();

if ($appointments_to_send->num_rows > 0) {
    write_log("Found " . $appointments_to_send->num_rows . " appointments to send.");
    while ($appointment = $appointments_to_send->fetch_assoc()) {
        $customer_name = $appointment['customer_name'];
        $appointment_time = date('H:i d/m/Y', strtotime($appointment['appointment_datetime']));
        $message = "SUA XE ABC: Thong bao, xe cua quy khach ($customer_name) da sua xong. Moi quy khach den nhan vao luc $appointment_time. Cam on!";

        write_log("Attempting to send SMS to " . $appointment['customer_phone']);
        $isSent = sendSmsViaMobileApi(
            SMS_GATEWAY_ENDPOINT,
            SMS_GATEWAY_TOKEN,
            $appointment['customer_phone'],
            $message
        );

        if ($isSent) {
            write_log("Command sent successfully for appointment ID: " . $appointment['id']);
            $update_stmt = $conn->prepare("UPDATE service_appointments SET status = 'sent' WHERE id = ?");
            $update_stmt->bind_param("i", $appointment['id']);
            $update_stmt->execute();
        } else {
            global $http_code, $error; // Giả định biến toàn cục từ hàm sendSmsViaMobileApi
            write_log("ERROR: Failed to send command for appointment ID: " . $appointment['id'] . " - HTTP Code: $http_code, Error: $error");
        }
    }
} else {
    write_log("No pending appointments found.");
}

$conn->close();
write_log("Cron job finished.");
?>