<?php
ob_start();
include 'config.php';
checkLogin();

$page_title  = "Laporan ke WA Admin";
$active_page = "laporan_wa";
include 'layout.php';

$wa_admin = get_setting($conn, 'wa_admin_number') ?: '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_wa'])) {
    $wa_num = preg_replace('/[^0-9]/', '', $_POST['wa_number'] ?? '');
    if (strlen($wa_num) >= 10) {
        $stmt = $conn->prepare("INSERT INTO system_settings (setting_name, setting_value) VALUES ('wa_admin_number', ?) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)");
        $stmt->bind_param("s", $wa_num);
        $stmt->execute();
        $stmt->close();
        $wa_admin = $wa_num;
        $save_ok  = true;
        get_setting($conn, 'wa_admin_number', true);
    } else {
        $save_err = "Nomor WA tidak valid.";
    }
}

$report_sent = false;
$report_msg  = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_report'])) {
    $tipe = $_POST['tipe_laporan'] ?? 'harian';
    $today = date('Y-m-d');

    $r1 = $conn->query("SELECT COALESCE(SUM(total_bayar),0) AS tot FROM transactions WHERE DATE(end_time) = '$today' AND status='completed'");
    $pb  = $r1->fetch_assoc()['tot'] ?? 0;

    $r2 = $conn->query("SELECT COALESCE(SUM(total_harga),0) AS tot FROM orders_fnb WHERE DATE(created_at) = '$today'");
    $pf  = $r2->fetch_assoc()['tot'] ?? 0;

    $r3 = $conn->query("SELECT COUNT(*) AS tot FROM tvs WHERE status='active'");
    $ua  = $r3->fetch_assoc()['tot'] ?? 0;

    $r4 = $conn->query("SELECT COUNT(*) AS tot FROM tvs");
    $tu  = $r4->fetch_assoc()['tot'] ?? 0;

    $r5 = $conn->query("SELECT COUNT(*) AS tot FROM transactions WHERE DATE(end_time) = '$today' AND status='completed'");
    $jt  = $r5->fetch_assoc()['tot'] ?? 0;

    $waktu_kirim = date('d/m/Y H:i:s', time());
    $pengirim    = $_SESSION['username'] ?? 'Operator';

    $teks = urlencode(
        "📊 *LAPORAN " . strtoupper($tipe) . " - ESCOBAR TV*\n" .
        "━━━━━━━━━━━━━━━━━━━━━━\n" .
        "🗓️ Tanggal   : " . date('d/m/Y') . "\n" .
        "⏰ Jam Kirim  : $waktu_kirim\n" .
        "👤 Pengirim   : $pengirim\n\n" .
        "💰 *PENDAPATAN HARI INI*\n" .
        "  • Billing : Rp " . number_format($pb, 0, ',', '.') . "\n" .
        "  • FnB     : Rp " . number_format($pf, 0, ',', '.') . "\n" .
        "  ─────────────────────\n" .
        "  *Total    : Rp " . number_format($pb + $pf, 0, ',', '.') . "*\n\n" .
        "🎮 *STATUS UNIT*\n" .
        "  • Aktif / Bermain : $ua\n" .
        "  • Total Unit      : $tu\n\n" .
        "🧾 Transaksi Selesai : $jt\n" .
        "━━━━━━━━━━━━━━━━━━━━━━\n" .
        "_Laporan otomatis dari Escobar Web_"
    );

    $wa_target = preg_replace('/[^0-9]/', '', $wa_admin);
    if (!empty($wa_target)) {
        $wa_url      = "https://wa.me/$wa_target?text=$teks";
        $report_sent = true;
        $report_msg  = $wa_url;
        write_log($conn, 'LAPORAN_WA', "Kirim laporan $tipe ke WA $wa_target");
    } else {
        $report_err = "Nomor WA admin belum diatur. Simpan dulu di bawah.";
    }
}
?>

<style>
.wa-wrap { display:flex; flex-direction:column; gap:28px; max-width:900px; }
.wa-card { background:var(--card-bg); border:1px solid var(--border); border-radius:20px; padding:32px; }
.wa-card h3 { font-size:1.1rem; font-weight:800; color:#fff; display:flex; align-items:center; gap:10px; margin-bottom:22px; }
.wa-card h3 i { color:var(--primary); font-size:1.4rem; }
.stat-row { display:grid; grid-template-columns:repeat(auto-fit,minmax(160px,1fr)); gap:16px; margin-bottom:24px; }
.stat-box { background:rgba(6,182,212,0.06); border:1px solid rgba(6,182,212,0.18); border-radius:14px; padding:18px; text-align:center; }
.stat-box .val { font-size:1.4rem; font-weight:800; color:var(--primary); font-family:'JetBrains Mono',monospace; }
.stat-box .lbl { font-size:0.72rem; color:var(--text-muted); text-transform:uppercase; margin-top:4px; font-weight:600; }
.btn-wa { background:#25d366!important; color:#fff!important; padding:14px 28px; border-radius:12px; border:none; font-weight:700; font-size:0.95rem; display:inline-flex; align-items:center; gap:10px; cursor:pointer; text-decoration:none; transition:.3s; }
.btn-wa:hover { filter:brightness(1.1); transform:translateY(-2px); box-shadow:0 6px 20px rgba(37,211,102,.3); }
.input-row { display:flex; gap:12px; align-items:center; flex-wrap:wrap; }
.badge-ok { background:rgba(16,185,129,.15); color:#10b981; padding:6px 14px; border-radius:8px; font-size:.82rem; font-weight:700; display:inline-flex; align-items:center; gap:6px; }
.badge-err { background:rgba(239,68,68,.15); color:#ef4444; padding:6px 14px; border-radius:8px; font-size:.82rem; font-weight:700; display:inline-flex; align-items:center; gap:6px; }
.tipe-select { display:flex; gap:10px; flex-wrap:wrap; margin-bottom:20px; }
.tipe-btn { padding:10px 22px; border-radius:10px; border:1px solid var(--border); background:transparent; color:var(--text-muted); cursor:pointer; font-weight:600; font-size:0.85rem; transition:.3s; }
.tipe-btn.active, .tipe-btn:hover { border-color:var(--primary); color:var(--primary); background:rgba(6,182,212,.08); }
.preview-box { background:#0f172a; border:1px solid var(--border); border-radius:14px; padding:20px; font-family:'JetBrains Mono',monospace; font-size:0.82rem; color:#94a3b8; line-height:1.8; white-space:pre-line; margin-bottom:20px; }
</style>

<?php
$today = date('Y-m-d');
$r1 = $conn->query("SELECT COALESCE(SUM(total_bayar),0) AS tot FROM transactions WHERE DATE(end_time)='$today' AND status='completed'");
$pb  = $r1->fetch_assoc()['tot'] ?? 0;
$r2  = $conn->query("SELECT COALESCE(SUM(total_harga),0) AS tot FROM orders_fnb WHERE DATE(created_at)='$today'");
$pf  = $r2->fetch_assoc()['tot'] ?? 0;
$r3  = $conn->query("SELECT COUNT(*) AS tot FROM tvs WHERE status='active'");
$ua  = $r3->fetch_assoc()['tot'] ?? 0;
$r4  = $conn->query("SELECT COUNT(*) AS tot FROM tvs");
$tu  = $r4->fetch_assoc()['tot'] ?? 0;
$r5  = $conn->query("SELECT COUNT(*) AS tot FROM transactions WHERE DATE(end_time)='$today' AND status='completed'");
$jt  = $r5->fetch_assoc()['tot'] ?? 0;
?>

<div class="wa-wrap">

<?php if (!empty($save_ok)): ?>
<div class="badge-ok"><i class='bx bx-check-circle'></i> Nomor WA admin berhasil disimpan!</div>
<?php endif; ?>
<?php if (!empty($report_err)): ?>
<div class="badge-err"><i class='bx bx-error-circle'></i> <?= htmlspecialchars($report_err) ?></div>
<?php endif; ?>

<!-- CARD: Kirim Laporan -->
<div class="wa-card">
    <h3><i class='bx bxl-whatsapp'></i> Kirim Laporan ke WA Admin</h3>

    <div class="stat-row">
        <div class="stat-box">
            <div class="val">Rp <?= number_format($pb + $pf, 0, ',', '.') ?></div>
            <div class="lbl">Total Hari Ini</div>
        </div>
        <div class="stat-box">
            <div class="val"><?= $ua ?>/<?= $tu ?></div>
            <div class="lbl">Unit Aktif</div>
        </div>
        <div class="stat-box">
            <div class="val"><?= $jt ?></div>
            <div class="lbl">Transaksi Selesai</div>
        </div>
        <div class="stat-box">
            <div class="val" style="color:<?= empty($wa_admin) ? '#ef4444' : '#10b981' ?>">
                <?= empty($wa_admin) ? '✗' : '✓' ?>
            </div>
            <div class="lbl">WA Admin <?= empty($wa_admin) ? 'Belum Diatur' : 'Sudah Diatur' ?></div>
        </div>
    </div>

    <div class="preview-box">📊 LAPORAN HARIAN - ESCOBAR TV
━━━━━━━━━━━━━━━━━━━━━━
🗓️ Tanggal   : <?= date('d/m/Y') ?>

⏰ Jam Kirim  : <?= date('d/m/Y H:i:s') ?>

👤 Pengirim   : <?= htmlspecialchars($_SESSION['username'] ?? 'Operator') ?>


💰 PENDAPATAN HARI INI
  • Billing : Rp <?= number_format($pb, 0, ',', '.') ?>

  • FnB     : Rp <?= number_format($pf, 0, ',', '.') ?>

  ─────────────────────
  Total     : Rp <?= number_format($pb + $pf, 0, ',', '.') ?>


🎮 STATUS UNIT
  • Aktif / Bermain : <?= $ua ?>

  • Total Unit      : <?= $tu ?>


🧾 Transaksi Selesai : <?= $jt ?>

━━━━━━━━━━━━━━━━━━━━━━
_Laporan otomatis dari Escobar Web_</div>

    <form method="POST" id="form-laporan">
        <input type="hidden" name="send_report" value="1">
        <input type="hidden" name="tipe_laporan" id="tipe_laporan" value="harian">
        <div class="tipe-select">
            <button type="button" class="tipe-btn active" onclick="setTipe('harian',this)">📅 Harian</button>
            <button type="button" class="tipe-btn" onclick="setTipe('shift',this)">🔄 Per Shift</button>
            <button type="button" class="tipe-btn" onclick="setTipe('mingguan',this)">📆 Mingguan</button>
        </div>

        <?php if ($report_sent && !empty($report_msg)): ?>
        <div class="badge-ok" style="margin-bottom:16px;"><i class='bx bx-check-circle'></i> Laporan siap! Klik tombol untuk membuka WhatsApp.</div>
        <a href="<?= htmlspecialchars($report_msg) ?>" target="_blank" class="btn-wa">
            <i class='bx bxl-whatsapp' style="font-size:1.4rem;"></i> Buka WhatsApp &amp; Kirim
        </a>
        <?php else: ?>
        <button type="submit" class="btn-wa" <?= empty($wa_admin) ? 'disabled style="opacity:.5;cursor:not-allowed;"' : '' ?>>
            <i class='bx bxl-whatsapp' style="font-size:1.4rem;"></i> Kirim Laporan via WhatsApp
        </button>
        <?php if (empty($wa_admin)): ?>
        <small style="color:#f59e0b;display:block;margin-top:10px;"><i class='bx bx-info-circle'></i> Simpan nomor WA admin dulu di bawah sebelum bisa kirim.</small>
        <?php endif; ?>
        <?php endif; ?>
    </form>
</div>

<!-- CARD: Pengaturan Nomor WA -->
<div class="wa-card">
    <h3><i class='bx bx-cog'></i> Pengaturan Nomor WA Admin</h3>
    <form method="POST">
        <input type="hidden" name="save_wa" value="1">
        <label style="color:var(--text-muted);font-size:.85rem;font-weight:600;display:block;margin-bottom:8px;">Nomor WhatsApp Admin (format: 628xxxx)</label>
        <div class="input-row">
            <input type="text" name="wa_number" placeholder="Contoh: 6281234567890"
                value="<?= htmlspecialchars($wa_admin) ?>"
                style="max-width:360px;" required>
            <button type="submit" class="btn btn-primary">
                <i class='bx bx-save'></i> Simpan
            </button>
        </div>
        <?php if (!empty($save_err)): ?>
        <div class="badge-err" style="margin-top:10px;"><?= htmlspecialchars($save_err) ?></div>
        <?php endif; ?>
        <small style="color:var(--text-muted);display:block;margin-top:8px;">Diawali 62 (kode negara Indonesia), tanpa + atau spasi.</small>
    </form>
</div>

</div>

<script>
function setTipe(val, el) {
    document.getElementById('tipe_laporan').value = val;
    document.querySelectorAll('.tipe-btn').forEach(b => b.classList.remove('active'));
    el.classList.add('active');
}
</script>
