<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../../config/database.php';

$response = ["status" => "success", "messages" => []];
try {
    $stmt = $conn->prepare("SELECT id, customer_phone, customer_name, appointment_datetime FROM service_appointments WHERE status = 'pending' LIMIT 10");
    if ($stmt === false) {
        throw new Exception("Prepare failed: " . $conn->error);
    }
    $stmt->execute();
    $result = $stmt->get_result();
    
    while ($row = $result->fetch_assoc()) {
        $customer_name = $row['customer_name'];
        $appointment_time = date('H:i d/m/Y', strtotime($row['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!";

        $response['messages'][] = [
            'id' => $row['id'],
            'to' => $row['customer_phone'],
            'message' => $message,
        ];
    }
    $stmt->close();
} catch (Exception $e) {
    http_response_code(500);
    $response = ["status" => "error", "message" => $e->getMessage()];
}

echo json_encode($response);
$conn->close();
?>