<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../classes/Broadcast.php';

$branchId = $_SESSION['branch_id'] ?? 0;
if (!$branchId) {
    redirect('/login.php', 'Session tidak valid', 'error');
}

$pageTitle = 'Broadcast Logs';

$db = db();
$stmt = $db->prepare("SELECT * FROM branches WHERE id = ?");
$stmt->execute([$branchId]);
$branch = $stmt->fetch();

try {
    $logs = Broadcast::getLogsByBranch($branchId, 200);
    $stats = Broadcast::getStats($branchId);
} catch (\Throwable $e) {
    $logs = [];
    $stats = ['total_broadcasts' => 0, 'total_sent' => 0, 'total_failed' => 0];
}

// ⭐ CEK apakah kolom source ada
$hasSourceColumn = false;
try {
    $checkCol = $db->query("SHOW COLUMNS FROM broadcast_logs LIKE 'source'")->fetch();
    $hasSourceColumn = !empty($checkCol);
} catch (\Throwable $e) {}

// Filter
$filterStatus = $_GET['status'] ?? '';
$filterSource = $_GET['source'] ?? '';
$search = trim($_GET['search'] ?? '');

if ($filterStatus || $search || $filterSource) {
    $filtered = [];
    foreach ($logs as $log) {
        if ($filterStatus && $log['status'] !== $filterStatus) continue;
        if ($filterSource && ($log['source'] ?? 'manual') !== $filterSource) continue;
        if ($search && stripos(($log['title'] ?? '') . ' ' . ($log['message'] ?? '') . ' ' . ($log['created_by_name'] ?? ''), $search) === false) continue;
        $filtered[] = $log;
    }
    $logs = $filtered;
}

// Stats after filter
$totalBroadcasts = count($logs);
$totalSent = array_sum(array_column($logs, 'total_sent'));
$totalFailed = array_sum(array_column($logs, 'total_failed'));
$completedCount = count(array_filter($logs, fn($l) => $l['status'] === 'completed'));
$partialCount = count(array_filter($logs, fn($l) => $l['status'] === 'partial'));
$failedCount = count(array_filter($logs, fn($l) => $l['status'] === 'failed'));

// ⭐ Count by source
$manualCount = count(array_filter($logs, fn($l) => ($l['source'] ?? 'manual') === 'manual'));
$cronCount = count(array_filter($logs, fn($l) => ($l['source'] ?? 'manual') === 'cron_reminder'));
$paymentCount = count(array_filter($logs, fn($l) => ($l['source'] ?? 'manual') === 'payment_success'));

// ⭐ Label sumber
$sourceLabels = [
    'manual' => ['👤', 'Manual', 'primary'],
    'cron_reminder' => ['⏰', 'Cron Reminder', 'warning'],
    'payment_success' => ['💰', 'Sukses Bayar', 'success'],
];

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

<style>
.navbar-modern { background: linear-gradient(135deg, #25D366 0%, #128C7E 100%); padding: 12px 20px; display: flex; align-items: center; justify-content: space-between; box-shadow: 0 4px 15px rgba(0,0,0,0.15); position: sticky; top: 0; z-index: 1000; }
.navbar-left { display: flex; align-items: center; gap: 14px; flex: 1; min-width: 0; }
.burger-btn { background: rgba(255,255,255,0.2); border: 2px solid rgba(255,255,255,0.3); color: white; width: 42px; height: 42px; border-radius: 12px; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 1.3rem; transition: all 0.3s ease; flex-shrink: 0; }
.burger-btn:hover, .burger-btn:active { background: rgba(255,255,255,0.35); transform: scale(1.05); }
.navbar-info { min-width: 0; flex: 1; }
.navbar-greeting { color: rgba(255,255,255,0.85); font-size: 0.75rem; margin: 0; }
.navbar-title { color: white; font-size: 1.15rem; font-weight: 700; margin: 2px 0 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.navbar-right { display: flex; align-items: center; gap: 10px; flex-shrink: 0; }
.navbar-badge { background: rgba(255,255,255,0.2); color: white; padding: 6px 12px; border-radius: 20px; font-size: 0.8rem; font-weight: 500; display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; }
.main-content { padding: 16px; max-width: 1200px; margin: 0 auto; display: flex; flex-direction: column; gap: 20px; }
.page-header { margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 15px; }
.page-title { font-size: 1.6rem; font-weight: 700; color: #003D7A; margin: 0; display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.page-title i { font-size: 1.8rem; color: #25D366; }
.summary-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 14px; margin-bottom: 22px; }
.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 transparent; }
.summary-card:hover { transform: translateY(-4px); box-shadow: 0 12px 25px rgba(0,0,0,0.1); }
.summary-card.whatsapp { border-left-color: #25D366; }
.summary-card.success { border-left-color: #00C853; }
.summary-card.danger { border-left-color: #DC3545; }
.summary-card.info { border-left-color: #00B8D4; }
.summary-card.warning { border-left-color: #FF9900; }
.summary-card.purple { border-left-color: #7c3aed; }
.summary-card-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px; }
.summary-card-title { color: #666; font-size: 0.78rem; font-weight: 600; margin: 0; text-transform: uppercase; letter-spacing: 0.5px; }
.summary-card-icon { width: 40px; height: 40px; border-radius: 12px; display: flex; align-items: center; justify-content: center; color: white; font-size: 1.15rem; }
.summary-card.whatsapp .summary-card-icon { background: linear-gradient(135deg, #25D366 0%, #128C7E 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.info .summary-card-icon { background: linear-gradient(135deg, #00B8D4 0%, #26C6DA 100%); }
.summary-card.warning .summary-card-icon { background: linear-gradient(135deg, #FF9900 0%, #FFB84D 100%); }
.summary-card.purple .summary-card-icon { background: linear-gradient(135deg, #7c3aed 0%, #a78bfa 100%); }
.summary-card-value { font-size: 1.6rem; font-weight: 800; margin-bottom: 4px; letter-spacing: -0.5px; color: #003D7A; line-height: 1.1; }
.summary-card-footer { font-size: 0.78rem; color: #999; display: flex; align-items: center; gap: 5px; }
.status-tabs { display: flex; gap: 8px; margin-bottom: 20px; overflow-x: auto; padding-bottom: 4px; flex-wrap: wrap; }
.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: #25D366; color: #25D366; }
.status-tab.active { background: linear-gradient(135deg, #25D366 0%, #128C7E 100%); color: white; border-color: transparent; box-shadow: 0 4px 12px rgba(37, 211, 102, 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.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.purple.active { background: linear-gradient(135deg, #7c3aed 0%, #a78bfa 100%); box-shadow: 0 4px 12px rgba(124, 58, 237, 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; }
.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.whatsapp { background: linear-gradient(135deg, #25D366 0%, #128C7E 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: 2fr 1fr 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.8rem; }
.form-control-filter, .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; box-sizing: border-box; }
.form-control-filter:focus, .form-select-filter:focus { outline: none; border-color: #25D366; background: white; box-shadow: 0 0 0 4px rgba(37, 211, 102, 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, #25D366 0%, #128C7E 100%); color: white; box-shadow: 0 4px 12px rgba(37, 211, 102, 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, #25D366 0%, #128C7E 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: 1000px; }
.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; }
.log-title { font-weight: 700; color: #003D7A; font-size: 0.88rem; margin-bottom: 2px; line-height: 1.3; }
.log-preview { font-size: 0.75rem; color: #999; line-height: 1.4; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
.log-date { font-weight: 600; color: #003D7A; font-size: 0.85rem; }
.log-time { font-size: 0.72rem; color: #999; margin-top: 2px; }
.log-count { font-weight: 800; font-size: 0.95rem; }
.log-count.success { color: #00C853; }
.log-count.danger { color: #DC3545; }
.log-user { display: flex; align-items: center; gap: 6px; font-size: 0.82rem; color: #666; }
.user-avatar-small { width: 24px; height: 24px; border-radius: 50%; background: linear-gradient(135deg, #25D366 0%, #128C7E 100%); color: white; display: flex; align-items: center; justify-content: center; font-weight: 700; font-size: 0.7rem; flex-shrink: 0; }
.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.completed { background: #d1e7dd; color: #0f5132; }
.badge-modern.partial { background: #fff3cd; color: #856404; }
.badge-modern.failed { background: #f8d7da; color: #842029; }
/* ⭐ Badge Sumber */
.badge-source { display: inline-flex; align-items: center; gap: 4px; padding: 4px 10px; border-radius: 20px; font-size: 0.72rem; font-weight: 700; white-space: nowrap; }
.badge-source.manual { background: #cfe2ff; color: #084298; }
.badge-source.cron_reminder { background: #fff3cd; color: #856404; }
.badge-source.payment_success { background: #d1e7dd; color: #0f5132; }
.btn-action { width: 32px; height: 32px; border: none; border-radius: 8px; display: inline-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.view { background: #cfe2ff; color: #084298; }
.btn-action.view:hover { background: #0066CC; color: white; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0, 102, 204, 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; }
.modal-modern .modal-content { border: none; border-radius: 16px; overflow: hidden; box-shadow: 0 20px 60px rgba(0,0,0,0.2); }
.modal-modern .modal-header { background: linear-gradient(135deg, #25D366 0%, #128C7E 100%); color: white; padding: 18px 24px; border: none; }
.modal-modern .modal-title { font-weight: 700; display: flex; align-items: center; gap: 10px; font-size: 1.1rem; }
.modal-modern .modal-body { padding: 24px; max-height: 70vh; overflow-y: auto; }
.modal-modern .modal-footer { padding: 16px 24px; border-top: 1px solid #f0f0f0; background: #f8fafc; display: flex; gap: 10px; justify-content: flex-end; flex-wrap: wrap; }
.detail-row { display: grid; grid-template-columns: 140px 1fr; gap: 12px; padding: 10px 0; border-bottom: 1px dashed #e8f4f8; align-items: flex-start; }
.detail-row:last-child { border-bottom: none; }
.detail-label { font-weight: 600; color: #666; font-size: 0.85rem; display: flex; align-items: center; gap: 6px; }
.detail-value { color: #333; font-size: 0.9rem; word-break: break-word; }
.detail-value strong { color: #003D7A; }
.message-content-box { background: #f8fafc; border: 2px solid #e8f4f8; border-radius: 12px; padding: 16px; white-space: pre-wrap; font-family: inherit; max-height: 400px; overflow-y: auto; color: #333; line-height: 1.6; margin-top: 8px; }
.stats-summary { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin: 16px 0; }
.stats-item { background: #f8fafc; border-radius: 10px; padding: 12px; text-align: center; border-left: 3px solid #0066CC; }
.stats-item.success { border-left-color: #00C853; }
.stats-item.danger { border-left-color: #DC3545; }
.stats-item-label { font-size: 0.72rem; color: #666; text-transform: uppercase; letter-spacing: 0.5px; font-weight: 600; margin-bottom: 4px; }
.stats-item-value { font-size: 1.2rem; font-weight: 800; color: #003D7A; }
.btn-modal { padding: 10px 20px; border: none; border-radius: 10px; font-size: 0.9rem; font-weight: 600; cursor: pointer; transition: all 0.3s ease; display: inline-flex; align-items: center; gap: 6px; text-decoration: none; }
.btn-modal.whatsapp { background: linear-gradient(135deg, #25D366 0%, #128C7E 100%); color: white; }
.btn-modal.secondary { background: white; color: #666; border: 2px solid #e8f4f8; }
@media (max-width: 992px) { .filter-form { grid-template-columns: 1fr 1fr; } .filter-form .form-group-filter:first-child { grid-column: 1 / -1; } }
@media (max-width: 768px) {
    .navbar-modern { padding: 10px 15px; }
    .navbar-title { font-size: 1rem; }
    .navbar-greeting, .navbar-badge { display: none; }
    .main-content { padding: 15px; }
    .summary-row { grid-template-columns: repeat(2, 1fr); gap: 10px; }
    .summary-card { padding: 14px; }
    .summary-card-value { font-size: 1.2rem; }
    .status-tabs { gap: 6px; }
    .status-tab { padding: 8px 14px; font-size: 0.8rem; }
    .card-body-modern { padding: 16px; }
    .filter-form { grid-template-columns: 1fr; }
    .table-modern { font-size: 0.82rem; }
    .table-modern th, .table-modern td { padding: 10px 12px; }
    .stats-summary { grid-template-columns: 1fr; }
    .detail-row { grid-template-columns: 1fr; gap: 4px; }
}
</style>

<div class="content-wrapper">
<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 class="navbar-info">
                <p class="navbar-greeting">Riwayat broadcast</p>
                <h1 class="navbar-title">Broadcast Logs - <?= htmlspecialchars($branch['name'] ?? 'Cabang') ?></h1>
            </div>
        </div>
        <div class="navbar-right">
            <span class="navbar-badge">
                <i class="bi bi-building"></i> <?= htmlspecialchars($branch['name'] ?? 'Cabang') ?>
            </span>
        </div>
    </div>

    <!-- Summary Cards -->
    <div class="summary-row">
        <div class="summary-card whatsapp">
            <div class="summary-card-header">
                <h6 class="summary-card-title">Total Broadcast</h6>
                <div class="summary-card-icon"><i class="bi bi-megaphone-fill"></i></div>
            </div>
            <div class="summary-card-value"><?= number_format($totalBroadcasts) ?></div>
            <div class="summary-card-footer">📢 Seluruh broadcast</div>
        </div>
        
        <div class="summary-card success">
            <div class="summary-card-header">
                <h6 class="summary-card-title">Pesan Terkirim</h6>
                <div class="summary-card-icon"><i class="bi bi-check-circle-fill"></i></div>
            </div>
            <div class="summary-card-value"><?= number_format($totalSent) ?></div>
            <div class="summary-card-footer">✅ Berhasil terkirim</div>
        </div>
        
        <div class="summary-card danger">
            <div class="summary-card-header">
                <h6 class="summary-card-title">Pesan Gagal</h6>
                <div class="summary-card-icon"><i class="bi bi-x-circle-fill"></i></div>
            </div>
            <div class="summary-card-value"><?= number_format($totalFailed) ?></div>
            <div class="summary-card-footer">❌ Gagal terkirim</div>
        </div>
        
        <div class="summary-card info">
            <div class="summary-card-header">
                <h6 class="summary-card-title">Tingkat Sukses</h6>
                <div class="summary-card-icon"><i class="bi bi-graph-up-arrow"></i></div>
            </div>
            <div class="summary-card-value">
                <?php 
                $totalAll = $totalSent + $totalFailed;
                $successRate = $totalAll > 0 ? round(($totalSent / $totalAll) * 100, 1) : 0;
                echo $successRate . '%';
                ?>
            </div>
            <div class="summary-card-footer">📊 Success rate</div>
        </div>
    </div>

    <!-- ⭐ Summary by Source -->
    <?php if ($hasSourceColumn): ?>
    <div class="summary-row" style="grid-template-columns: repeat(3, 1fr);">
        <div class="summary-card primary" style="border-left-color: #0066CC;">
            <div class="summary-card-header">
                <h6 class="summary-card-title">👤 Broadcast Manual</h6>
                <div class="summary-card-icon" style="background: linear-gradient(135deg, #0066CC 0%, #00B4FF 100%);"><i class="bi bi-person-fill"></i></div>
            </div>
            <div class="summary-card-value"><?= number_format($manualCount) ?></div>
            <div class="summary-card-footer">Dikirim manual oleh admin</div>
        </div>
        
        <div class="summary-card warning">
            <div class="summary-card-header">
                <h6 class="summary-card-title">⏰ Reminder Otomatis</h6>
                <div class="summary-card-icon"><i class="bi bi-clock-fill"></i></div>
            </div>
            <div class="summary-card-value"><?= number_format($cronCount) ?></div>
            <div class="summary-card-footer">Dari cron job (H-3, H-1, Hari H)</div>
        </div>
        
        <div class="summary-card success">
            <div class="summary-card-header">
                <h6 class="summary-card-title">💰 Notif Sukses Bayar</h6>
                <div class="summary-card-icon"><i class="bi bi-cash-coin"></i></div>
            </div>
            <div class="summary-card-value"><?= number_format($paymentCount) ?></div>
            <div class="summary-card-footer">Setelah pembayaran cash</div>
        </div>
    </div>
    <?php endif; ?>

    <!-- Status Tabs -->
    <div class="status-tabs">
        <a href="/branch/broadcast_logs.php" class="status-tab <?= !$filterStatus && !$filterSource ? 'active' : '' ?>">
            <i class="bi bi-list-ul"></i> Semua
            <span class="status-tab-count"><?= $totalBroadcasts ?></span>
        </a>
        <a href="/branch/broadcast_logs.php?status=completed" class="status-tab success <?= $filterStatus === 'completed' ? 'active' : '' ?>">
            <i class="bi bi-check-circle"></i> Completed
            <span class="status-tab-count"><?= $completedCount ?></span>
        </a>
        <a href="/branch/broadcast_logs.php?status=partial" class="status-tab warning <?= $filterStatus === 'partial' ? 'active' : '' ?>">
            <i class="bi bi-exclamation-circle"></i> Partial
            <span class="status-tab-count"><?= $partialCount ?></span>
        </a>
        <a href="/branch/broadcast_logs.php?status=failed" class="status-tab danger <?= $filterStatus === 'failed' ? 'active' : '' ?>">
            <i class="bi bi-x-circle"></i> Failed
            <span class="status-tab-count"><?= $failedCount ?></span>
        </a>
        
        <?php if ($hasSourceColumn): ?>
        <span style="align-self: center; color: #999; font-size: 0.8rem; margin: 0 4px;">|</span>
        <a href="/branch/broadcast_logs.php?source=manual" class="status-tab <?= $filterSource === 'manual' ? 'active' : '' ?>">
            👤 Manual
            <span class="status-tab-count"><?= $manualCount ?></span>
        </a>
        <a href="/branch/broadcast_logs.php?source=cron_reminder" class="status-tab warning <?= $filterSource === 'cron_reminder' ? 'active' : '' ?>">
            ⏰ Cron
            <span class="status-tab-count"><?= $cronCount ?></span>
        </a>
        <a href="/branch/broadcast_logs.php?source=payment_success" class="status-tab success <?= $filterSource === 'payment_success' ? 'active' : '' ?>">
            💰 Sukses Bayar
            <span class="status-tab-count"><?= $paymentCount ?></span>
        </a>
        <?php endif; ?>
    </div>

    <!-- Filter Card -->
    <div class="card-modern">
        <div class="card-header-modern whatsapp">
            <div class="title-left">
                <i class="bi bi-funnel-fill"></i>
                <span>Filter & Pencarian</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-search"></i> Cari</label>
                    <input type="text" name="search" class="form-control-filter" 
                           value="<?= htmlspecialchars($search) ?>" 
                           placeholder="Judul, pesan, atau nama pengirim...">
                </div>
                <div class="form-group-filter">
                    <label class="form-label-filter"><i class="bi bi-circle"></i> Status</label>
                    <select name="status" class="form-select-filter">
                        <option value="">Semua Status</option>
                        <option value="completed" <?= $filterStatus === 'completed' ? 'selected' : '' ?>>✅ Completed</option>
                        <option value="partial" <?= $filterStatus === 'partial' ? 'selected' : '' ?>>⚠️ Partial</option>
                        <option value="failed" <?= $filterStatus === 'failed' ? 'selected' : '' ?>>❌ Failed</option>
                    </select>
                </div>
                <?php if ($hasSourceColumn): ?>
                <div class="form-group-filter">
                    <label class="form-label-filter"><i class="bi bi-signpost-fill"></i> Sumber</label>
                    <select name="source" class="form-select-filter">
                        <option value="">Semua Sumber</option>
                        <option value="manual" <?= $filterSource === 'manual' ? 'selected' : '' ?>>👤 Manual</option>
                        <option value="cron_reminder" <?= $filterSource === 'cron_reminder' ? 'selected' : '' ?>>⏰ Cron Reminder</option>
                        <option value="payment_success" <?= $filterSource === 'payment_success' ? 'selected' : '' ?>>💰 Sukses Bayar</option>
                    </select>
                </div>
                <?php endif; ?>
                <button type="submit" class="btn-filter primary">
                    <i class="bi bi-funnel"></i><span>Filter</span>
                </button>
                <a href="/branch/broadcast_logs.php" class="btn-filter outline">
                    <i class="bi bi-arrow-counterclockwise"></i><span>Reset</span>
                </a>
            </form>
        </div>
    </div>

    <!-- Logs Table -->
    <div class="table-wrapper">
        <div class="table-header">
            <div class="table-header-title">
                <i class="bi bi-list-ul"></i>
                <span>Riwayat Broadcast</span>
                <span class="table-header-count"><?= count($logs) ?> broadcast</span>
            </div>
        </div>
        
        <?php if (empty($logs)): ?>
            <div class="empty-state">
                <div class="empty-state-icon"><i class="bi bi-inbox"></i></div>
                <h5 class="empty-state-title">Belum ada broadcast</h5>
                <p class="empty-state-subtitle">
                    <?php if ($filterStatus || $search || $filterSource): ?>
                        Tidak ada broadcast yang sesuai filter. 
                        <a href="/branch/broadcast_logs.php" style="color: #25D366; font-weight: 600;">Reset filter</a>
                    <?php else: ?>
                        Broadcast yang dilakukan akan muncul di sini.
                    <?php endif; ?>
                </p>
            </div>
        <?php else: ?>
            <div class="table-scroll">
                <table class="table-modern">
                    <thead>
                        <tr>
                            <th>Tanggal</th>
                            <th>Judul / Pesan</th>
                            <?php if ($hasSourceColumn): ?><th>Sumber</th><?php endif; ?>
                            <th>Target</th>
                            <th class="text-center">Terkirim</th>
                            <th class="text-center">Gagal</th>
                            <th>Status</th>
                            <th>Oleh</th>
                            <th class="text-center">Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($logs as $log): 
                            $targetLabels = [
                                'all_customers' => ['📢', 'Semua Customer'],
                                'selected_customers' => ['☑️', 'Customer Terpilih'],
                                'single_customer' => ['👤', 'Single Customer'],
                                'branch' => ['🏢', 'Cabang Tertentu'],
                                'custom_numbers' => ['🔢', 'Nomor Custom'],
                                'by_package' => ['📦', 'Berdasarkan Paket'],
                                'by_status' => ['🔖', 'Berdasarkan Status'],
                                'cron_reminder_h-3' => ['⏰', 'Reminder H-3'],
                                'cron_reminder_h-1' => ['⏰', 'Reminder H-1'],
                                'cron_reminder_hari_h' => ['⏰', 'Reminder Hari H'],
                            ];
                            $targetType = $log['target_type'] ?? 'manual';
                            $targetInfo = $targetLabels[$targetType] ?? ['📋', $targetType];
                            $source = $log['source'] ?? 'manual';
                            $sourceInfo = $sourceLabels[$source] ?? ['📋', $source, 'secondary'];
                        ?>
                            <tr>
                                <td>
                                    <div class="log-date"><?= date('d/m/Y', strtotime($log['created_at'])) ?></div>
                                    <div class="log-time"><?= date('H:i', strtotime($log['created_at'])) ?> WIB</div>
                                </td>
                                <td style="min-width: 220px;">
                                    <div class="log-title"><?= htmlspecialchars($log['title'] ?? '(Tanpa Judul)') ?></div>
                                    <div class="log-preview"><?= htmlspecialchars(substr($log['message'] ?? '', 0, 60)) ?><?= strlen($log['message'] ?? '') > 60 ? '...' : '' ?></div>
                                </td>
                                <?php if ($hasSourceColumn): ?>
                                <td>
                                    <span class="badge-source <?= $source ?>">
                                        <?= $sourceInfo[0] ?> <?= $sourceInfo[1] ?>
                                    </span>
                                </td>
                                <?php endif; ?>
                                <td>
                                    <span style="display: inline-flex; align-items: center; gap: 4px; padding: 3px 8px; background: #f0f0f0; border-radius: 6px; font-size: 0.75rem; color: #666; font-weight: 600;">
                                        <?= $targetInfo[0] ?> <?= $targetInfo[1] ?>
                                    </span>
                                </td>
                                <td class="text-center">
                                    <div class="log-count success"><?= $log['total_sent'] ?></div>
                                </td>
                                <td class="text-center">
                                    <div class="log-count danger"><?= $log['total_failed'] ?></div>
                                </td>
                                <td>
                                    <?php if ($log['status'] === 'completed'): ?>
                                        <span class="badge-modern completed"><i class="bi bi-check-circle-fill"></i> Completed</span>
                                    <?php elseif ($log['status'] === 'partial'): ?>
                                        <span class="badge-modern partial"><i class="bi bi-exclamation-circle-fill"></i> Partial</span>
                                    <?php else: ?>
                                        <span class="badge-modern failed"><i class="bi bi-x-circle-fill"></i> Failed</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <div class="log-user">
                                        <div class="user-avatar-small">
                                            <?= strtoupper(substr($log['created_by_name'] ?? 'U', 0, 1)) ?>
                                        </div>
                                        <span><?= htmlspecialchars($log['created_by_name'] ?? 'Sistem') ?></span>
                                    </div>
                                </td>
                                <td>
                                    <div style="text-align: center;">
                                        <button type="button" class="btn-action view" 
                                                data-bs-toggle="modal" 
                                                data-bs-target="#logModal<?= $log['id'] ?>"
                                                title="Lihat Detail">
                                            <i class="bi bi-eye-fill"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>

                            <!-- Modal Detail -->
                            <div class="modal fade modal-modern" id="logModal<?= $log['id'] ?>" tabindex="-1">
                                <div class="modal-dialog modal-lg modal-dialog-centered">
                                    <div class="modal-content">
                                        <div class="modal-header">
                                            <h5 class="modal-title">
                                                <i class="bi bi-megaphone-fill"></i>
                                                <span>Detail Broadcast</span>
                                            </h5>
                                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                                        </div>
                                        <div class="modal-body">
                                            <div class="detail-row">
                                                <div class="detail-label"><i class="bi bi-tag-fill"></i> Judul</div>
                                                <div class="detail-value"><strong><?= htmlspecialchars($log['title'] ?? '(Tanpa Judul)') ?></strong></div>
                                            </div>
                                            <?php if ($hasSourceColumn): ?>
                                            <div class="detail-row">
                                                <div class="detail-label"><i class="bi bi-signpost-fill"></i> Sumber</div>
                                                <div class="detail-value">
                                                    <span class="badge-source <?= $source ?>">
                                                        <?= $sourceInfo[0] ?> <?= $sourceInfo[1] ?>
                                                    </span>
                                                </div>
                                            </div>
                                            <?php endif; ?>
                                            <div class="detail-row">
                                                <div class="detail-label"><i class="bi bi-calendar3"></i> Tanggal</div>
                                                <div class="detail-value"><strong><?= date('d F Y, H:i', strtotime($log['created_at'])) ?> WIB</strong></div>
                                            </div>
                                            <div class="detail-row">
                                                <div class="detail-label"><i class="bi bi-bullseye"></i> Target</div>
                                                <div class="detail-value">
                                                    <?= $targetInfo[0] ?> <?= $targetInfo[1] ?>
                                                    <span style="color: #999; font-size: 0.8rem; margin-left: 6px;">(Total: <?= $log['total_targets'] ?? 0 ?> nomor)</span>
                                                </div>
                                            </div>
                                            <div class="detail-row">
                                                <div class="detail-label"><i class="bi bi-person-circle"></i> Pengirim</div>
                                                <div class="detail-value"><strong><?= htmlspecialchars($log['created_by_name'] ?? 'Sistem') ?></strong></div>
                                            </div>
                                            <div class="detail-row">
                                                <div class="detail-label"><i class="bi bi-flag-fill"></i> Status</div>
                                                <div class="detail-value">
                                                    <?php if ($log['status'] === 'completed'): ?>
                                                        <span class="badge-modern completed"><i class="bi bi-check-circle-fill"></i> Completed</span>
                                                    <?php elseif ($log['status'] === 'partial'): ?>
                                                        <span class="badge-modern partial"><i class="bi bi-exclamation-circle-fill"></i> Partial</span>
                                                    <?php else: ?>
                                                        <span class="badge-modern failed"><i class="bi bi-x-circle-fill"></i> Failed</span>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                            
                                            <div class="stats-summary">
                                                <div class="stats-item">
                                                    <div class="stats-item-label">Total Target</div>
                                                    <div class="stats-item-value"><?= $log['total_targets'] ?? 0 ?></div>
                                                </div>
                                                <div class="stats-item success">
                                                    <div class="stats-item-label">Terkirim</div>
                                                    <div class="stats-item-value" style="color: #00C853;"><?= $log['total_sent'] ?></div>
                                                </div>
                                                <div class="stats-item danger">
                                                    <div class="stats-item-label">Gagal</div>
                                                    <div class="stats-item-value" style="color: #DC3545;"><?= $log['total_failed'] ?></div>
                                                </div>
                                            </div>
                                            
                                            <div style="margin-top: 16px;">
                                                <div class="detail-label" style="margin-bottom: 8px;">
                                                    <i class="bi bi-chat-left-text-fill"></i> Isi Pesan:
                                                </div>
                                                <div class="message-content-box"><?= htmlspecialchars($log['message'] ?? '') ?></div>
                                            </div>
                                        </div>
                                        <div class="modal-footer">
                                            <button type="button" class="btn-modal secondary" data-bs-dismiss="modal">Tutup</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </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' : '';
    }
}
</script>

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