<?php
// =========================================================================
// admin/monitoring_user_llm.php - CRM & SAAS BILLING MANAGEMENT
// Developer: Sikawarsito, S.Kom
// =========================================================================

session_start();
include '../../config/database.php'; // Sesuaikan jalur jika diperlukan

if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../../auth/login_page.php");
    exit;
}

// 1. AKSI: KIRIM PESAN POP-UP
if (isset($_POST['send_message'])) {
    $uid = (int)$_POST['user_id'];
    $pesan = mysqli_real_escape_string($conn, $_POST['pesan_popup']);
    mysqli_query($conn, "UPDATE users SET llm_message = '$pesan' WHERE id = $uid");
    $_SESSION['msg'] = "Pesan pop-up berhasil dikirim!";
    header("Location: monitoring_user_llm.php");
    exit;
}

// 2. AKSI: EDIT STATUS AKUN (FREE / PRO)
if (isset($_POST['edit_tier'])) {
    $uid = (int)$_POST['user_id'];
    $tier = mysqli_real_escape_string($conn, $_POST['status_akun']);
    $expiry = !empty($_POST['pro_expiry']) ? "'" . mysqli_real_escape_string($conn, $_POST['pro_expiry']) . "'" : "NULL";
    
    mysqli_query($conn, "UPDATE users SET status_akun = '$tier', llm_pro_expiry = $expiry WHERE id = $uid");
    $_SESSION['msg'] = "Tipe Akun berlangganan berhasil diperbarui!";
    header("Location: monitoring_user_llm.php");
    exit;
}

// 3. AKSI: BLOKIR / BUKA BLOKIR / HAPUS API
if (isset($_GET['action']) && isset($_GET['uid'])) {
    $uid = (int)$_GET['uid'];
    if ($_GET['action'] == 'block') {
        mysqli_query($conn, "UPDATE users SET llm_status = 'blocked', llm_message = 'Akses API Dibekukan.' WHERE id = $uid");
    } elseif ($_GET['action'] == 'unblock') {
        mysqli_query($conn, "UPDATE users SET llm_status = 'active', llm_message = 'Akses API Dipulihkan.' WHERE id = $uid");
    } elseif ($_GET['action'] == 'delete_api') {
        mysqli_query($conn, "DELETE FROM api_key_bot WHERE user_id = $uid");
    }
    $_SESSION['msg'] = "Tindakan berhasil dieksekusi.";
    header("Location: monitoring_user_llm.php");
    exit;
}

// Filter Pencarian
$search = isset($_GET['search']) ? mysqli_real_escape_string($conn, $_GET['search']) : '';
$whereClause = "";
if (!empty($search)) {
    $whereClause = "WHERE u.username LIKE '%$search%' OR u.email_guru LIKE '%$search%'";
}

// Ambil Data User (Hanya yang punya API Key)
$query_users = mysqli_query($conn, "
    SELECT u.id, u.username, u.email_guru, u.llm_status, u.llm_message, u.status_akun, u.llm_kredit_terpakai, u.llm_pro_expiry,
           COUNT(k.id) as total_keys,
           SUM(k.usage_count) as total_usage,
           GROUP_CONCAT(k.nama_project SEPARATOR '<br>') as projects
    FROM users u
    JOIN api_key_bot k ON u.id = k.user_id
    $whereClause
    GROUP BY u.id
    ORDER BY total_usage DESC
");

$pesan_notif = "";
if (isset($_SESSION['msg'])) { $pesan_notif = $_SESSION['msg']; unset($_SESSION['msg']); }
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SaaS Billing & User Monitor - Admin</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <style>
        body { background-color: #f0f4f9; font-family: 'Inter', sans-serif; }
        .card-premium { background: #ffffff; border: 1px solid #e2e8f0; border-radius: 20px; box-shadow: 0 4px 20px rgba(0,0,0,0.04); }
        .table-keys th { background: #f8fafc; font-weight: 600; color: #64748b; font-size: 13px; text-transform: uppercase; }
        .usage-badge { font-weight: bold; font-family: monospace; font-size: 14px; background: #e8f0fe; color: #1a73e8; padding: 5px 12px; border-radius: 8px; }
    </style>
</head>
<body>
    <div class="container-fluid py-5 px-4">
        <div class="row align-items-center mb-4">
            <div class="col-md-5">
                <h2 class="fw-bold m-0 text-dark">
                    <i class="bi bi-wallet2 text-primary me-2"></i> Billing & User Monitor
                </h2>
            </div>
            <div class="col-md-4 mt-3 mt-md-0">
                <form method="GET" action="">
                    <div class="input-group shadow-sm">
                        <input type="text" name="search" class="form-control border-end-0 bg-white" style="border-radius: 50rem 0 0 50rem;" placeholder="Cari username..." value="<?= htmlspecialchars($search) ?>">
                        <button class="btn btn-primary" style="border-radius: 0 50rem 50rem 0;" type="submit"><i class="bi bi-search"></i> Cari</button>
                    </div>
                </form>
            </div>
            <div class="col-md-3 mt-3 mt-md-0 text-md-end">
                <a href="dashboard_llm.php" class="btn btn-white border rounded-pill fw-bold text-secondary shadow-sm px-4 bg-white">
                    <i class="bi bi-arrow-left me-1"></i> Dashboard
                </a>
            </div>
        </div>

        <?php if($pesan_notif): ?>
            <div class="alert alert-success fw-bold shadow-sm rounded-4 mb-4"><i class="bi bi-check-circle-fill me-2"></i> <?= $pesan_notif ?></div>
        <?php endif; ?>

        <div class="card-premium p-4">
            <div class="table-responsive">
                <table class="table table-hover align-middle table-keys">
                    <thead>
                        <tr>
                            <th>User Info</th>
                            <th>Tipe Langganan</th>
                            <th class="text-center">Kredit Bulanan (Token)</th>
                            <th>Status API</th>
                            <th class="text-end">Tindakan Admin</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while($row = mysqli_fetch_assoc($query_users)): 
                            $is_pro = ($row['status_akun'] == 'pro');
                            $kredit_terpakai = $row['llm_kredit_terpakai'] ?? 0;
                            $persentase = ($kredit_terpakai / 100000) * 100;
                            if($persentase > 100) $persentase = 100;
                        ?>
                        <tr>
                            <td>
                                <div class="fw-bold text-dark"><?= htmlspecialchars($row['username']) ?></div>
                                <div class="text-muted small mb-1">
                                    <span class="badge bg-primary text-white" style="font-size: 10px;"><?= $row['total_keys'] ?> API Key Dibuat</span>
                                </div>
                                <?php if(!empty($row['projects'])): ?>
                                    <button class="btn btn-sm btn-outline-secondary py-0 mt-1" type="button" data-bs-toggle="collapse" data-bs-target="#projectList<?= $row['id'] ?>" aria-expanded="false" style="font-size: 10px;">
                                        <i class="bi bi-list-ul"></i> Lihat List Key
                                    </button>
                                    <div class="collapse" id="projectList<?= $row['id'] ?>">
                                        <div class="small mt-2 p-2 rounded text-muted" style="font-size: 11px; background-color: #f8fafc; border: 1px dashed #cbd5e1;">
                                            <strong>Nama Key/Project:</strong><br>
                                            <?= $row['projects'] ?>
                                        </div>
                                    </div>
                                <?php endif; ?>
                                <?php if($row['llm_message']): ?>
                                    <div class="mt-2"><span class="badge bg-warning text-dark" style="font-size:10px;"><i class="bi bi-envelope-check-fill"></i> Pesan tertunda</span></div>
                                <?php endif; ?>
                            </td>
                            
                            <td>
                                <?php if($is_pro): ?>
                                    <span class="badge bg-warning text-dark border border-warning px-3 py-1 fs-6"><i class="bi bi-star-fill"></i> PRO</span>
                                    <div class="small mt-1 text-danger fw-bold" style="font-size: 11px;">
                                        Exp: <?= !empty($row['llm_pro_expiry']) ? date('d M Y, H:i', strtotime($row['llm_pro_expiry'])) : 'Selamanya' ?>
                                    </div>
                                <?php else: ?>
                                    <span class="badge bg-secondary bg-opacity-25 text-dark border px-3 py-1 fs-6">FREE</span>
                                <?php endif; ?>
                            </td>
                            
                            <td class="text-center">
                                <?php if($is_pro): ?>
                                    <span class="badge bg-success bg-opacity-25 text-success border border-success-subtle px-3 py-2"><i class="bi bi-infinity"></i> Unlimited Tokens</span>
                                <?php else: ?>
                                    <div class="d-flex justify-content-between small fw-bold mb-1">
                                        <span class="<?= ($kredit_terpakai >= 100000) ? 'text-danger' : 'text-primary' ?>"><?= number_format($kredit_terpakai) ?></span>
                                        <span class="text-muted">100.000</span>
                                    </div>
                                    <div class="progress" style="height: 6px;">
                                        <div class="progress-bar <?= ($persentase >= 90) ? 'bg-danger' : 'bg-primary' ?>" style="width: <?= $persentase ?>%;"></div>
                                    </div>
                                <?php endif; ?>
                            </td>
                            
                            <td>
                                <?php if($row['llm_status'] == 'blocked'): ?>
                                    <span class="badge bg-danger"><i class="bi bi-slash-circle"></i> BLOCKED</span>
                                <?php else: ?>
                                    <span class="badge bg-success"><i class="bi bi-check-circle"></i> ACTIVE</span>
                                <?php endif; ?>
                            </td>
                            
                            <td class="text-end">
                                <button class="btn btn-sm btn-dark text-white fw-bold shadow-sm" data-bs-toggle="modal" data-bs-target="#editModal<?= $row['id'] ?>">
                                    <i class="bi bi-pencil-square"></i> Edit Tier
                                </button>
                                <button class="btn btn-sm btn-info text-white fw-bold shadow-sm ms-1" data-bs-toggle="modal" data-bs-target="#msgModal<?= $row['id'] ?>">
                                    <i class="bi bi-chat-text-fill"></i> Pesan
                                </button>
                                <?php if($row['llm_status'] == 'active'): ?>
                                    <a href="?action=block&uid=<?= $row['id'] ?>" class="btn btn-sm btn-warning fw-bold shadow-sm ms-1" onclick="return confirm('Blokir akses API?')"><i class="bi bi-slash-circle"></i> Blokir</a>
                                <?php else: ?>
                                    <a href="?action=unblock&uid=<?= $row['id'] ?>" class="btn btn-sm btn-success fw-bold shadow-sm ms-1"><i class="bi bi-check-circle"></i> Buka</a>
                                <?php endif; ?>
                            </td>
                        </tr>

                        <div class="modal fade" id="editModal<?= $row['id'] ?>" tabindex="-1">
                            <div class="modal-dialog modal-dialog-centered modal-sm">
                                <div class="modal-content rounded-4 border-0 shadow-lg">
                                    <div class="modal-header border-0 bg-light">
                                        <h5 class="modal-title fw-bold"><i class="bi bi-star-fill text-warning me-2"></i>Edit Langganan</h5>
                                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                    </div>
                                    <form method="POST">
                                        <div class="modal-body p-4">
                                            <input type="hidden" name="user_id" value="<?= $row['id'] ?>">
                                            <div class="mb-3">
                                                <label class="form-label fw-bold small">Tipe Akun</label>
                                                <select name="status_akun" class="form-select bg-light fw-bold" id="tierSelect<?= $row['id'] ?>" onchange="toggleDate(this.value, <?= $row['id'] ?>)">
                                                    <option value="free" <?= (!$is_pro) ? 'selected' : '' ?>>FREE (Max 1 Key, 100K Token)</option>
                                                    <option value="pro" <?= ($is_pro) ? 'selected' : '' ?>>PRO (Max 5 Key, Unlimited)</option>
                                                </select>
                                            </div>
                                            <div class="mb-2" id="dateWrapper<?= $row['id'] ?>" style="display: <?= ($is_pro) ? 'block' : 'none' ?>;">
                                                <label class="form-label fw-bold small text-danger">Tanggal & Waktu Berakhir (Kedaluwarsa)</label>
                                                <input type="datetime-local" name="pro_expiry" class="form-control border-danger" value="<?= !empty($row['llm_pro_expiry']) ? date('Y-m-d\TH:i', strtotime($row['llm_pro_expiry'])) : '' ?>">
                                                <small class="text-muted" style="font-size:11px;">* Kosongkan jika ingin berlaku selamanya.</small>
                                            </div>
                                        </div>
                                        <div class="modal-footer border-0">
                                            <button type="submit" name="edit_tier" class="btn btn-dark fw-bold w-100">Simpan Perubahan</button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>

                        <div class="modal fade" id="msgModal<?= $row['id'] ?>" tabindex="-1">
                            <div class="modal-dialog modal-dialog-centered">
                                <div class="modal-content rounded-4 border-0 shadow-lg">
                                    <div class="modal-header border-0 bg-light">
                                        <h5 class="modal-title fw-bold">Kirim Pesan Pop-Up</h5>
                                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                    </div>
                                    <form method="POST">
                                        <div class="modal-body p-4">
                                            <input type="hidden" name="user_id" value="<?= $row['id'] ?>">
                                            <textarea name="pesan_popup" class="form-control bg-light border-0" rows="4" required><?= $row['llm_message'] ?></textarea>
                                        </div>
                                        <div class="modal-footer border-0">
                                            <button type="submit" name="send_message" class="btn btn-primary fw-bold w-100">Kirim Pesan</button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Logika untuk menampilkan/menyembunyikan input tanggal Expiry
        function toggleDate(val, id) {
            document.getElementById('dateWrapper'+id).style.display = (val === 'pro') ? 'block' : 'none';
        }
    </script>
</body>
</html>