<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../classes/Broadcast.php';
requireRole('super_admin');
$pageTitle = 'Broadcast Logs';

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

try {
    $logs = Broadcast::getAllLogs($branchFilter ?: null, 200);
    $stats = Broadcast::getStats($branchFilter ?: null);
} catch (\Throwable $e) {
    $logs = [];
    $stats = ['total_broadcasts' => 0, 'total_sent' => 0, 'total_failed' => 0, 'completed_count' => 0, 'partial_count' => 0, 'failed_count' => 0];
    $error = 'Error loading data: ' . $e->getMessage();
}

// Get branches for filter
$db = db();
$branches = $db->query("SELECT id, name FROM branches ORDER BY name")->fetchAll();

// Filter by status (manual filter)
if ($statusFilter) {
    $logs = array_filter($logs, fn($l) => $l['status'] === $statusFilter);
}

require __DIR__ . '/../includes/header.php';
require __DIR__ . '/../includes/sidebar.php';
?>
<div class="main-content">
  <h3><i class="bi bi-clock-history me-2"></i>Broadcast Logs</h3>
  
  <?= flashMessage() ?>
  
  <?php if (!empty($error)): ?>
    <div class="alert alert-danger alert-dismissible fade show">
      <?= htmlspecialchars($error) ?>
      <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
  <?php endif; ?>
  
  <!-- Stats Cards -->
  <div class="row g-3 mb-4">
    <div class="col-md-3">
      <div class="card border-primary">
        <div class="card-body text-center">
          <h6 class="text-muted mb-1">Total Broadcast</h6>
          <h2 class="text-primary mb-0"><?= $stats['total_broadcasts'] ?? 0 ?></h2>
        </div>
      </div>
    </div>
    <div class="col-md-3">
      <div class="card border-success">
        <div class="card-body text-center">
          <h6 class="text-muted mb-1">Pesan Terkirim</h6>
          <h2 class="text-success mb-0"><?= $stats['total_sent'] ?? 0 ?></h2>
        </div>
      </div>
    </div>
    <div class="col-md-3">
      <div class="card border-danger">
        <div class="card-body text-center">
          <h6 class="text-muted mb-1">Pesan Gagal</h6>
          <h2 class="text-danger mb-0"><?= $stats['total_failed'] ?? 0 ?></h2>
        </div>
      </div>
    </div>
    <div class="col-md-3">
      <div class="card border-info">
        <div class="card-body text-center">
          <h6 class="text-muted mb-1">Success Rate</h6>
          <?php 
          $totalMessages = ($stats['total_sent'] ?? 0) + ($stats['total_failed'] ?? 0);
          $rate = $totalMessages > 0 ? round(($stats['total_sent'] / $totalMessages) * 100, 1) : 0;
          ?>
          <h2 class="text-info mb-0"><?= $rate ?>%</h2>
        </div>
      </div>
    </div>
  </div>
  
  <!-- Filter -->
  <div class="card mb-3">
    <div class="card-body">
      <form method="GET" class="row g-2 align-items-end">
        <div class="col-md-4">
          <label class="form-label small">Cabang</label>
          <select name="branch" class="form-select form-select-sm">
            <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>
        <div class="col-md-4">
          <label class="form-label small">Status</label>
          <select name="status" class="form-select form-select-sm">
            <option value="">Semua Status</option>
            <option value="completed" <?= $statusFilter === 'completed' ? 'selected' : '' ?>>Completed</option>
            <option value="partial" <?= $statusFilter === 'partial' ? 'selected' : '' ?>>Partial</option>
            <option value="failed" <?= $statusFilter === 'failed' ? 'selected' : '' ?>>Failed</option>
          </select>
        </div>
        <div class="col-md-4 d-flex gap-2">
          <button type="submit" class="btn btn-primary btn-sm flex-fill">
            <i class="bi bi-funnel"></i> Filter
          </button>
          <a href="/admin/broadcast_logs.php" class="btn btn-outline-secondary btn-sm">
            <i class="bi bi-x-lg"></i>
          </a>
        </div>
      </form>
    </div>
  </div>
  
  <!-- Logs Table -->
  <div class="card">
    <div class="card-header">
      <i class="bi bi-list-ul me-2"></i>Riwayat Broadcast
      <span class="badge bg-secondary ms-2"><?= count($logs) ?></span>
    </div>
    <div class="card-body p-0">
      <?php if (empty($logs)): ?>
        <div class="text-center py-5 text-muted">
          <i class="bi bi-inbox fs-1"></i>
          <p class="mt-2">Belum ada broadcast</p>
        </div>
      <?php else: ?>
        <div class="table-responsive">
          <table class="table table-hover mb-0">
            <thead class="table-light">
              <tr>
                <th>Tanggal</th>
                <th>Judul</th>
                <th>Cabang</th>
                <th>Target</th>
                <th>Terkirim</th>
                <th>Gagal</th>
                <th>Status</th>
                <th>Oleh</th>
                <th>Aksi</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($logs as $log): ?>
                <?php 
                $targetData = json_decode($log['target_data'] ?? '[]', true);
                $targetCount = 0;
                $targetLabel = '';
                
                switch ($log['target_type']) {
                    case 'all_customers':
                        $targetLabel = 'Semua Customer';
                        $targetCount = $log['total_sent'] + $log['total_failed'];
                        break;
                    case 'selected_customers':
                        $targetLabel = 'Customer Terpilih';
                        $targetCount = is_array($targetData) ? count($targetData) : 0;
                        break;
                    case 'branch':
                        $targetLabel = 'Cabang Tertentu';
                        $targetCount = $log['total_sent'] + $log['total_failed'];
                        break;
                    case 'custom_numbers':
                        $targetLabel = 'Nomor Custom';
                        $targetCount = isset($targetData['numbers']) ? count($targetData['numbers']) : 0;
                        break;
                }
                ?>
                <tr>
                  <td>
                    <small><?= date('d/m/Y H:i', strtotime($log['created_at'])) ?></small>
                  </td>
                  <td>
                    <strong><?= htmlspecialchars($log['title'] ?? '(Tanpa Judul)') ?></strong>
                    <br><small class="text-muted"><?= htmlspecialchars(substr($log['message'], 0, 50)) ?>...</small>
                  </td>
                  <td>
                    <small><?= htmlspecialchars($log['branch_name'] ?? 'Pusat') ?></small>
                  </td>
                  <td>
                    <small>
                      <span class="badge bg-info"><?= htmlspecialchars($targetLabel) ?></span>
                      <br><?= $targetCount ?> target
                    </small>
                  </td>
                  <td>
                    <span class="text-success fw-bold"><?= $log['total_sent'] ?? 0 ?></span>
                  </td>
                  <td>
                    <span class="text-danger fw-bold"><?= $log['total_failed'] ?? 0 ?></span>
                  </td>
                  <td>
                    <?php if ($log['status'] === 'completed'): ?>
                      <span class="badge bg-success"><i class="bi bi-check-circle"></i> Completed</span>
                    <?php elseif ($log['status'] === 'partial'): ?>
                      <span class="badge bg-warning text-dark"><i class="bi bi-exclamation-circle"></i> Partial</span>
                    <?php elseif ($log['status'] === 'failed'): ?>
                      <span class="badge bg-danger"><i class="bi bi-x-circle"></i> Failed</span>
                    <?php endif; ?>
                  </td>
                  <td>
                    <small><?= htmlspecialchars($log['created_by_name'] ?? '-') ?></small>
                  </td>
                  <td>
                    <button type="button" class="btn btn-sm btn-outline-primary" 
                            data-bs-toggle="modal" data-bs-target="#detailModal<?= $log['id'] ?>">
                      <i class="bi bi-eye"></i>
                    </button>
                    
                    <!-- Detail Modal -->
                    <div class="modal fade" id="detailModal<?= $log['id'] ?>" tabindex="-1">
                      <div class="modal-dialog modal-lg">
                        <div class="modal-content">
                          <div class="modal-header bg-primary text-white">
                            <h5 class="modal-title">Detail Broadcast</h5>
                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                          </div>
                          <div class="modal-body">
                            <div class="row mb-3">
                              <div class="col-md-6">
                                <strong>Judul:</strong><br>
                                <?= htmlspecialchars($log['title'] ?? '-') ?>
                              </div>
                              <div class="col-md-6">
                                <strong>Tanggal:</strong><br>
                                <?= date('d/m/Y H:i:s', strtotime($log['created_at'])) ?>
                              </div>
                            </div>
                            
                            <div class="mb-3">
                              <strong>Pesan:</strong>
                              <pre class="bg-light p-3 rounded mt-2" style="white-space: pre-wrap;"><?= htmlspecialchars($log['message']) ?></pre>
                            </div>
                            
                            <div class="row">
                              <div class="col-md-4">
                                <strong>Target Type:</strong><br>
                                <span class="badge bg-info"><?= htmlspecialchars($targetLabel) ?></span>
                              </div>
                              <div class="col-md-4">
                                <strong>Terkirim:</strong><br>
                                <span class="text-success fw-bold"><?= $log['total_sent'] ?></span>
                              </div>
                              <div class="col-md-4">
                                <strong>Gagal:</strong><br>
                                <span class="text-danger fw-bold"><?= $log['total_failed'] ?></span>
                              </div>
                            </div>
                            
                            <?php if (!empty($targetData)): ?>
                              <hr>
                              <strong>Target Data:</strong>
                              <pre class="bg-light p-2 rounded mt-2 small"><?= htmlspecialchars(json_encode($targetData, JSON_PRETTY_PRINT)) ?></pre>
                            <?php endif; ?>
                          </div>
                          <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
                          </div>
                        </div>
                      </div>
                    </div>
                  </td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      <?php endif; ?>
    </div>
  </div>
</div>
<?php require __DIR__ . '/../includes/footer.php'; ?>