<?php
require_once __DIR__ . '/../config/whatsapp.php';
require_once __DIR__ . '/../config/topup.php';

if (!isset($data_admin['agent_level'], $data_admin['agent_name']) || !in_array($data_admin['agent_level'], ['admin', 'head_agent'], true)) {
    header("Location: index");
    exit();
}

$isAdmin = $data_admin['agent_level'] === 'admin';
$canManageAgentRate = $isAdmin;
$currentAgentName = agent_public_name((array)$data_admin);
$currentAgentRefs = agent_identity_values((array)$data_admin);
$hasWhatsappTable = wa_ensure_agent_contact_table($call);
$globalRateCoin = topup_get_global_rate($call);
topup_ensure_agent_rate_column($call);

$agentRows = [];
$agentTotal = 0;
$activeAgentTotal = 0;
$blockedAgentTotal = 0;
$agentBalanceTotal = 0.0;
$baseSelect = $hasWhatsappTable
    ? "SELECT a.*, c.whatsapp AS agent_whatsapp FROM tb_agent a LEFT JOIN tb_agent_contact c ON c.agent_code = a.agent_name OR c.agent_code = a.agent_code"
    : "SELECT a.*, '' AS agent_whatsapp FROM tb_agent a";

if ($isAdmin) {
    $query = $baseSelect . " ORDER BY a.id DESC";
    $result = mysqli_query($call, $query);
} else {
    $uplineWhere = agent_reference_condition($call, 'a.agent_upline', $data_admin);
    $query = $baseSelect . " WHERE $uplineWhere ORDER BY a.id DESC";
    $result = mysqli_query($call, $query);
}

if ($result) {
    while ($agentRow = mysqli_fetch_assoc($result)) {
        $statusValue = strtolower((string)($agentRow['agent_status'] ?? ''));
        $agentTotal++;
        if ($statusValue === 'blocked') {
            $blockedAgentTotal++;
        } else {
            $activeAgentTotal++;
        }
        $agentBalanceTotal += (float)($agentRow['agent_balance'] ?? 0);
        $agentRows[] = $agentRow;
    }
}

?>

<?php if (isset($_GET['alert'])): ?>
<script>
document.addEventListener("DOMContentLoaded", function () {
    <?php if ($_GET['alert'] === 'delete_success'): ?>
        alert("✅ Agent berhasil dihapus");
    <?php elseif ($_GET['alert'] === 'delete_failed'): ?>
        alert("❌ Gagal menghapus agent");
    <?php elseif ($_GET['alert'] === 'has_downline'): ?>
        alert("⚠️ Agent tidak bisa dihapus karena masih memiliki downline");
    <?php elseif ($_GET['alert'] === 'self_delete'): ?>
        alert("⚠️ Anda tidak bisa menghapus akun sendiri");
    <?php elseif ($_GET['alert'] === 'access_denied'): ?>
        alert("❌ Akses ditolak");
    <?php else: ?>
        alert("⚠️ Terjadi kesalahan");
    <?php endif; ?>
});
</script>
<?php endif; ?>

<div class="app-page-shell">
    <div class="row g-4">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h4 class="card-title mb-1">Daftar Akun Agent</h4>
                <p class="text-muted mb-0">Gunakan aksi cepat untuk edit akun, topup, atau blokir akses.</p>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table id="dataTableExample" class="table table-striped table-hover align-middle">
                        <thead class="table-light">
                            <tr>
                                <th>Agent Name</th>
                                <th>WhatsApp</th>
                                <th>Agent Level</th>
                                <th>Agent Balance</th>
                                <th>Rate Topup</th>
                                <th>Agent Downline</th>
                                <th>Agent Status</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            foreach ($agentRows as $agentRow) {
                                $statusValue = strtolower((string)($agentRow['agent_status'] ?? ''));
                                $statusClass = $statusValue === 'blocked' ? 'bg-light-danger text-danger' : 'bg-light-success text-success';
                                $statusLabel = $statusValue === 'blocked' ? 'Blocked' : 'Active';
                                $agentWhatsapp = wa_normalize_number((string)($agentRow['agent_whatsapp'] ?? ''));
                                $agentBalanceRaw = (string)($agentRow['agent_balance'] ?? '0');
                                $agentBalanceFormatted = number_format((float)$agentBalanceRaw, 0, ',', '.');
                                $agentRate = (float)($agentRow['rate_coin'] ?? 0);
                                if ($agentRate <= 0) {
                                    $agentRate = $globalRateCoin;
                                }
                                $agentRateFormatted = rtrim(rtrim(number_format($agentRate, 4, '.', ''), '0'), '.');
                                $agentIdentity = agent_public_name((array)$agentRow);
                                $isSelfRow = in_array($agentIdentity, $currentAgentRefs, true)
                                    || in_array((string)($agentRow['agent_code'] ?? ''), $currentAgentRefs, true);
                            ?>
                                <tr>
                                    <td><?= htmlspecialchars((string)($agentRow['agent_name'] ?? ''), ENT_QUOTES, 'UTF-8') ?></td>
                                    <td><?= $agentWhatsapp !== '' ? htmlspecialchars($agentWhatsapp, ENT_QUOTES, 'UTF-8') : '-' ?></td>
                                    <td><?= htmlspecialchars((string)($agentRow['agent_level'] ?? ''), ENT_QUOTES, 'UTF-8') ?></td>
                                    <td class="text-end"><?= $agentBalanceFormatted ?></td>
                                    <td class="text-end"><?= htmlspecialchars($agentRateFormatted, ENT_QUOTES, 'UTF-8') ?></td>
                                    <td><?= htmlspecialchars(topup_agent_name($call, (string)($agentRow['agent_upline'] ?? '')), ENT_QUOTES, 'UTF-8') ?></td>
                                    <td><span class="badge <?= $statusClass ?>"><?= htmlspecialchars($statusLabel, ENT_QUOTES, 'UTF-8') ?></span></td>
                                    <td>
                                        <div class="d-flex flex-wrap gap-2">
                                            <button
                                                type="button"
                                                class="btn btn-outline-warning btn-sm edit-agent-account-btn"
                                                data-id="<?= htmlspecialchars($agentIdentity, ENT_QUOTES, 'UTF-8') ?>"
                                                data-name="<?= htmlspecialchars((string)($agentRow['agent_name'] ?? ''), ENT_QUOTES, 'UTF-8') ?>"
                                                data-level="<?= htmlspecialchars((string)($agentRow['agent_level'] ?? ''), ENT_QUOTES, 'UTF-8') ?>"
                                                data-status="<?= htmlspecialchars((string)($agentRow['agent_status'] ?? ''), ENT_QUOTES, 'UTF-8') ?>"
                                                data-whatsapp="<?= htmlspecialchars($agentWhatsapp, ENT_QUOTES, 'UTF-8') ?>"
                                                data-rate="<?= htmlspecialchars($agentRateFormatted, ENT_QUOTES, 'UTF-8') ?>"
                                                data-bs-toggle="modal"
                                                data-bs-target="#editAgentAccountModal">
                                                Edit Akun
                                            </button>

                                            <?php if (!$isSelfRow): ?>
                                            <button
                                                type="button"
                                                class="btn btn-outline-primary btn-sm topup-agent-btn"
                                                data-id="<?= htmlspecialchars($agentIdentity, ENT_QUOTES, 'UTF-8') ?>"
                                                data-name="<?= htmlspecialchars((string)($agentRow['agent_name'] ?? ''), ENT_QUOTES, 'UTF-8') ?>"
                                                data-balance="<?= htmlspecialchars($agentBalanceRaw, ENT_QUOTES, 'UTF-8') ?>"
                                                data-balance-formatted="<?= htmlspecialchars($agentBalanceFormatted, ENT_QUOTES, 'UTF-8') ?>"
                                                data-rate="<?= htmlspecialchars($agentRateFormatted, ENT_QUOTES, 'UTF-8') ?>"
                                                data-bs-toggle="modal"
                                                data-bs-target="#topupAgentModal">
                                                Topup
                                            </button>
                                            <?php endif; ?>

                                            <?php if ($isAdmin): ?>
                                            <form action="function/delete_agent.php" method="POST" class="m-0">
                                                <input
                                                    type="hidden"
                                                    name="agent_identifier"
                                                    value="<?= htmlspecialchars($agentIdentity, ENT_QUOTES, 'UTF-8') ?>">
                                                <button
                                                    type="submit"
                                                    name="delete_agent"
                                                    class="btn btn-outline-danger btn-sm"
                                                    onclick="return confirm('Yakin ingin menghapus agent ini?');">
                                                    Hapus
                                                </button>
                                            </form>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                            <?php
                            }
                            ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
</div>

<div class="modal fade" id="editAgentAccountModal" tabindex="-1" aria-labelledby="editAgentAccountModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editAgentAccountModalLabel">Edit Akun Agent</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form action="function/update_agent.php" method="POST" id="editAgentAccountForm">
                    <input type="hidden" id="editAgentAccountIdentifier" name="agent_identifier">

                    <div class="mb-3">
                        <label class="form-label">Current Agent Name</label>
                        <input type="text" class="form-control" id="editAgentAccountIdentifierView" readonly>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Agent Name</label>
                        <input type="text" class="form-control" id="editAgentAccountName" name="agent_name" required>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">WhatsApp Agent</label>
                        <input type="text" class="form-control" id="editAgentWhatsapp" name="agent_whatsapp" placeholder="08xxxxxxxxxx / 628xxxxxxxxxx">
                        <small class="text-muted">Nomor ini dipakai untuk notif login dan akses bot topup via WhatsApp.</small>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Agent Level</label>
                        <?php if ($isAdmin): ?>
                        <select class="form-select" id="editAgentAccountLevel" name="agent_level" required>
                            <option value="admin">Admin</option>
                            <option value="head_agent">Head Agent</option>
                            <option value="agent">Agent</option>
                        </select>
                        <?php else: ?>
                        <input type="hidden" name="agent_level" value="agent">
                        <input type="text" class="form-control" value="agent" readonly>
                        <?php endif; ?>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Agent Status</label>
                        <select class="form-select" id="editAgentAccountStatus" name="agent_status" required>
                            <option value="active">Active</option>
                            <option value="blocked">Inactive</option>
                        </select>
                    </div>

                    <?php if ($canManageAgentRate): ?>
                    <div class="mb-3">
                        <label class="form-label">Rate Topup Agent</label>
                        <input type="number" class="form-control" id="editAgentRateCoin" name="agent_rate_coin" min="0.0001" step="0.0001" required>
                        <small class="text-muted">Rate adalah persen harga coin. Contoh rate 8: topup Rp80.000 menjadi 1.000.000 coin.</small>
                    </div>
                    <?php endif; ?>

                    <button type="submit" name="save_agent_account" class="btn btn-primary">Save Changes</button>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="topupAgentModal" tabindex="-1" aria-labelledby="topupAgentModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="topupAgentModalLabel">Topup / Balance Agent</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form action="function/update_agent_balance.php" method="POST" id="topupAgentForm">
                    <input type="hidden" id="topupAgentIdentifier" name="agent_identifier">

                    <div class="mb-3">
                        <label class="form-label">Agent Terpilih</label>
                        <input type="text" class="form-control" id="topupAgentIdentifierView" readonly>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Agent Name</label>
                        <input type="text" class="form-control" id="topupAgentName" readonly>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Balance Saat Ini</label>
                        <input type="text" class="form-control" id="topupCurrentBalance" readonly>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Jumlah Balance</label>
                        <input type="number" class="form-control" id="topupBalanceAmount" name="agent_balance" min="1" step="1" required>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Balance Action</label>
                        <select class="form-select" id="topupBalanceAction" name="balance_action" required>
                            <option value="12">Add Balance</option>
                            <option value="11">Reduce Balance</option>
                        </select>
                    </div>

                    <?php if ($isAdmin): ?>
                    <div class="mb-3">
                        <label class="form-label">Estimasi Nominal (IDR)</label>
                        <input type="text" class="form-control" id="topupEstimatedAmount" readonly>
                        <small class="text-muted" id="topupRateHint">Rate sedang dimuat...</small>
                    </div>
                    <?php endif; ?>

                    <button type="submit" name="edit_agent_balance" class="btn btn-primary">Proses Balance</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener("DOMContentLoaded", function () {
    const numberFormatter = new Intl.NumberFormat("id-ID");
    const editButtons = document.querySelectorAll(".edit-agent-account-btn");
    const topupButtons = document.querySelectorAll(".topup-agent-btn");

    const editAgentIdentifier = document.getElementById("editAgentAccountIdentifier");
    const editAgentIdentifierView = document.getElementById("editAgentAccountIdentifierView");
    const editAgentName = document.getElementById("editAgentAccountName");
    const editAgentWhatsapp = document.getElementById("editAgentWhatsapp");
    const editAgentLevel = document.getElementById("editAgentAccountLevel");
    const editAgentStatus = document.getElementById("editAgentAccountStatus");
    const editAgentRateCoin = document.getElementById("editAgentRateCoin");

    editButtons.forEach(function (button) {
        button.addEventListener("click", function () {
            const agentIdentifier = this.dataset.id || "";
            const agentName = this.dataset.name || "";
            const agentWhatsapp = this.dataset.whatsapp || "";
            const agentLevel = this.dataset.level || "agent";
            const agentStatus = (this.dataset.status || "active").toLowerCase();
            const agentRate = this.dataset.rate || "";

            editAgentIdentifier.value = agentIdentifier;
            editAgentIdentifierView.value = agentIdentifier;
            editAgentName.value = agentName;
            editAgentWhatsapp.value = agentWhatsapp;
            if (editAgentRateCoin) {
                editAgentRateCoin.value = agentRate;
            }

            if (editAgentLevel) {
                editAgentLevel.value = agentLevel;
            }

            editAgentStatus.value = agentStatus === "blocked" ? "blocked" : "active";
        });
    });

    const topupAgentIdentifier = document.getElementById("topupAgentIdentifier");
    const topupAgentIdentifierView = document.getElementById("topupAgentIdentifierView");
    const topupAgentName = document.getElementById("topupAgentName");
    const topupCurrentBalance = document.getElementById("topupCurrentBalance");
    const topupBalanceAmount = document.getElementById("topupBalanceAmount");
    const topupBalanceAction = document.getElementById("topupBalanceAction");
    const topupEstimatedAmount = document.getElementById("topupEstimatedAmount");
    const topupRateHint = document.getElementById("topupRateHint");

    let rateCoin = 7.5;

    function updateTopupEstimate() {
        if (!topupEstimatedAmount) {
            return;
        }

        const balanceAmount = parseFloat(topupBalanceAmount.value || "0");
        const estimatedAmount = rateCoin > 0 ? Math.floor(balanceAmount * (rateCoin / 100)) : 0;

        topupEstimatedAmount.value = numberFormatter.format(estimatedAmount);
    }

    topupButtons.forEach(function (button) {
        button.addEventListener("click", function () {
            const agentIdentifier = this.dataset.id || "";
            const agentName = this.dataset.name || "";
            const currentBalance = parseFloat(this.dataset.balance || "0");
            const agentRate = parseFloat(this.dataset.rate || "0");

            if (agentRate > 0) {
                rateCoin = agentRate;
            }

            topupAgentIdentifier.value = agentIdentifier;
            topupAgentIdentifierView.value = agentIdentifier;
            topupAgentName.value = agentName;
            topupCurrentBalance.value = numberFormatter.format(currentBalance);
            topupBalanceAmount.value = "";
            topupBalanceAction.value = "12";
            if (topupRateHint) {
                topupRateHint.textContent = "Rate agent: " + rateCoin + "% dari jumlah coin.";
            }
            updateTopupEstimate();
        });
    });

    if (topupBalanceAmount) {
        topupBalanceAmount.addEventListener("input", updateTopupEstimate);
    }

    if (topupBalanceAction) {
        topupBalanceAction.addEventListener("change", updateTopupEstimate);
    }

    if (topupEstimatedAmount && topupRateHint) {
        topupRateHint.textContent = "Pilih agent untuk melihat rate.";
    }
});
</script>
