<?php
/**
 * ============================================================
 * SYNC_REPORT.PHP - Client Side (localhost)
 * Letakkan di folder escobarweb/
 *
 * Dipanggil via AJAX dari index.php setiap 5 menit.
 *
 * FITUR:
 * - Sync hari ini (setiap 5 menit)
 * - Sync kemarin (setiap 5 menit, agar data final)
 * - Backfill 7 hari ke belakang (sekali per hari)
 *   Penanda disimpan di file .last_backfill (tidak butuh DB)
 * ============================================================
 */
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;
}

// ── Fungsi sync satu tanggal ke server ──
function syncTanggal(mysqli $conn, string $license_key, string $report_url, string $tanggal): array
{
    // BILLING
    $q1   = $conn->query("SELECT COALESCE(SUM(total_bayar),0) as total, COUNT(*) as cnt
                           FROM transactions
                           WHERE DATE(end_time)='$tanggal' AND status='completed'");
    $bill = $q1->fetch_assoc();

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

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

    $fnb   = [
        'total' => (int)$fnb1['total'] + (int)$fnb2['total'],
        'cnt'   => (int)$fnb1['cnt']   + (int)$fnb2['cnt'],
    ];

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

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

    // TV DETAILS — filter DATE(end_time) identik dengan history.php
    $tv_details = [];
    $q4 = $conn->query("
        SELECT tv.nama_tv, COUNT(*) as total_trx,
               SUM(t.total_bayar) as total_revenue,
               SUM(TIMESTAMPDIFF(MINUTE, t.start_time, t.end_time)) as total_menit
        FROM transactions t JOIN tvs tv ON t.tv_id = tv.id
        WHERE DATE(t.end_time) = '$tanggal' AND t.status = 'completed'
        GROUP BY t.tv_id, tv.nama_tv ORDER BY tv.nama_tv");
    if ($q4) while ($r = $q4->fetch_assoc()) {
        $tv_details[] = [
            'nama_tv'     => $r['nama_tv'],
            'total_trx'   => (int)$r['total_trx'],
            'revenue'     => (int)$r['total_revenue'],
            'total_menit' => (int)$r['total_menit'],
        ];
    }

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

    // KIRIM KE SERVER
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL            => $report_url,
        CURLOPT_POST           => 1,
        CURLOPT_POSTFIELDS     => http_build_query([
            'action'      => 'sync',
            'license_key' => $license_key,
            'report_date' => $tanggal,
            'data'        => json_encode([
                'report_date'   => $tanggal,
                '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,
            ]),
        ]),
        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);

    $result = json_decode($res, true);
    $ok     = ($http_code == 200 && ($result['status'] ?? '') === 'success');

    return [
        'tanggal'   => $tanggal,
        'ok'        => $ok,
        'billing'   => (int)$bill['total'],
        'fnb'       => (int)$fnb['total'],
        'fnb_tv'    => (int)$fnb1['total'],
        'fnb_kasir' => (int)$fnb2['total'],
        'topup'     => (int)$topup['total'],
        'grand'     => $grand,
        'http_code' => $http_code,
        'curl_err'  => $err,
    ];
}

$today     = date('Y-m-d');
$yesterday = date('Y-m-d', strtotime('-1 day'));
$results   = [];

// ── 1. SELALU SYNC HARI INI ──
$results['today'] = syncTanggal($conn, $license_key, $report_url, $today);

// ── 2. SELALU SYNC KEMARIN ──
$results['yesterday'] = syncTanggal($conn, $license_key, $report_url, $yesterday);

// ── 3. AUTO-BACKFILL 7 HARI KE BELAKANG ──
// Pakai file .last_backfill sebagai penanda — tidak butuh kolom DB apapun
$backfill_file = __DIR__ . '/.last_backfill';
$last_backfill = @file_get_contents($backfill_file);
$last_backfill = $last_backfill ? trim($last_backfill) : '';

if ($last_backfill !== $today) {
    $backfill_results = [];
    for ($i = 2; $i <= 7; $i++) {
        $tgl = date('Y-m-d', strtotime("-$i days"));
        $r   = syncTanggal($conn, $license_key, $report_url, $tgl);
        $backfill_results[] = $r;
        usleep(100000); // 0.1 detik jeda
    }
    $results['backfill'] = $backfill_results;

    // Simpan tanggal backfill terakhir ke file
    @file_put_contents($backfill_file, $today);
}

// ── RESPONSE ──
$today_result = $results['today'];

if ($today_result['ok']) {
    echo json_encode([
        'status'          => 'success',
        'server_response' => ['status' => 'success'],
        'debug'           => [
            'date'      => $today,
            'billing'   => $today_result['billing'],
            'fnb'       => $today_result['fnb'],
            'fnb_tv'    => $today_result['fnb_tv'],
            'fnb_kasir' => $today_result['fnb_kasir'],
            'topup'     => $today_result['topup'],
            'grand'     => $today_result['grand'],
            'backfill'  => isset($results['backfill'])
                ? count($results['backfill']) . ' hari di-backfill'
                : 'skip (sudah backfill hari ini)',
        ],
    ]);
} else {
    echo json_encode([
        'status'     => 'error',
        'msg'        => 'Sync hari ini gagal',
        'http_code'  => $today_result['http_code'],
        'curl_error' => $today_result['curl_err'],
    ]);
}

ob_end_flush();