<?php
/*
 * Admin Panel - Daftar Agent
 * Integrated with MikhMon Sidebar
 */

// No session_start() needed - already started in index.php
// No auth check needed - already checked in index.php

include_once('./include/db_config.php');
include_once('./lib/Agent.class.php');

$agent = new Agent();
$agents = $agent->getAllAgents();

// Handle actions
if (isset($_GET['action'])) {
    $action = $_GET['action'];
    $agentId = $_GET['agent_id'] ?? 0;
    
    if ($action == 'activate' && $agentId) {
        $agent->updateAgent($agentId, ['status' => 'active']);
        echo "<script>alert('Agent berhasil diaktifkan'); window.location='?hotspot=agent-list&session=$session';</script>";
    } elseif ($action == 'deactivate' && $agentId) {
        $agent->updateAgent($agentId, ['status' => 'inactive']);
        echo "<script>alert('Agent berhasil dinonaktifkan'); window.location='?hotspot=agent-list&session=$session';</script>";
    } elseif ($action == 'delete' && $agentId) {
        if (confirm('Yakin ingin menghapus agent ini?')) {
            $agent->deleteAgent($agentId);
            echo "<script>alert('Agent berhasil dihapus'); window.location='?hotspot=agent-list&session=$session';</script>";
        }
    }
}

function formatRupiah($amount) {
    return 'Rp ' . number_format($amount, 0, ',', '.');
}
?>

<style>
.agent-container {
    padding: 20px;
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.page-header h2 {
    margin: 0;
    color: #333;
}

.btn {
    padding: 10px 20px;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    text-decoration: none;
    display: inline-block;
    font-weight: 500;
}

.btn-primary {
    background: #667eea;
    color: white;
}

.btn-success {
    background: #10b981;
    color: white;
}

.btn-danger {
    background: #ef4444;
    color: white;
}

.btn-warning {
    background: #f59e0b;
    color: white;
}

.btn-sm {
    padding: 5px 10px;
    font-size: 12px;
}

.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 15px;
    margin-bottom: 20px;
}

.stat-card {
    background: white;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.stat-card h3 {
    margin: 0 0 10px 0;
    font-size: 14px;
    color: #666;
}

.stat-card .value {
    font-size: 24px;
    font-weight: bold;
    color: #333;
}

.agent-table {
    background: white;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    overflow: hidden;
}

.table-header {
    padding: 15px 20px;
    background: #f8f9fa;
    border-bottom: 1px solid #e0e0e0;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.search-box {
    padding: 8px 15px;
    border: 1px solid #e0e0e0;
    border-radius: 5px;
    width: 300px;
}

table {
    width: 100%;
    border-collapse: collapse;
}

table th {
    background: #f8f9fa;
    padding: 12px;
    text-align: left;
    font-weight: 600;
    color: #333;
    border-bottom: 2px solid #e0e0e0;
}

table td {
    padding: 12px;
    border-bottom: 1px solid #f0f0f0;
}

table tr:hover {
    background: #f8f9fa;
}

.badge {
    padding: 4px 12px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 600;
}

.badge-active {
    background: #d1fae5;
    color: #065f46;
}

.badge-inactive {
    background: #fee2e2;
    color: #991b1b;
}

.badge-suspended {
    background: #fef3c7;
    color: #92400e;
}

.badge-bronze { background: #fef3c7; color: #92400e; }
.badge-silver { background: #e5e7eb; color: #374151; }
.badge-gold { background: #fef3c7; color: #92400e; }
.badge-platinum { background: #dbeafe; color: #1e40af; }

.action-buttons {
    display: flex;
    gap: 5px;
}

.empty-state {
    text-align: center;
    padding: 60px 20px;
    color: #999;
}

.empty-state i {
    font-size: 64px;
    margin-bottom: 20px;
    opacity: 0.3;
}
</style>

<div class="agent-container">
    <div class="page-header">
        <div>
            <h2><i class="fa fa-users"></i> Daftar Agent/Reseller</h2>
            <p style="margin: 5px 0 0 0; color: #666;">Kelola agent dan reseller voucher</p>
        </div>
        <a href="./?hotspot=agent-add&session=<?= $session; ?>" class="btn btn-primary">
            <i class="fa fa-plus"></i> Tambah Agent
        </a>
    </div>

    <!-- Statistics -->
    <div class="stats-grid">
        <div class="stat-card">
            <h3>Total Agent</h3>
            <div class="value"><?= count($agents); ?></div>
        </div>
        <div class="stat-card">
            <h3>Agent Aktif</h3>
            <div class="value" style="color: #10b981;">
                <?= count(array_filter($agents, function($a) { return $a['status'] == 'active'; })); ?>
            </div>
        </div>
        <div class="stat-card">
            <h3>Total Saldo</h3>
            <div class="value" style="color: #667eea;">
                <?= formatRupiah(array_sum(array_column($agents, 'balance'))); ?>
            </div>
        </div>
        <div class="stat-card">
            <h3>Agent Baru (Bulan Ini)</h3>
            <div class="value" style="color: #f59e0b;">
                <?= count(array_filter($agents, function($a) { 
                    return date('Y-m', strtotime($a['created_at'])) == date('Y-m'); 
                })); ?>
            </div>
        </div>
    </div>

    <!-- Agent Table -->
    <div class="agent-table">
        <div class="table-header">
            <h3 style="margin: 0;">Daftar Agent</h3>
            <input type="text" id="searchAgent" class="search-box" placeholder="Cari agent..." onkeyup="searchTable()">
        </div>

        <?php if (empty($agents)): ?>
        <div class="empty-state">
            <i class="fa fa-users"></i>
            <h3>Belum Ada Agent</h3>
            <p>Klik tombol "Tambah Agent" untuk menambahkan agent baru</p>
        </div>
        <?php else: ?>
        <table id="agentTable">
            <thead>
                <tr>
                    <th>Kode</th>
                    <th>Nama</th>
                    <th>No. WhatsApp</th>
                    <th>Level</th>
                    <th>Saldo</th>
                    <th>Komisi</th>
                    <th>Status</th>
                    <th>Terdaftar</th>
                    <th>Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($agents as $agt): ?>
                <tr>
                    <td><strong><?= $agt['agent_code']; ?></strong></td>
                    <td><?= $agt['agent_name']; ?></td>
                    <td><?= $agt['phone']; ?></td>
                    <td><span class="badge badge-<?= $agt['level']; ?>"><?= ucfirst($agt['level']); ?></span></td>
                    <td><strong><?= formatRupiah($agt['balance']); ?></strong></td>
                    <td><?= $agt['commission_percent']; ?>%</td>
                    <td>
                        <span class="badge badge-<?= $agt['status']; ?>">
                            <?= ucfirst($agt['status']); ?>
                        </span>
                    </td>
                    <td><?= date('d M Y', strtotime($agt['created_at'])); ?></td>
                    <td>
                        <div class="action-buttons">
                            <a href="./?hotspot=agent-edit&agent_id=<?= $agt['id']; ?>&session=<?= $session; ?>" 
                               class="btn btn-warning btn-sm" title="Edit">
                                <i class="fa fa-edit"></i>
                            </a>
                            <a href="./?hotspot=agent-topup&agent_id=<?= $agt['id']; ?>&session=<?= $session; ?>" 
                               class="btn btn-success btn-sm" title="Topup">
                                <i class="fa fa-money"></i>
                            </a>
                            <?php if ($agt['status'] == 'active'): ?>
                            <a href="?hotspot=agent-list&action=deactivate&agent_id=<?= $agt['id']; ?>&session=<?= $session; ?>" 
                               class="btn btn-danger btn-sm" title="Nonaktifkan"
                               onclick="return confirm('Nonaktifkan agent ini?')">
                                <i class="fa fa-ban"></i>
                            </a>
                            <?php else: ?>
                            <a href="?hotspot=agent-list&action=activate&agent_id=<?= $agt['id']; ?>&session=<?= $session; ?>" 
                               class="btn btn-success btn-sm" title="Aktifkan"
                               onclick="return confirm('Aktifkan agent ini?')">
                                <i class="fa fa-check"></i>
                            </a>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <?php endif; ?>
    </div>
</div>

<script>
function searchTable() {
    const input = document.getElementById('searchAgent');
    const filter = input.value.toUpperCase();
    const table = document.getElementById('agentTable');
    const tr = table.getElementsByTagName('tr');

    for (let i = 1; i < tr.length; i++) {
        let found = false;
        const td = tr[i].getElementsByTagName('td');
        
        for (let j = 0; j < td.length; j++) {
            if (td[j]) {
                const txtValue = td[j].textContent || td[j].innerText;
                if (txtValue.toUpperCase().indexOf(filter) > -1) {
                    found = true;
                    break;
                }
            }
        }
        
        tr[i].style.display = found ? '' : 'none';
    }
}
</script>
