<?php
/**
 * ============================================================
 * SYNC_REPORT.PHP - Client Side (localhost)
 * Letakkan di folder escobarweb/
 * 
 * Dipanggil via AJAX dari index.php setiap 5 menit
 * untuk mengirim data omset ke server online.
 * ============================================================
 */
ob_start();
include 'config.php';

header('Content-Type: application/json');

$license_key = get_setting($conn, 'license_key');
$report_url  = 'https://escobargame.site/report/api.php';

if (empty($license_key)) {
    echo json_encode(['status' => 'error', 'msg' => 'No license key']);
    exit;
}

$today = date('Y-m-d');

// ============================================================
// 1. QUERY OMSET HARI INI
// ============================================================

// --- Billing / Rental ---
$q1   = $conn->query("SELECT COALESCE(SUM(total_bayar),0) as total, COUNT(*) as cnt 
                       FROM transactions 
                       WHERE DATE(end_time) = '$today' AND status='completed'");
$bill = $q1->fetch_assoc();

// --- F&B: orders_fnb (dari TV) ---
$q2a  = $conn->query("SELECT COALESCE(SUM(total_harga),0) as total, COUNT(*) as cnt 
                       FROM orders_fnb 
                       WHERE DATE(created_at) = '$today'");
$fnb1 = $q2a->fetch_assoc();

// --- F&B: snack_sales (dari kasir langsung) ---
$q2b  = $conn->query("SELECT COALESCE(SUM(total),0) as total, COUNT(*) as cnt 
                       FROM snack_sales 
                       WHERE DATE(created_at) = '$today'");
$fnb2 = $q2b ? $q2b->fetch_assoc() : ['total' => 0, 'cnt' => 0];

// Gabungkan kedua sumber F&B
$fnb = [
    'total' => (int)$fnb1['total'] + (int)$fnb2['total'],
    'cnt'   => (int)$fnb1['cnt']   + (int)$fnb2['cnt'],
];

// --- Top Up Member ---
$q3   = $conn->query("SELECT COALESCE(SUM(amount),0) as total, COUNT(*) as cnt 
                       FROM member_topups 
                       WHERE DATE(created_at) = '$today'");
$topup = $q3 ? $q3->fetch_assoc() : ['total' => 0, 'cnt' => 0];

$grand = (int)$bill['total'] + (int)$fnb['total'] + (int)$topup['total'];

// ============================================================
// 2. DETAIL PER TV
// ============================================================
$tv_details = [];
$q4 = $conn->query("
    SELECT t.tv_id, tv.nama_tv, 
           COUNT(*) as total_trx, 
           SUM(t.total_bayar) as total_revenue,
           SUM(TIMESTAMPDIFF(MINUTE, t.start_time, COALESCE(t.end_time, NOW()))) as total_menit
    FROM transactions t 
    JOIN tvs tv ON t.tv_id = tv.id
    WHERE DATE(t.start_time) = '$today' AND t.status = 'completed'
    GROUP BY t.tv_id, tv.nama_tv
    ORDER BY tv.nama_tv
");
if ($q4) {
    while ($row = $q4->fetch_assoc()) {
        $tv_details[] = [
            'nama_tv'     => $row['nama_tv'],
            'total_trx'   => (int)$row['total_trx'],
            'revenue'     => (int)$row['total_revenue'],
            'total_menit' => (int)$row['total_menit'],
        ];
    }
}

// ============================================================
// 3. STATUS TV REALTIME
// ============================================================
$tv_status = [];
$q5 = $conn->query("SELECT id, nama_tv, status, ip_address FROM tvs ORDER BY nama_tv");
if ($q5) {
    while ($row = $q5->fetch_assoc()) {
        $tv_status[] = [
            'nama_tv' => $row['nama_tv'],
            'status'  => $row['status'],
        ];
    }
}

// ============================================================
// 4. KIRIM KE SERVER
// ============================================================
$payload = [
    'action'      => 'sync',
    'license_key' => $license_key,
    'report_date' => $today,
    'data'        => json_encode([
        'total_billing'  => (int)$bill['total'],
        'total_fnb'      => (int)$fnb['total'],
        'total_topup'    => (int)$topup['total'],
        'grand_total'    => $grand,
        'count_billing'  => (int)$bill['cnt'],
        'count_fnb'      => (int)$fnb['cnt'],
        'count_topup'    => (int)$topup['cnt'],
        'tv_details'     => $tv_details,
        'tv_status'      => $tv_status,
    ]),
];

$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL            => $report_url,
    CURLOPT_POST           => 1,
    CURLOPT_POSTFIELDS     => http_build_query($payload),
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_TIMEOUT        => 15,
    CURLOPT_SSL_VERIFYPEER => 0,
]);
$res       = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$err       = curl_error($ch);
curl_close($ch);

if ($http_code == 200 && $res) {
    $result = json_decode($res, true);
    echo json_encode([
        'status'          => 'success',
        'server_response' => $result,
        'debug'           => [
            'billing'  => $bill['total'],
            'fnb'      => $fnb['total'],
            'fnb_tv'   => $fnb1['total'],
            'fnb_kasir'=> $fnb2['total'],
            'topup'    => $topup['total'],
            'grand'    => $grand,
        ],
    ]);
} else {
    echo json_encode([
        'status'     => 'error',
        'msg'        => 'Sync failed',
        'http_code'  => $http_code,
        'curl_error' => $err,
    ]);
}

ob_end_flush();