<?php
/**
 * Admin Premium Management
 * Manage premium plans, user upgrades, and payment confirmations
 */

session_start();
require_once '../db_connect.php';

if(!isset($_SESSION['user_id']) || $_SESSION['role'] != 'admin') {
    header('Location: ../login');
    exit;
}

$admin_id = $_SESSION['user_id'];
$error = '';
$success = '';
$current_year = date('Y');

// Get payment settings
$settings_result = mysqli_query($conn, "SELECT setting_key, setting_value FROM payment_settings");
$settings = [];
while($s = mysqli_fetch_assoc($settings_result)) {
    $settings[$s['setting_key']] = $s['setting_value'];
}

$basic_yearly_fee = $settings['yearly_fee'] ?? 50000;
$premium_yearly_fee = $settings['premium_yearly_fee'] ?? 100000;
$max_images_per_land = $settings['max_images_per_land'] ?? 5;

// Handle form submissions
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $action = $_POST['action'] ?? '';

    // Update pricing settings
    if($action == 'update_pricing') {
        $new_basic_fee = floatval($_POST['basic_yearly_fee']);
        $new_premium_fee = floatval($_POST['premium_yearly_fee']);
        $new_max_images = intval($_POST['max_images_per_land']);

        if($new_basic_fee < 0 || $new_premium_fee < 0) {
            $error = 'Fees cannot be negative';
        } elseif($new_premium_fee < $new_basic_fee) {
            $error = 'Premium fee must be higher than or equal to basic fee';
        } elseif($new_max_images < 1 || $new_max_images > 20) {
            $error = 'Max images must be between 1 and 20';
        } else {
            $updates = [
                'yearly_fee' => $new_basic_fee,
                'premium_yearly_fee' => $new_premium_fee,
                'max_images_per_land' => $new_max_images
            ];

            foreach($updates as $key => $value) {
                mysqli_query($conn, "INSERT INTO payment_settings (setting_key, setting_value)
                                     VALUES ('$key', '$value')
                                     ON DUPLICATE KEY UPDATE setting_value = '$value'");
            }

            $basic_yearly_fee = $new_basic_fee;
            $premium_yearly_fee = $new_premium_fee;
            $max_images_per_land = $new_max_images;
            $success = 'Pricing settings updated successfully';
        }
    }

    // Upgrade user to premium
    if($action == 'upgrade_user') {
        $user_id = intval($_POST['user_id']);
        $custom_amount = !empty($_POST['custom_amount']) ? floatval($_POST['custom_amount']) : null;

        $update_sql = "UPDATE users SET user_type = 'premium'";
        if($custom_amount !== null) {
            $update_sql .= ", premium_amount = $custom_amount";
        }
        $update_sql .= " WHERE id = $user_id";

        if(mysqli_query($conn, $update_sql)) {
            // Log the upgrade
            $details = json_encode(['upgraded_by' => $admin_id, 'custom_amount' => $custom_amount]);
            mysqli_query($conn, "INSERT INTO activity_logs (user_id, action, details, ip_address)
                                VALUES ($user_id, 'upgraded_to_premium', '$details', '{$_SERVER['REMOTE_ADDR']}')");
            $success = 'User upgraded to premium successfully';
        } else {
            $error = 'Failed to upgrade user';
        }
    }

    // Downgrade user to basic
    if($action == 'downgrade_user') {
        $user_id = intval($_POST['user_id']);

        if(mysqli_query($conn, "UPDATE users SET user_type = 'basic', premium_amount = NULL WHERE id = $user_id")) {
            $details = json_encode(['downgraded_by' => $admin_id]);
            mysqli_query($conn, "INSERT INTO activity_logs (user_id, action, details, ip_address)
                                VALUES ($user_id, 'downgraded_to_basic', '$details', '{$_SERVER['REMOTE_ADDR']}')");
            $success = 'User downgraded to basic successfully';
        } else {
            $error = 'Failed to downgrade user';
        }
    }

    // Set custom premium amount for user
    if($action == 'set_custom_amount') {
        $user_id = intval($_POST['user_id']);
        $custom_amount = floatval($_POST['custom_amount']);

        if($custom_amount <= 0) {
            $error = 'Amount must be greater than zero';
        } else {
            if(mysqli_query($conn, "UPDATE users SET premium_amount = $custom_amount WHERE id = $user_id")) {
                $success = 'Custom premium amount set successfully';
            } else {
                $error = 'Failed to set custom amount';
            }
        }
    }

    // Record payment for user
    if($action == 'record_payment') {
        $user_id = intval($_POST['user_id']);
        $amount = floatval($_POST['amount']);
        $payment_year = intval($_POST['payment_year']);
        $payment_date = mysqli_real_escape_string($conn, $_POST['payment_date']);
        $payment_method = mysqli_real_escape_string($conn, $_POST['payment_method']);
        $reference = mysqli_real_escape_string($conn, trim($_POST['reference_number']));
        $notes = mysqli_real_escape_string($conn, trim($_POST['notes']));

        if($amount <= 0) {
            $error = 'Amount must be greater than zero';
        } else {
            // Check if payment already exists
            $check = mysqli_query($conn, "SELECT id FROM user_payments WHERE user_id = $user_id AND payment_year = $payment_year AND status = 'confirmed'");
            if(mysqli_num_rows($check) > 0) {
                $error = "Payment for year $payment_year already exists for this user";
            } else {
                $sql = "INSERT INTO user_payments (user_id, amount, payment_year, payment_date, payment_method, reference_number, notes, status, recorded_by, confirmed_by)
                        VALUES ($user_id, $amount, $payment_year, '$payment_date', '$payment_method', '$reference', '$notes', 'confirmed', $admin_id, $admin_id)";

                if(mysqli_query($conn, $sql)) {
                    $success = 'Payment recorded and confirmed successfully';
                } else {
                    $error = 'Failed to record payment: ' . mysqli_error($conn);
                }
            }
        }
    }
}

// Get statistics
$stats = [];

// Total users by type
$r = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as cnt FROM users WHERE role = 'user'"));
$stats['total_users'] = $r['cnt'];

$r = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as cnt FROM users WHERE role = 'user' AND user_type = 'premium'"));
$stats['premium_users'] = $r['cnt'];

$stats['basic_users'] = $stats['total_users'] - $stats['premium_users'];

// Revenue this year
$r = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COALESCE(SUM(amount), 0) as total FROM user_payments WHERE payment_year = $current_year AND status = 'confirmed'"));
$stats['revenue_this_year'] = $r['total'];

// Pending upgrade requests (from activity logs)
$upgrade_requests = mysqli_query($conn, "
    SELECT al.*, u.full_name, u.email, u.phone, u.user_type, u.premium_amount
    FROM activity_logs al
    JOIN users u ON al.user_id = u.id
    WHERE al.action = 'premium_upgrade_request'
    AND u.user_type = 'basic'
    ORDER BY al.created_at DESC
    LIMIT 20
");

// Get all users with their payment status
$users_result = mysqli_query($conn, "
    SELECT u.*,
           (SELECT MAX(payment_year) FROM user_payments WHERE user_id = u.id AND status = 'confirmed') as last_paid_year,
           (SELECT SUM(amount) FROM user_payments WHERE user_id = u.id AND status = 'confirmed') as total_paid
    FROM users u
    WHERE u.role = 'user'
    ORDER BY u.user_type DESC, u.full_name ASC
");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Premium Management - Admin</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="../assets/font-awesome/css/all.min.css">
    <link href="../assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Inter', sans-serif; }
        :root {
            --primary: #1a3a6e;
            --gold: #d4af37;
            --gold-light: #f5d77a;
            --success: #22c55e;
            --warning: #f59e0b;
            --danger: #ef4444;
            --gray-50: #f8fafc;
            --gray-100: #f1f5f9;
            --gray-200: #e2e8f0;
            --gray-500: #64748b;
            --gray-700: #334155;
            --gray-800: #1e293b;
        }

        .page-header {
            background: linear-gradient(135deg, var(--gold) 0%, var(--gold-light) 100%);
            border-radius: 20px;
            padding: 30px;
            margin-bottom: 30px;
            color: var(--primary);
        }

        .page-header h1 {
            font-size: 28px;
            font-weight: 700;
            margin: 0 0 8px;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .page-header p {
            margin: 0;
            opacity: 0.8;
        }

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

        .stat-card {
            border-radius: 16px;
            padding: 24px;
            color: white;
            position: relative;
            overflow: hidden;
        }

        .stat-card::before {
            content: '';
            position: absolute;
            top: -50%;
            right: -50%;
            width: 100%;
            height: 100%;
            background: rgba(255,255,255,0.1);
            border-radius: 50%;
        }

        .stat-card.gold { background: linear-gradient(135deg, var(--gold), var(--gold-light)); color: var(--primary); }
        .stat-card.blue { background: linear-gradient(135deg, #3b82f6, #2563eb); }
        .stat-card.green { background: linear-gradient(135deg, var(--success), #16a34a); }
        .stat-card.purple { background: linear-gradient(135deg, #8b5cf6, #7c3aed); }

        .stat-card .stat-icon {
            width: 50px;
            height: 50px;
            border-radius: 12px;
            background: rgba(255,255,255,0.2);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
            margin-bottom: 15px;
        }

        .stat-card h3 {
            font-size: 28px;
            font-weight: 700;
            margin: 0;
        }

        .stat-card p {
            margin: 5px 0 0;
            opacity: 0.9;
            font-size: 13px;
        }

        .content-tabs {
            display: flex;
            gap: 10px;
            margin-bottom: 24px;
            flex-wrap: wrap;
        }

        .tab-btn {
            padding: 12px 24px;
            border: none;
            border-radius: 12px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            background: white;
            color: var(--gray-500);
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }

        .tab-btn.active {
            background: linear-gradient(135deg, var(--gold), var(--gold-light));
            color: var(--primary);
        }

        .tab-btn:hover:not(.active) {
            background: var(--gray-100);
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        .card {
            background: white;
            border-radius: 16px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.05);
            overflow: hidden;
            margin-bottom: 24px;
        }

        .card-header {
            padding: 20px 24px;
            border-bottom: 1px solid var(--gray-200);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .card-header h3 {
            font-size: 16px;
            font-weight: 600;
            margin: 0;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .card-header.gold {
            background: linear-gradient(135deg, rgba(212, 175, 55, 0.1), rgba(245, 215, 122, 0.1));
            border-left: 4px solid var(--gold);
        }

        .card-body {
            padding: 24px;
        }

        .pricing-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 24px;
        }

        .pricing-card {
            border: 2px solid var(--gray-200);
            border-radius: 16px;
            padding: 24px;
            text-align: center;
            transition: all 0.3s;
        }

        .pricing-card.premium {
            border-color: var(--gold);
            background: linear-gradient(135deg, rgba(212, 175, 55, 0.05), rgba(245, 215, 122, 0.05));
        }

        .pricing-card .plan-icon {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 16px;
            font-size: 24px;
        }

        .pricing-card.basic .plan-icon {
            background: var(--gray-100);
            color: var(--gray-500);
        }

        .pricing-card.premium .plan-icon {
            background: linear-gradient(135deg, var(--gold), var(--gold-light));
            color: var(--primary);
        }

        .pricing-card h4 {
            font-size: 20px;
            font-weight: 700;
            margin-bottom: 8px;
        }

        .pricing-card .price {
            font-size: 28px;
            font-weight: 700;
            color: var(--primary);
            margin-bottom: 20px;
        }

        .pricing-card .price span {
            font-size: 14px;
            font-weight: 400;
            color: var(--gray-500);
        }

        .form-group {
            margin-bottom: 16px;
        }

        .form-label {
            display: block;
            font-size: 13px;
            font-weight: 600;
            color: var(--gray-700);
            margin-bottom: 6px;
        }

        .form-control {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid var(--gray-200);
            border-radius: 10px;
            font-size: 14px;
            transition: all 0.3s;
        }

        .form-control:focus {
            outline: none;
            border-color: var(--gold);
            box-shadow: 0 0 0 4px rgba(212, 175, 55, 0.1);
        }

        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 10px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-gold {
            background: linear-gradient(135deg, var(--gold), var(--gold-light));
            color: var(--primary);
        }

        .btn-gold:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(212, 175, 55, 0.3);
        }

        .btn-success {
            background: linear-gradient(135deg, var(--success), #16a34a);
            color: white;
        }

        .btn-danger {
            background: linear-gradient(135deg, var(--danger), #dc2626);
            color: white;
        }

        .btn-outline {
            background: transparent;
            border: 2px solid var(--gray-200);
            color: var(--gray-600);
        }

        .btn-sm {
            padding: 8px 14px;
            font-size: 12px;
        }

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

        .table-modern thead th {
            background: var(--gray-50);
            padding: 14px 16px;
            text-align: left;
            font-size: 11px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            color: var(--gray-500);
            border-bottom: 2px solid var(--gray-200);
        }

        .table-modern tbody td {
            padding: 14px 16px;
            border-bottom: 1px solid var(--gray-100);
            font-size: 13px;
            vertical-align: middle;
        }

        .table-modern tbody tr:hover {
            background: var(--gray-50);
        }

        .badge {
            display: inline-flex;
            align-items: center;
            gap: 4px;
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 11px;
            font-weight: 600;
        }

        .badge-premium {
            background: linear-gradient(135deg, rgba(212, 175, 55, 0.2), rgba(245, 215, 122, 0.2));
            color: #b8860b;
        }

        .badge-basic {
            background: var(--gray-100);
            color: var(--gray-600);
        }

        .badge-success {
            background: rgba(34, 197, 94, 0.15);
            color: #16a34a;
        }

        .badge-warning {
            background: rgba(245, 158, 11, 0.15);
            color: #d97706;
        }

        .badge-danger {
            background: rgba(239, 68, 68, 0.15);
            color: #dc2626;
        }

        .user-cell {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            color: white;
            font-size: 14px;
        }

        .user-avatar.basic {
            background: linear-gradient(135deg, #667eea, #764ba2);
        }

        .user-avatar.premium {
            background: linear-gradient(135deg, var(--gold), var(--gold-light));
            color: var(--primary);
        }

        .user-info h5 {
            font-size: 14px;
            font-weight: 600;
            margin: 0 0 2px;
        }

        .user-info span {
            font-size: 12px;
            color: var(--gray-500);
        }

        .request-card {
            background: var(--gray-50);
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 16px;
            border-left: 4px solid var(--gold);
        }

        .request-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 12px;
        }

        .request-user h5 {
            font-size: 15px;
            font-weight: 600;
            margin: 0 0 4px;
        }

        .request-user span {
            font-size: 13px;
            color: var(--gray-500);
        }

        .request-date {
            font-size: 12px;
            color: var(--gray-500);
        }

        .request-details {
            font-size: 13px;
            color: var(--gray-600);
            margin-bottom: 12px;
        }

        .request-actions {
            display: flex;
            gap: 10px;
        }

        .alert {
            padding: 16px 20px;
            border-radius: 12px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .alert-success {
            background: rgba(34, 197, 94, 0.1);
            color: #166534;
            border-left: 4px solid var(--success);
        }

        .alert-danger {
            background: rgba(239, 68, 68, 0.1);
            color: #991b1b;
            border-left: 4px solid var(--danger);
        }

        /* Modal */
        .modal-backdrop {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 9998;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s;
        }

        .modal-backdrop.active {
            opacity: 1;
            visibility: visible;
        }

        .modal {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%) scale(0.9);
            background: white;
            border-radius: 16px;
            z-index: 9999;
            width: 90%;
            max-width: 500px;
            max-height: 90vh;
            overflow-y: auto;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s;
        }

        .modal.active {
            opacity: 1;
            visibility: visible;
            transform: translate(-50%, -50%) scale(1);
        }

        .modal-header {
            padding: 20px 24px;
            border-bottom: 1px solid var(--gray-200);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-header h3 {
            font-size: 18px;
            font-weight: 600;
            margin: 0;
        }

        .modal-close {
            background: var(--gray-100);
            border: none;
            width: 32px;
            height: 32px;
            border-radius: 8px;
            cursor: pointer;
        }

        .modal-body {
            padding: 24px;
        }

        .modal-footer {
            padding: 16px 24px;
            border-top: 1px solid var(--gray-200);
            display: flex;
            justify-content: flex-end;
            gap: 12px;
        }

        .search-box {
            position: relative;
            max-width: 300px;
        }

        .search-box input {
            width: 100%;
            padding: 10px 16px 10px 40px;
            border: 2px solid var(--gray-200);
            border-radius: 10px;
            font-size: 14px;
        }

        .search-box i {
            position: absolute;
            left: 14px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--gray-400);
        }

        .empty-state {
            text-align: center;
            padding: 40px;
        }

        .empty-state i {
            font-size: 48px;
            color: var(--gray-300);
            margin-bottom: 16px;
        }

        .empty-state h4 {
            color: var(--gray-600);
            margin-bottom: 8px;
        }

        .empty-state p {
            color: var(--gray-500);
            font-size: 14px;
        }

        @media (max-width: 768px) {
            .page-header {
                padding: 20px;
            }

            .page-header h1 {
                font-size: 22px;
            }

            .content-tabs {
                overflow-x: auto;
                flex-wrap: nowrap;
                padding-bottom: 10px;
            }

            .tab-btn {
                white-space: nowrap;
            }

            .table-modern {
                display: block;
                overflow-x: auto;
            }
        }
    </style>
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>

    <main class="admin-main">
        <div class="page-header">
            <h1><i class="fas fa-crown"></i> Premium Management</h1>
            <p>Manage premium plans, user upgrades, and payment confirmations</p>
        </div>

        <?php if($error): ?>
        <div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> <?php echo $error; ?></div>
        <?php endif; ?>

        <?php if($success): ?>
        <div class="alert alert-success"><i class="fas fa-check-circle"></i> <?php echo $success; ?></div>
        <?php endif; ?>

        <!-- Stats -->
        <div class="stats-grid">
            <div class="stat-card gold">
                <div class="stat-icon"><i class="fas fa-crown"></i></div>
                <h3><?php echo $stats['premium_users']; ?></h3>
                <p>Premium Users</p>
            </div>
            <div class="stat-card blue">
                <div class="stat-icon"><i class="fas fa-user"></i></div>
                <h3><?php echo $stats['basic_users']; ?></h3>
                <p>Basic Users</p>
            </div>
            <div class="stat-card green">
                <div class="stat-icon"><i class="fas fa-money-bill-wave"></i></div>
                <h3>TZS <?php echo number_format($stats['revenue_this_year']); ?></h3>
                <p>Revenue (<?php echo $current_year; ?>)</p>
            </div>
            <div class="stat-card purple">
                <div class="stat-icon"><i class="fas fa-users"></i></div>
                <h3><?php echo $stats['total_users']; ?></h3>
                <p>Total Users</p>
            </div>
        </div>

        <!-- Tabs -->
        <div class="content-tabs">
            <button class="tab-btn active" onclick="showTab('pricing')">
                <i class="fas fa-tags"></i> Pricing
            </button>
            <button class="tab-btn" onclick="showTab('requests')">
                <i class="fas fa-arrow-up"></i> Upgrade Requests
                <?php if(mysqli_num_rows($upgrade_requests) > 0): ?>
                <span class="badge badge-warning"><?php echo mysqli_num_rows($upgrade_requests); ?></span>
                <?php endif; ?>
            </button>
            <button class="tab-btn" onclick="showTab('users')">
                <i class="fas fa-users"></i> All Users
            </button>
        </div>

        <!-- Pricing Tab -->
        <div id="tab-pricing" class="tab-content active">
            <div class="card">
                <div class="card-header gold">
                    <h3><i class="fas fa-tags"></i> Plan Pricing</h3>
                </div>
                <div class="card-body">
                    <form method="POST">
                        <input type="hidden" name="action" value="update_pricing">
                        <div class="pricing-grid">
                            <div class="pricing-card basic">
                                <div class="plan-icon"><i class="fas fa-user"></i></div>
                                <h4>Basic Plan</h4>
                                <div class="form-group">
                                    <label class="form-label">Yearly Fee (TZS)</label>
                                    <input type="number" name="basic_yearly_fee" class="form-control"
                                           value="<?php echo $basic_yearly_fee; ?>" min="0" step="1000">
                                </div>
                                <ul style="text-align: left; font-size: 13px; color: var(--gray-600); list-style: none; padding: 0;">
                                    <li><i class="fas fa-check text-success"></i> Unlimited lands</li>
                                    <li><i class="fas fa-check text-success"></i> Beacon points</li>
                                    <li><i class="fas fa-check text-success"></i> Digital certificates</li>
                                    <li><i class="fas fa-times text-danger"></i> No image uploads</li>
                                </ul>
                            </div>
                            <div class="pricing-card premium">
                                <div class="plan-icon"><i class="fas fa-crown"></i></div>
                                <h4>Premium Plan</h4>
                                <div class="form-group">
                                    <label class="form-label">Yearly Fee (TZS)</label>
                                    <input type="number" name="premium_yearly_fee" class="form-control"
                                           value="<?php echo $premium_yearly_fee; ?>" min="0" step="1000">
                                </div>
                                <div class="form-group">
                                    <label class="form-label">Max Images per Land</label>
                                    <input type="number" name="max_images_per_land" class="form-control"
                                           value="<?php echo $max_images_per_land; ?>" min="1" max="20">
                                </div>
                                <ul style="text-align: left; font-size: 13px; color: var(--gray-600); list-style: none; padding: 0;">
                                    <li><i class="fas fa-check text-success"></i> All Basic features</li>
                                    <li><i class="fas fa-crown text-warning"></i> Image uploads</li>
                                    <li><i class="fas fa-crown text-warning"></i> Premium badge</li>
                                    <li><i class="fas fa-crown text-warning"></i> Priority support</li>
                                </ul>
                            </div>
                        </div>
                        <div style="text-align: center; margin-top: 24px;">
                            <button type="submit" class="btn btn-gold">
                                <i class="fas fa-save"></i> Save Pricing
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Upgrade Requests Tab -->
        <div id="tab-requests" class="tab-content">
            <div class="card">
                <div class="card-header">
                    <h3><i class="fas fa-arrow-up"></i> Pending Upgrade Requests</h3>
                </div>
                <div class="card-body">
                    <?php if(mysqli_num_rows($upgrade_requests) == 0): ?>
                    <div class="empty-state">
                        <i class="fas fa-inbox"></i>
                        <h4>No Pending Requests</h4>
                        <p>There are no pending upgrade requests at this time.</p>
                    </div>
                    <?php else: ?>
                    <?php while($req = mysqli_fetch_assoc($upgrade_requests)):
                        $details = json_decode($req['details'], true);
                    ?>
                    <div class="request-card">
                        <div class="request-header">
                            <div class="request-user">
                                <h5><?php echo htmlspecialchars($req['full_name']); ?></h5>
                                <span><?php echo htmlspecialchars($req['email']); ?> | <?php echo htmlspecialchars($req['phone']); ?></span>
                            </div>
                            <div class="request-date">
                                <?php echo date('d M Y, H:i', strtotime($req['created_at'])); ?>
                            </div>
                        </div>
                        <div class="request-details">
                            <strong>Contact Phone:</strong> <?php echo htmlspecialchars($details['contact_phone'] ?? 'N/A'); ?><br>
                            <strong>Upgrade Fee:</strong> TZS <?php echo number_format($details['upgrade_fee'] ?? $premium_yearly_fee); ?><br>
                            <?php if(!empty($details['notes'])): ?>
                            <strong>Notes:</strong> <?php echo htmlspecialchars($details['notes']); ?>
                            <?php endif; ?>
                        </div>
                        <div class="request-actions">
                            <button class="btn btn-success btn-sm" onclick="openUpgradeModal(<?php echo $req['user_id']; ?>, '<?php echo htmlspecialchars($req['full_name']); ?>', <?php echo $details['upgrade_fee'] ?? $premium_yearly_fee; ?>)">
                                <i class="fas fa-check"></i> Approve & Record Payment
                            </button>
                            <a href="users?id=<?php echo $req['user_id']; ?>" class="btn btn-outline btn-sm">
                                <i class="fas fa-eye"></i> View User
                            </a>
                        </div>
                    </div>
                    <?php endwhile; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Users Tab -->
        <div id="tab-users" class="tab-content">
            <div class="card">
                <div class="card-header">
                    <h3><i class="fas fa-users"></i> User Management</h3>
                    <div class="search-box">
                        <i class="fas fa-search"></i>
                        <input type="text" id="userSearch" placeholder="Search users..." onkeyup="filterUsers()">
                    </div>
                </div>
                <div class="card-body" style="padding: 0;">
                    <table class="table-modern" id="usersTable">
                        <thead>
                            <tr>
                                <th>User</th>
                                <th>Account Type</th>
                                <th>Custom Amount</th>
                                <th>Last Paid</th>
                                <th>Total Paid</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php mysqli_data_seek($users_result, 0); while($user = mysqli_fetch_assoc($users_result)): ?>
                            <tr>
                                <td>
                                    <div class="user-cell">
                                        <div class="user-avatar <?php echo $user['user_type'] ?? 'basic'; ?>">
                                            <?php echo strtoupper(substr($user['full_name'] ?: $user['username'], 0, 1)); ?>
                                        </div>
                                        <div class="user-info">
                                            <h5><?php echo htmlspecialchars($user['full_name'] ?: $user['username']); ?></h5>
                                            <span><?php echo htmlspecialchars($user['email']); ?></span>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <?php if(($user['user_type'] ?? 'basic') == 'premium'): ?>
                                    <span class="badge badge-premium"><i class="fas fa-crown"></i> Premium</span>
                                    <?php else: ?>
                                    <span class="badge badge-basic">Basic</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if($user['premium_amount']): ?>
                                    TZS <?php echo number_format($user['premium_amount']); ?>
                                    <?php else: ?>
                                    <span style="color: var(--gray-400);">-</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if($user['last_paid_year']): ?>
                                    <?php if($user['last_paid_year'] >= $current_year): ?>
                                    <span class="badge badge-success"><?php echo $user['last_paid_year']; ?></span>
                                    <?php else: ?>
                                    <span class="badge badge-danger"><?php echo $user['last_paid_year']; ?></span>
                                    <?php endif; ?>
                                    <?php else: ?>
                                    <span class="badge badge-warning">Never</span>
                                    <?php endif; ?>
                                </td>
                                <td>TZS <?php echo number_format($user['total_paid'] ?? 0); ?></td>
                                <td>
                                    <div style="display: flex; gap: 6px; flex-wrap: wrap;">
                                        <?php if(($user['user_type'] ?? 'basic') == 'basic'): ?>
                                        <button class="btn btn-gold btn-sm" onclick="openUpgradeModal(<?php echo $user['id']; ?>, '<?php echo htmlspecialchars($user['full_name'] ?: $user['username']); ?>', <?php echo $premium_yearly_fee; ?>)">
                                            <i class="fas fa-crown"></i> Upgrade
                                        </button>
                                        <?php else: ?>
                                        <form method="POST" style="display:inline;" onsubmit="return confirm('Downgrade this user to basic?')">
                                            <input type="hidden" name="action" value="downgrade_user">
                                            <input type="hidden" name="user_id" value="<?php echo $user['id']; ?>">
                                            <button type="submit" class="btn btn-outline btn-sm">
                                                <i class="fas fa-arrow-down"></i> Downgrade
                                            </button>
                                        </form>
                                        <button class="btn btn-outline btn-sm" onclick="openCustomAmountModal(<?php echo $user['id']; ?>, '<?php echo htmlspecialchars($user['full_name'] ?: $user['username']); ?>', <?php echo $user['premium_amount'] ?? $premium_yearly_fee; ?>)">
                                            <i class="fas fa-edit"></i> Amount
                                        </button>
                                        <?php endif; ?>
                                        <button class="btn btn-success btn-sm" onclick="openPaymentModal(<?php echo $user['id']; ?>, '<?php echo htmlspecialchars($user['full_name'] ?: $user['username']); ?>', '<?php echo $user['user_type'] ?? 'basic'; ?>', <?php echo $user['premium_amount'] ?? 0; ?>)">
                                            <i class="fas fa-money-bill"></i> Payment
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </main>

    <!-- Modal Backdrop -->
    <div class="modal-backdrop" id="modalBackdrop" onclick="closeModal()"></div>

    <!-- Upgrade Modal -->
    <div class="modal" id="upgradeModal">
        <div class="modal-header">
            <h3><i class="fas fa-crown"></i> Upgrade to Premium</h3>
            <button class="modal-close" onclick="closeModal()"><i class="fas fa-times"></i></button>
        </div>
        <form method="POST">
            <input type="hidden" name="action" value="upgrade_user">
            <input type="hidden" name="user_id" id="upgrade_user_id">
            <div class="modal-body">
                <p style="margin-bottom: 20px;">Upgrading <strong id="upgrade_user_name"></strong> to Premium account.</p>
                <div class="form-group">
                    <label class="form-label">Custom Premium Amount (Optional)</label>
                    <input type="number" name="custom_amount" id="upgrade_custom_amount" class="form-control"
                           placeholder="Leave empty to use default premium fee" min="0" step="1000">
                    <small style="color: var(--gray-500);">Default: TZS <?php echo number_format($premium_yearly_fee); ?>/year</small>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline" onclick="closeModal()">Cancel</button>
                <button type="submit" class="btn btn-gold"><i class="fas fa-crown"></i> Upgrade User</button>
            </div>
        </form>
    </div>

    <!-- Custom Amount Modal -->
    <div class="modal" id="customAmountModal">
        <div class="modal-header">
            <h3><i class="fas fa-edit"></i> Set Custom Premium Amount</h3>
            <button class="modal-close" onclick="closeModal()"><i class="fas fa-times"></i></button>
        </div>
        <form method="POST">
            <input type="hidden" name="action" value="set_custom_amount">
            <input type="hidden" name="user_id" id="custom_user_id">
            <div class="modal-body">
                <p style="margin-bottom: 20px;">Setting custom amount for <strong id="custom_user_name"></strong>.</p>
                <div class="form-group">
                    <label class="form-label">Custom Premium Amount (TZS/year)</label>
                    <input type="number" name="custom_amount" id="custom_amount_value" class="form-control"
                           required min="1" step="1000">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline" onclick="closeModal()">Cancel</button>
                <button type="submit" class="btn btn-gold"><i class="fas fa-save"></i> Save Amount</button>
            </div>
        </form>
    </div>

    <!-- Payment Modal -->
    <div class="modal" id="paymentModal">
        <div class="modal-header">
            <h3><i class="fas fa-money-bill"></i> Record Payment</h3>
            <button class="modal-close" onclick="closeModal()"><i class="fas fa-times"></i></button>
        </div>
        <form method="POST">
            <input type="hidden" name="action" value="record_payment">
            <input type="hidden" name="user_id" id="payment_user_id">
            <div class="modal-body">
                <p style="margin-bottom: 20px;">Recording payment for <strong id="payment_user_name"></strong>.</p>
                <div class="form-group">
                    <label class="form-label">Amount (TZS) *</label>
                    <input type="number" name="amount" id="payment_amount" class="form-control" required min="1">
                </div>
                <div class="form-group">
                    <label class="form-label">Payment Year *</label>
                    <select name="payment_year" class="form-control" required>
                        <?php for($y = $current_year + 1; $y >= $current_year - 2; $y--): ?>
                        <option value="<?php echo $y; ?>" <?php echo $y == $current_year ? 'selected' : ''; ?>><?php echo $y; ?></option>
                        <?php endfor; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">Payment Date *</label>
                    <input type="date" name="payment_date" class="form-control" value="<?php echo date('Y-m-d'); ?>" required>
                </div>
                <div class="form-group">
                    <label class="form-label">Payment Method</label>
                    <select name="payment_method" class="form-control">
                        <option value="cash">Cash</option>
                        <option value="bank_transfer">Bank Transfer</option>
                        <option value="mobile_money">Mobile Money</option>
                        <option value="other">Other</option>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">Reference Number</label>
                    <input type="text" name="reference_number" class="form-control" placeholder="Transaction ID">
                </div>
                <div class="form-group">
                    <label class="form-label">Notes</label>
                    <textarea name="notes" class="form-control" rows="2"></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline" onclick="closeModal()">Cancel</button>
                <button type="submit" class="btn btn-success"><i class="fas fa-save"></i> Record Payment</button>
            </div>
        </form>
    </div>

    <script src="../assets/vendor/jquery/jquery.min.js"></script>
    <script src="../assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script>
        // Tab switching
        function showTab(tabName) {
            document.querySelectorAll('.tab-content').forEach(tab => tab.classList.remove('active'));
            document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
            document.getElementById('tab-' + tabName).classList.add('active');
            event.target.closest('.tab-btn').classList.add('active');
        }

        // Modal functions
        function openModal(modalId) {
            document.getElementById('modalBackdrop').classList.add('active');
            document.getElementById(modalId).classList.add('active');
        }

        function closeModal() {
            document.getElementById('modalBackdrop').classList.remove('active');
            document.querySelectorAll('.modal').forEach(m => m.classList.remove('active'));
        }

        function openUpgradeModal(userId, userName, defaultAmount) {
            document.getElementById('upgrade_user_id').value = userId;
            document.getElementById('upgrade_user_name').textContent = userName;
            document.getElementById('upgrade_custom_amount').value = '';
            openModal('upgradeModal');
        }

        function openCustomAmountModal(userId, userName, currentAmount) {
            document.getElementById('custom_user_id').value = userId;
            document.getElementById('custom_user_name').textContent = userName;
            document.getElementById('custom_amount_value').value = currentAmount;
            openModal('customAmountModal');
        }

        function openPaymentModal(userId, userName, userType, customAmount) {
            document.getElementById('payment_user_id').value = userId;
            document.getElementById('payment_user_name').textContent = userName;

            // Set default amount based on user type
            let defaultAmount = userType === 'premium'
                ? (customAmount > 0 ? customAmount : <?php echo $premium_yearly_fee; ?>)
                : <?php echo $basic_yearly_fee; ?>;
            document.getElementById('payment_amount').value = defaultAmount;

            openModal('paymentModal');
        }

        // User search
        function filterUsers() {
            const search = document.getElementById('userSearch').value.toLowerCase();
            const rows = document.querySelectorAll('#usersTable tbody tr');

            rows.forEach(row => {
                const text = row.textContent.toLowerCase();
                row.style.display = text.includes(search) ? '' : 'none';
            });
        }

        // Close modal on escape
        document.addEventListener('keydown', e => {
            if (e.key === 'Escape') closeModal();
        });
    </script>
</body>
</html>
