<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../classes/Bill.php';
require_once __DIR__ . '/../classes/Customer.php';
require_once __DIR__ . '/../classes/MikroTik.php'; // Ditambahkan untuk restore

requireRole('super_admin');
$pageTitle = 'Tagihan';

$success = '';
$error = '';

// Handle actions (GET)
if (isset($_GET['action']) && isset($_GET['id']) && verifyCsrf($_GET['token'] ?? '')) {
    $action = $_GET['action'];
    $billId = (int) $_GET['id'];
    
    try {
        switch ($action) {
            case 'delete':
                $result = Bill::delete($billId);
                if ($result['success']) {
                    logActivity(currentUserId(), 'delete_bill', "Hapus tagihan #$billId");
                    redirect('/admin/bills.php', '✅ Tagihan berhasil dihapus');
                } else {
                    redirect('/admin/bills.php', '❌ ' . $result['error'], 'error');
                }
                break;
        }
    } catch (\Throwable $e) {
        redirect('/admin/bills.php', '❌ Error: ' . $e->getMessage(), 'error');
    }
}

// ============================================================================
// HANDLE MANUAL PAYMENT (POST FROM MODAL)
// ============================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_pay']) && verifyCsrf($_POST['csrf_token'] ?? '')) {
    $billId = (int) $_POST['bill_id'];
    $paymentMethod = $_POST['payment_method'] ?? 'Tunai';
    $category = $_POST['category'] ?? 'Pelunasan Tagihan';
    
    $result = Bill::pay($billId, $paymentMethod, $category);
    
    if ($result['success']) {
        $db = db();
        $stmt = $db->prepare("SELECT customer_id FROM bills WHERE id = ?");
        $stmt->execute([$billId]);
        $billInfo = $stmt->fetch();
        
        if ($billInfo) {
            $customer = Customer::find($billInfo['customer_id']);
            
            // 1. Customer di-restore (jika suspended)
            if ($customer && $customer['status'] === 'suspended') {
                try {
                    $mt = new MikroTik();
                    $mt->restoreCustomer($customer['pppoe_username']);
                    Customer::update($customer['id'], ['status' => 'active']);
                } catch (\Throwable $e) {}
            }
            
            // 2. Auto-generate tagihan bulan depan (+1 bulan)
            if (method_exists('Bill', 'generateNextMonth')) {
                Bill::generateNextMonth($customer['id']);
            } else {
                Bill::generate($customer['id']); // Fallback
            }
        }
        
        logActivity(currentUserId(), 'pay_bill', "Bayar manual tagihan #$billId via $paymentMethod ($category)");
        redirect('/admin/bills.php', '✅ Pembayaran berhasil dicatat & tagihan bulan depan digenerate');
    } else {
        redirect('/admin/bills.php', '❌ ' . $result['error'], 'error');
    }
}

// Filter
$statusFilter = $_GET['status'] ?? '';
$branchFilter = $_GET['branch'] ?? '';

try {
    $bills = Bill::getAll($statusFilter, $branchFilter ?: null);
    $stats = Bill::getStats();
    $db = db();
    $branches = $db->query("SELECT id, name FROM branches ORDER BY name")->fetchAll();
} catch (\Throwable $e) {
    $bills = [];
    $stats = ['total' => 0, 'unpaid_count' => 0, 'paid_count' => 0, 'overdue_count' => 0, 'unpaid_amount' => 0, 'paid_amount' => 0];
    $branches = [];
    $error = 'Error loading data: ' . $e->getMessage();
}

require __DIR__ . '/../includes/header.php';
require __DIR__ . '/../includes/sidebar.php';
?>

<style>
/* ... (Copy semua CSS dari file bills.php asli Anda di sini) ... */
.page-header { margin-bottom: 20px; }
.page-title { font-size: 1.8rem; font-weight: 700; color: #003D7A; margin: 0 0 8px; display: flex; align-items: center; gap: 12px; }
.page-title i { font-size: 2rem; color: #0066CC; }
.summary-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; margin-bottom: 20px; }
.summary-card { background: white; border-radius: 16px; padding: 18px; box-shadow: 0 4px 15px rgba(0,0,0,0.06); position: relative; overflow: hidden; transition: all 0.3s ease; border-left: 4px solid; text-decoration: none; color: inherit; display: block; }
.summary-card:hover { transform: translateY(-3px); box-shadow: 0 8px 20px rgba(0,0,0,0.1); color: inherit; }
.summary-card.primary { border-left-color: #0066CC; }
.summary-card.warning { border-left-color: #FF9900; }
.summary-card.success { border-left-color: #00C853; }
.summary-card.danger { border-left-color: #DC3545; }
.summary-card-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px; }
.summary-card-title { color: #666; font-size: 0.75rem; font-weight: 600; margin: 0; text-transform: uppercase; letter-spacing: 0.5px; }
.summary-card-icon { width: 36px; height: 36px; border-radius: 10px; display: flex; align-items: center; justify-content: center; color: white; font-size: 1rem; }
.summary-card.primary .summary-card-icon { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); }
.summary-card.warning .summary-card-icon { background: linear-gradient(135deg, #FF9900 0%, #FFB84D 100%); }
.summary-card.success .summary-card-icon { background: linear-gradient(135deg, #00C853 0%, #69F0AE 100%); }
.summary-card.danger .summary-card-icon { background: linear-gradient(135deg, #DC3545 0%, #FF6B7A 100%); }
.summary-card-value { font-size: 1.5rem; font-weight: 800; margin-bottom: 2px; letter-spacing: -0.5px; }
.summary-card.primary .summary-card-value { color: #0066CC; }
.summary-card.warning .summary-card-value { color: #FF9900; }
.summary-card.success .summary-card-value { color: #00C853; }
.summary-card.danger .summary-card-value { color: #DC3545; }
.summary-card-footer { font-size: 0.75rem; color: #999; }
.status-tabs { display: flex; gap: 8px; margin-bottom: 20px; overflow-x: auto; padding-bottom: 4px; }
.status-tab { padding: 10px 18px; border-radius: 10px; text-decoration: none; font-size: 0.88rem; font-weight: 600; white-space: nowrap; transition: all 0.3s ease; display: inline-flex; align-items: center; gap: 6px; border: 2px solid #e8f4f8; background: white; color: #666; }
.status-tab:hover { border-color: #0066CC; color: #0066CC; }
.status-tab.active { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); color: white; border-color: transparent; box-shadow: 0 4px 12px rgba(0, 102, 204, 0.3); }
.status-tab.warning.active { background: linear-gradient(135deg, #FF9900 0%, #FFB84D 100%); box-shadow: 0 4px 12px rgba(255, 153, 0, 0.3); }
.status-tab.danger.active { background: linear-gradient(135deg, #DC3545 0%, #FF6B7A 100%); box-shadow: 0 4px 12px rgba(220, 53, 69, 0.3); }
.status-tab.success.active { background: linear-gradient(135deg, #00C853 0%, #69F0AE 100%); box-shadow: 0 4px 12px rgba(0, 200, 83, 0.3); }
.status-tab-count { background: rgba(255,255,255,0.3); padding: 2px 8px; border-radius: 10px; font-size: 0.75rem; font-weight: 700; }
.status-tab:not(.active) .status-tab-count { background: #e8f4f8; color: #666; }
.alert-modern { padding: 14px 18px; border-radius: 12px; margin-bottom: 16px; display: flex; align-items: flex-start; gap: 12px; font-size: 0.9rem; border: 2px solid; }
.alert-modern.success { background: #e8f5e9; border-color: #a5d6a7; color: #2e7d32; }
.alert-modern.danger { background: #ffebee; border-color: #ef9a9a; color: #c62828; }
.alert-modern.warning { background: #fff8e1; border-color: #ffe082; color: #f57c00; }
.alert-modern.info { background: #e3f2fd; border-color: #90caf9; color: #1565c0; }
.alert-modern i { font-size: 1.2rem; margin-top: 2px; flex-shrink: 0; }
.card-modern { background: white; border-radius: 16px; box-shadow: 0 4px 20px rgba(0,0,0,0.08); overflow: hidden; margin-bottom: 20px; border: none; }
.card-header-modern { color: white; padding: 16px 20px; font-size: 1rem; font-weight: 600; display: flex; align-items: center; justify-content: space-between; gap: 10px; flex-wrap: wrap; }
.card-header-modern.primary { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); }
.card-header-modern .title-left { display: flex; align-items: center; gap: 10px; }
.card-body-modern { padding: 20px; }
.filter-form { display: grid; grid-template-columns: 1fr auto auto; gap: 12px; align-items: end; }
.form-group-filter { margin-bottom: 0; }
.form-label-filter { display: block; font-weight: 600; color: #003D7A; margin-bottom: 6px; font-size: 0.82rem; }
.form-select-filter { width: 100%; padding: 10px 14px; border: 2px solid #e8f4f8; border-radius: 10px; font-size: 0.88rem; transition: all 0.3s ease; background: #f8fafc; font-family: inherit; }
.form-select-filter:focus { outline: none; border-color: #0066CC; background: white; box-shadow: 0 0 0 4px rgba(0, 102, 204, 0.1); }
.btn-filter { padding: 10px 16px; border: none; border-radius: 10px; font-size: 0.88rem; font-weight: 600; cursor: pointer; transition: all 0.3s ease; display: inline-flex; align-items: center; justify-content: center; gap: 6px; text-decoration: none; white-space: nowrap; height: 42px; }
.btn-filter.primary { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); color: white; box-shadow: 0 4px 12px rgba(0, 102, 204, 0.3); }
.btn-filter.outline { background: white; color: #666; border: 2px solid #e8f4f8; }
.table-wrapper { background: white; border-radius: 16px; box-shadow: 0 4px 20px rgba(0,0,0,0.08); overflow: hidden; margin-bottom: 20px; }
.table-header { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); color: white; padding: 16px 20px; display: flex; align-items: center; justify-content: space-between; gap: 10px; flex-wrap: wrap; }
.table-header-title { display: flex; align-items: center; gap: 10px; font-weight: 600; font-size: 1rem; }
.table-header-count { background: rgba(255,255,255,0.2); padding: 4px 12px; border-radius: 20px; font-size: 0.82rem; font-weight: 600; }
.table-scroll { overflow-x: auto; -webkit-overflow-scrolling: touch; }
.table-modern { width: 100%; border-collapse: separate; border-spacing: 0; font-size: 0.88rem; min-width: 900px; }
.table-modern thead { background: #f8fafc; position: sticky; top: 0; z-index: 10; }
.table-modern th { padding: 12px 14px; text-align: left; font-weight: 700; color: #003D7A; border-bottom: 2px solid #e8f4f8; font-size: 0.78rem; text-transform: uppercase; letter-spacing: 0.5px; white-space: nowrap; }
.table-modern td { padding: 12px 14px; border-bottom: 1px solid #f0f0f0; vertical-align: middle; }
.table-modern tbody tr { transition: all 0.2s ease; }
.table-modern tbody tr:hover { background: #f8fafc; }
.table-modern tbody tr:last-child td { border-bottom: none; }
.table-modern tbody tr.row-overdue { background: #fff8f8; }
.table-modern tbody tr.row-overdue:hover { background: #fff0f0; }
.customer-cell { display: flex; align-items: center; gap: 10px; }
.customer-avatar { width: 36px; height: 36px; border-radius: 50%; background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); color: white; display: flex; align-items: center; justify-content: center; font-weight: 700; font-size: 0.85rem; flex-shrink: 0; }
.customer-name { font-weight: 700; color: #003D7A; font-size: 0.88rem; margin: 0; line-height: 1.3; }
.customer-meta { font-size: 0.75rem; color: #999; margin-top: 1px; }
.bill-number { font-family: 'Courier New', monospace; font-weight: 700; color: #003D7A; font-size: 0.85rem; background: #f8fafc; padding: 3px 8px; border-radius: 6px; border-left: 3px solid #0066CC; display: inline-block; }
.amount { font-weight: 800; color: #003D7A; font-size: 0.92rem; }
.badge-modern { display: inline-flex; align-items: center; gap: 4px; padding: 5px 10px; border-radius: 20px; font-size: 0.72rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; white-space: nowrap; }
.badge-modern.paid { background: #d1e7dd; color: #0f5132; }
.badge-modern.unpaid { background: #fff3cd; color: #856404; }
.badge-modern.overdue { background: #f8d7da; color: #842029; }
.overdue-info { font-size: 0.72rem; color: #DC3545; margin-top: 3px; display: flex; align-items: center; gap: 3px; font-weight: 600; }
.action-buttons { display: flex; gap: 4px; flex-wrap: nowrap; }
.btn-action { width: 32px; height: 32px; border: none; border-radius: 8px; display: flex; align-items: center; justify-content: center; cursor: pointer; transition: all 0.3s ease; font-size: 0.88rem; text-decoration: none; flex-shrink: 0; }
.btn-action.pay { background: #d1e7dd; color: #0f5132; }
.btn-action.pay:hover { background: #00C853; color: white; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0, 200, 83, 0.3); }
.btn-action.delete { background: #ffe5e5; color: #842029; }
.btn-action.delete:hover { background: #b02a37; color: white; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(176, 42, 55, 0.3); }
.empty-state { text-align: center; padding: 50px 20px; }
.empty-state-icon { width: 70px; height: 70px; margin: 0 auto 16px; background: #f8fafc; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 2rem; color: #ccc; }
.empty-state-title { color: #666; font-weight: 600; margin-bottom: 6px; font-size: 1rem; }
.empty-state-subtitle { color: #999; font-size: 0.85rem; margin: 0; }
.mobile-list { display: none; }
.mobile-list-item { background: white; padding: 14px 16px; border-bottom: 1px solid #f0f0f0; display: flex; align-items: center; gap: 12px; transition: all 0.2s ease; }
.mobile-list-item:hover { background: #f8fafc; }
.mobile-list-item:last-child { border-bottom: none; }
.mobile-list-item.overdue { background: #fff8f8; border-left: 3px solid #DC3545; }
.mobile-list-avatar { width: 40px; height: 40px; border-radius: 50%; background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); color: white; display: flex; align-items: center; justify-content: center; font-weight: 700; font-size: 0.95rem; flex-shrink: 0; }
.mobile-list-content { flex: 1; min-width: 0; }
.mobile-list-header { display: flex; justify-content: space-between; align-items: flex-start; gap: 8px; margin-bottom: 4px; }
.mobile-list-name { font-weight: 700; color: #003D7A; font-size: 0.9rem; margin: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.mobile-list-amount { font-weight: 800; color: #003D7A; font-size: 0.88rem; white-space: nowrap; }
.mobile-list-meta { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; font-size: 0.75rem; color: #999; margin-bottom: 6px; }
.mobile-list-meta code { background: #f0f0f0; padding: 1px 6px; border-radius: 4px; font-size: 0.7rem; }
.mobile-list-footer { display: flex; justify-content: space-between; align-items: center; gap: 8px; margin-top: 6px; }
.mobile-list-actions { display: flex; gap: 6px; }

/* === MODAL PEMBAYARAN === */
.modal-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0, 0, 0, 0.6); backdrop-filter: blur(4px); display: flex; align-items: center; justify-content: center; z-index: 9999; animation: fadeIn 0.2s ease; }
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
.modal-content { background: white; border-radius: 16px; width: 90%; max-width: 450px; box-shadow: 0 10px 40px rgba(0,0,0,0.2); overflow: hidden; animation: slideDown 0.3s ease; }
@keyframes slideDown { from { opacity: 0; transform: translateY(-30px); } to { opacity: 1; transform: translateY(0); } }
.modal-header { background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%); color: white; padding: 16px 20px; display: flex; justify-content: space-between; align-items: center; }
.modal-header h3 { margin: 0; font-size: 1.1rem; display: flex; align-items: center; gap: 8px; font-weight: 700; }
.modal-close { background: rgba(255,255,255,0.2); border: none; color: white; font-size: 1.2rem; cursor: pointer; width: 32px; height: 32px; border-radius: 50%; display: flex; align-items: center; justify-content: center; transition: all 0.2s; }
.modal-close:hover { background: rgba(255,255,255,0.4); }
.modal-body { padding: 20px; }
.bill-summary { background: #f8fafc; padding: 12px; border-radius: 10px; margin-bottom: 16px; border-left: 4px solid #0066CC; }
.bill-summary p { margin: 4px 0; font-size: 0.85rem; color: #666; }
.bill-summary strong { color: #003D7A; }
.modal-body .form-group { margin-bottom: 15px; }
.modal-body label { display: flex; align-items: center; gap: 6px; font-weight: 600; color: #003D7A; margin-bottom: 6px; font-size: 0.85rem; }
.modal-footer { padding: 16px 20px; background: #f8fafc; display: flex; justify-content: flex-end; gap: 10px; border-top: 1px solid #e8f4f8; }

@media (max-width: 768px) {
    .desktop-table { display: none; }
    .mobile-list { display: block; }
    .filter-form { grid-template-columns: 1fr; }
    .btn-filter { width: 100%; }
}
</style>

<div class="main-content">
    <div class="navbar-modern">
        <div class="navbar-left">
            <button class="burger-btn" onclick="toggleSidebar()"><i class="bi bi-list"></i></button>
            <div><h1 class="navbar-title">Tagihan</h1></div>
        </div>
        <div class="navbar-right"><span class="navbar-badge"><i class="bi bi-receipt"></i> Billing</span></div>
    </div>

    <div class="content-wrapper">
        <?= flashMessage() ?>

        <?php if ($error): ?><div class="alert-modern danger"><i class="bi bi-exclamation-circle-fill"></i><div><?= htmlspecialchars($error) ?></div></div><?php endif; ?>
        <?php if (($stats['unpaid_amount'] ?? 0) > 0): ?><div class="alert-modern warning"><i class="bi bi-exclamation-triangle-fill"></i><div><strong>Total tagihan belum dibayar:</strong> Rp <?= number_format($stats['unpaid_amount'], 0, ',', '.') ?></div></div><?php endif; ?>

        <div class="summary-row">
            <a href="/admin/bills.php" class="summary-card primary"><div class="summary-card-header"><h6 class="summary-card-title">Total Tagihan</h6><div class="summary-card-icon"><i class="bi bi-receipt"></i></div></div><div class="summary-card-value"><?= number_format($stats['total'] ?? 0) ?></div><div class="summary-card-footer">📋 Seluruh tagihan</div></a>
            <a href="/admin/bills.php?status=unpaid" class="summary-card warning"><div class="summary-card-header"><h6 class="summary-card-title">Belum Bayar</h6><div class="summary-card-icon"><i class="bi bi-clock-fill"></i></div></div><div class="summary-card-value"><?= number_format($stats['unpaid_count'] ?? 0) ?></div><div class="summary-card-footer">💰 Rp <?= number_format(($stats['unpaid_amount'] ?? 0) / 1000000, 1) ?>M</div></a>
            <a href="/admin/bills.php?status=paid" class="summary-card success"><div class="summary-card-header"><h6 class="summary-card-title">Lunas</h6><div class="summary-card-icon"><i class="bi bi-check-circle-fill"></i></div></div><div class="summary-card-value"><?= number_format($stats['paid_count'] ?? 0) ?></div><div class="summary-card-footer">✅ Rp <?= number_format(($stats['paid_amount'] ?? 0) / 1000000, 1) ?>M</div></a>
            <a href="/admin/bills.php?status=overdue" class="summary-card danger"><div class="summary-card-header"><h6 class="summary-card-title">Terlambat</h6><div class="summary-card-icon"><i class="bi bi-exclamation-triangle-fill"></i></div></div><div class="summary-card-value"><?= number_format($stats['overdue_count'] ?? 0) ?></div><div class="summary-card-footer">⚠️ Perlu ditindaklanjuti</div></a>
        </div>

        <div class="status-tabs">
            <a href="/admin/bills.php" class="status-tab <?= !$statusFilter ? 'active' : '' ?>"><i class="bi bi-list-ul"></i> Semua <span class="status-tab-count"><?= $stats['total'] ?? 0 ?></span></a>
            <a href="/admin/bills.php?status=unpaid" class="status-tab warning <?= $statusFilter === 'unpaid' ? 'active' : '' ?>"><i class="bi bi-clock"></i> Belum Bayar <span class="status-tab-count"><?= $stats['unpaid_count'] ?? 0 ?></span></a>
            <a href="/admin/bills.php?status=overdue" class="status-tab danger <?= $statusFilter === 'overdue' ? 'active' : '' ?>"><i class="bi bi-exclamation-triangle"></i> Terlambat <span class="status-tab-count"><?= $stats['overdue_count'] ?? 0 ?></span></a>
            <a href="/admin/bills.php?status=paid" class="status-tab success <?= $statusFilter === 'paid' ? 'active' : '' ?>"><i class="bi bi-check-circle"></i> Lunas <span class="status-tab-count"><?= $stats['paid_count'] ?? 0 ?></span></a>
        </div>

        <div class="card-modern">
            <div class="card-header-modern primary"><div class="title-left"><i class="bi bi-funnel-fill"></i><span>Filter</span></div></div>
            <div class="card-body-modern">
                <form method="GET" class="filter-form">
                    <div class="form-group-filter"><label class="form-label-filter"><i class="bi bi-building"></i> Cabang</label><select name="branch" class="form-select-filter"><option value="">Semua Cabang</option><?php foreach ($branches as $b): ?><option value="<?= $b['id'] ?>" <?= $branchFilter == $b['id'] ? 'selected' : '' ?>><?= htmlspecialchars($b['name']) ?></option><?php endforeach; ?></select></div>
                    <button type="submit" class="btn-filter primary"><i class="bi bi-funnel"></i><span>Filter</span></button>
                    <a href="/admin/bills.php" class="btn-filter outline"><i class="bi bi-arrow-counterclockwise"></i><span>Reset</span></a>
                </form>
            </div>
        </div>

        <!-- Desktop Table -->
        <div class="table-wrapper desktop-table">
            <div class="table-header"><div class="table-header-title"><i class="bi bi-receipt"></i><span>Daftar Tagihan</span></div><span class="table-header-count"><?= count($bills) ?> tagihan</span></div>
            <?php if (empty($bills)): ?>
                <div class="empty-state"><div class="empty-state-icon"><i class="bi bi-inbox"></i></div><h5 class="empty-state-title">Tidak ada tagihan</h5><p class="empty-state-subtitle">Belum ada tagihan yang sesuai filter</p></div>
            <?php else: ?>
                <div class="table-scroll">
                    <table class="table-modern">
                        <thead><tr><th>No. Tagihan</th><th>Pelanggan</th><th>Cabang</th><th>Periode</th><th>Jatuh Tempo</th><th>Jumlah</th><th>Status</th><th>Bayar</th><th class="text-center">Aksi</th></tr></thead>
                        <tbody>
                            <?php foreach ($bills as $b): ?>
                                <tr class="<?= $b['status'] === 'overdue' ? 'row-overdue' : '' ?>">
                                    <td><span class="bill-number"><?= htmlspecialchars($b['bill_number']) ?></span></td>
                                    <td><div class="customer-cell"><div class="customer-avatar"><?= strtoupper(substr($b['customer_name'], 0, 1)) ?></div><div><div class="customer-name"><?= htmlspecialchars($b['customer_name']) ?></div><div class="customer-meta">#<?= htmlspecialchars($b['customer_number']) ?> <?php if (!empty($b['pppoe_username'])): ?>· <code><?= htmlspecialchars($b['pppoe_username']) ?></code><?php endif; ?></div></div></div></td>
                                    <td><small><?= htmlspecialchars($b['branch_name'] ?? '-') ?></small></td>
                                    <td><?= sprintf('%02d/%d', $b['period_month'] ?? date('m', strtotime($b['due_date'])), $b['period_year'] ?? date('Y', strtotime($b['due_date']))) ?></td>
                                    <td><?= date('d/m/Y', strtotime($b['due_date'])) ?> <?php if ($b['status'] === 'overdue'): ?><div class="overdue-info"><i class="bi bi-exclamation-triangle-fill"></i> Terlambat <?= floor((strtotime('today') - strtotime($b['due_date'])) / 86400) ?> hari</div><?php endif; ?></td>
                                    <td><div class="amount">Rp <?= number_format($b['amount'], 0, ',', '.') ?></div></td>
                                    <td><?php if ($b['status'] === 'paid'): ?><span class="badge-modern paid"><i class="bi bi-check-circle-fill"></i> Lunas</span><?php elseif ($b['status'] === 'overdue'): ?><span class="badge-modern overdue"><i class="bi bi-exclamation-triangle-fill"></i> Terlambat</span><?php else: ?><span class="badge-modern unpaid"><i class="bi bi-clock-fill"></i> Belum Bayar</span><?php endif; ?></td>
                                    <td><?= $b['paid_at'] ? date('d/m/Y', strtotime($b['paid_at'])) : '-' ?></td>
                                    <td>
                                        <div class="action-buttons">
                                            <?php if ($b['status'] !== 'paid'): ?>
                                                <button type="button" class="btn-action pay"
                                                   onclick="openPayModal(<?= $b['id'] ?>, <?= $b['customer_id'] ?? 0 ?>, '<?= htmlspecialchars($b['customer_name'], ENT_QUOTES) ?>', '<?= htmlspecialchars($b['bill_number'], ENT_QUOTES) ?>', 'Rp <?= number_format($b['amount'], 0, ',', '.') ?>')"
                                                   title="Bayar">
                                                    <i class="bi bi-cash-coin"></i>
                                                </button>
                                            <?php endif; ?>
                                            <a href="/admin/bills.php?action=delete&id=<?= $b['id'] ?>&token=<?= csrfToken() ?>" class="btn-action delete" onclick="return confirm('Hapus tagihan <?= htmlspecialchars($b['bill_number']) ?>?')" title="Hapus"><i class="bi bi-trash-fill"></i></a>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>

        <!-- Mobile List -->
        <?php if (empty($bills)): ?>
            <div class="mobile-list" style="background: white; border-radius: 16px; box-shadow: 0 4px 20px rgba(0,0,0,0.08); overflow: hidden;">
                <div class="table-header"><div class="table-header-title"><i class="bi bi-receipt"></i><span>Daftar Tagihan</span></div><span class="table-header-count">0 tagihan</span></div>
                <div class="empty-state"><div class="empty-state-icon"><i class="bi bi-inbox"></i></div><h5 class="empty-state-title">Tidak ada tagihan</h5><p class="empty-state-subtitle">Belum ada tagihan yang sesuai filter</p></div>
            </div>
        <?php else: ?>
            <div class="mobile-list" style="background: white; border-radius: 16px; box-shadow: 0 4px 20px rgba(0,0,0,0.08); overflow: hidden;">
                <div class="table-header"><div class="table-header-title"><i class="bi bi-receipt"></i><span>Daftar Tagihan</span></div><span class="table-header-count"><?= count($bills) ?> tagihan</span></div>
                <?php foreach ($bills as $b): ?>
                    <div class="mobile-list-item <?= $b['status'] === 'overdue' ? 'overdue' : '' ?>">
                        <div class="mobile-list-avatar"><?= strtoupper(substr($b['customer_name'], 0, 1)) ?></div>
                        <div class="mobile-list-content">
                            <div class="mobile-list-header"><h5 class="mobile-list-name"><?= htmlspecialchars($b['customer_name']) ?></h5><div class="mobile-list-amount">Rp <?= number_format($b['amount'], 0, ',', '.') ?></div></div>
                            <div class="mobile-list-meta"><code>#<?= htmlspecialchars($b['bill_number']) ?></code><span>·</span><span><?= htmlspecialchars($b['branch_name'] ?? '-') ?></span><span>·</span><span>Periode <?= sprintf('%02d/%d', $b['period_month'] ?? date('m', strtotime($b['due_date'])), $b['period_year'] ?? date('Y', strtotime($b['due_date']))) ?></span></div>
                            <div class="mobile-list-footer">
                                <div>
                                    <?php if ($b['status'] === 'paid'): ?><span class="badge-modern paid"><i class="bi bi-check-circle-fill"></i> Lunas</span><?php if ($b['paid_at']): ?><div style="font-size: 0.7rem; color: #999; margin-top: 2px;"><?= date('d/m/Y', strtotime($b['paid_at'])) ?></div><?php endif; ?><?php elseif ($b['status'] === 'overdue'): ?><span class="badge-modern overdue"><i class="bi bi-exclamation-triangle-fill"></i> Terlambat</span><div style="font-size: 0.7rem; color: #DC3545; margin-top: 2px; font-weight: 600;">⚠️ <?= floor((strtotime('today') - strtotime($b['due_date'])) / 86400) ?> hari</div><?php else: ?><span class="badge-modern unpaid"><i class="bi bi-clock-fill"></i> Belum Bayar</span><div style="font-size: 0.7rem; color: #999; margin-top: 2px;">JT: <?= date('d/m/Y', strtotime($b['due_date'])) ?></div><?php endif; ?>
                                </div>
                                <div class="mobile-list-actions">
                                    <?php if ($b['status'] !== 'paid'): ?>
                                        <button type="button" class="btn-action pay"
                                           onclick="openPayModal(<?= $b['id'] ?>, <?= $b['customer_id'] ?? 0 ?>, '<?= htmlspecialchars($b['customer_name'], ENT_QUOTES) ?>', '<?= htmlspecialchars($b['bill_number'], ENT_QUOTES) ?>', 'Rp <?= number_format($b['amount'], 0, ',', '.') ?>')"
                                           title="Bayar">
                                            <i class="bi bi-cash-coin"></i>
                                        </button>
                                    <?php endif; ?>
                                    <a href="/admin/bills.php?action=delete&id=<?= $b['id'] ?>&token=<?= csrfToken() ?>" class="btn-action delete" onclick="return confirm('Hapus tagihan?')" title="Hapus"><i class="bi bi-trash-fill"></i></a>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>

    <!-- Modal Pembayaran Manual -->
    <div id="payModal" class="modal-overlay" style="display: none;">
        <div class="modal-content">
            <div class="modal-header">
                <h3><i class="bi bi-cash-coin"></i> Konfirmasi Pembayaran Manual</h3>
                <button class="modal-close" onclick="closePayModal()">&times;</button>
            </div>
            <form method="POST">
                <?= csrfField() ?>
                <input type="hidden" name="bill_id" id="modal_bill_id">
                <input type="hidden" name="customer_id" id="modal_customer_id" value="0">
                
                <div class="modal-body">
                    <div class="bill-summary">
                        <p>Pelanggan: <strong id="modal_customer_name"></strong></p>
                        <p>No. Tagihan: <strong id="modal_bill_number"></strong></p>
                        <p>Jumlah: <strong id="modal_bill_amount" style="color: #00C853;"></strong></p>
                    </div>
                    <div class="form-group"><label><i class="bi bi-credit-card"></i> Metode Pembayaran</label><select name="payment_method" class="form-control-filter" required><option value="Tunai">Tunai</option><option value="Transfer Bank">Transfer Bank</option><option value="QRIS">QRIS</option><option value="Edc">EDC</option><option value="Lainnya">Lainnya</option></select></div>
                    <div class="form-group"><label><i class="bi bi-tag"></i> Kategori</label><select name="category" class="form-control-filter" required><option value="Pelunasan Tagihan">Pelunasan Tagihan</option><option value="Pemasukan Lainnya">Pemasukan Lainnya</option><option value="Denda">Denda</option><option value="Biaya Instalasi">Biaya Instalasi</option></select></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn-filter outline" onclick="closePayModal()">Batal</button>
                    <button type="submit" name="submit_pay" class="btn-filter primary"><i class="bi bi-check-circle"></i> Bayar Sekarang</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function toggleSidebar() {
    const sidebar = document.getElementById('sidebar');
    const overlay = document.getElementById('sidebarOverlay');
    if (sidebar && overlay) {
        sidebar.classList.toggle('active');
        overlay.classList.toggle('active');
        document.body.style.overflow = sidebar.classList.contains('active') ? 'hidden' : '';
    }
}

function openPayModal(billId, customerId, customerName, billNumber, billAmount) {
    document.getElementById('modal_bill_id').value = billId;
    document.getElementById('modal_customer_id').value = customerId || 0;
    document.getElementById('modal_customer_name').innerText = customerName;
    document.getElementById('modal_bill_number').innerText = billNumber;
    document.getElementById('modal_bill_amount').innerText = billAmount;
    document.getElementById('payModal').style.display = 'flex';
}

function closePayModal() {
    document.getElementById('payModal').style.display = 'none';
}

window.onclick = function(event) {
    const modal = document.getElementById('payModal');
    if (event.target === modal) closePayModal();
}
</script>

<?php require __DIR__ . '/../includes/footer.php'; ?>