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

$response = [
    'status' => 'error',
    'payment_status' => 'idle',
    'order_id' => 0,
    'order_code' => '',
    'customer_name' => '',
    'customer_phone' => '',
    'total_amount' => 0
];

try {
    $stmt_display = $conn->query("SELECT * FROM cms_payment_display WHERE id = 1");
    if (!$stmt_display) {
        throw new Exception("Không thể truy vấn bảng hiển thị.");
    }
    $display_data = $stmt_display->fetch_assoc();

    if ($display_data) {
        $response = [
            'status' => 'success',
            'payment_status' => $display_data['payment_status'],
            'order_id' => (int)$display_data['order_id'],
            'order_code' => $display_data['order_code'],
            'customer_name' => $display_data['customer_name'],
            'customer_phone' => $display_data['customer_phone'],
            'total_amount' => (float)$display_data['total_amount']
        ];

        if ($response['payment_status'] === 'waiting' && $response['order_id'] > 0) {
            $stmt_order = $conn->prepare("SELECT total_money, customer_pay FROM cms_orders WHERE ID = ? AND deleted = 0");
            if ($stmt_order) {
                $stmt_order->bind_param("i", $response['order_id']);
                $stmt_order->execute();
                $order_result = $stmt_order->get_result()->fetch_assoc();
                $stmt_order->close();

                if ($order_result) {
                    $total_money = (float)$order_result['total_money'];
                    $customer_pay = (float)$order_result['customer_pay'];
                    $debt = $total_money - $customer_pay;

                    if ($debt <= 0) {
                        $conn->query("UPDATE cms_payment_display SET payment_status = 'paid' WHERE id = 1");
                        $response['payment_status'] = 'paid';
                    }
                } else {
                    $conn->query("UPDATE cms_payment_display SET payment_status = 'idle', order_id = 0, order_code = '', customer_name = '', customer_phone = '', total_amount = 0 WHERE id = 1");
                    $response['payment_status'] = 'idle';
                }
            }
        }
    } else {
        $response['message'] = 'Không tìm thấy dữ liệu hiển thị.';
    }

} catch (Exception $e) {
    $response['message'] = $e->getMessage();
}

echo json_encode($response);
?>