<?php
// admin.php - Complete Fixed Version (No Header Errors)

// Start output buffering and session at the VERY BEGINNING
ob_start();
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once 'config.php';
require_once 'inc/db.php';
require_once 'inc/functions.php';
require_once 'inc/telegram.php';

// Check admin authentication
function check_admin_auth() {
    if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
        if (isset($_POST['admin_token'])) {
            if ($_POST['admin_token'] === ADMIN_TOKEN) {
                $_SESSION['admin_logged_in'] = true;
                $_SESSION['login_time'] = time();
                // Use JavaScript redirect to avoid header issues
                echo '<script>window.location.href = "admin.php";</script>';
                exit;
            } else {
                show_login_form("Invalid token!");
                exit;
            }
        } else {
            show_login_form();
            exit;
        }
    }
    
    // Auto logout after 2 hours - Fixed with isset check
    if (isset($_SESSION['login_time']) && (time() - $_SESSION['login_time'] > 7200)) {
        session_destroy();
        show_login_form("Session expired. Please login again.");
        exit;
    }
}

// Show login form
function show_login_form($error = '') {
    // Clear buffer and show login form
    ob_clean();
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Admin Login - File Locker Bot</title>
        <style>
            * { box-sizing: border-box; }
            body { 
                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; 
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                margin: 0; 
                padding: 0; 
                min-height: 100vh;
                display: flex;
                align-items: center;
                justify-content: center;
            }
            .login-container {
                background: white;
                border-radius: 15px;
                box-shadow: 0 15px 35px rgba(0,0,0,0.1);
                padding: 40px;
                width: 100%;
                max-width: 400px;
            }
            .login-header {
                text-align: center;
                margin-bottom: 30px;
            }
            .login-header h2 {
                color: #333;
                margin: 0;
                font-size: 28px;
            }
            .login-header p {
                color: #666;
                margin: 10px 0 0 0;
            }
            .form-group { 
                margin-bottom: 20px; 
            }
            label { 
                display: block; 
                margin-bottom: 8px; 
                font-weight: 600;
                color: #333;
            }
            input[type="password"] { 
                width: 100%; 
                padding: 12px 15px;
                border: 2px solid #e1e5e9;
                border-radius: 8px;
                font-size: 16px;
                transition: border-color 0.3s;
            }
            input[type="password"]:focus {
                outline: none;
                border-color: #007bff;
            }
            button { 
                background: linear-gradient(135deg, #007bff, #0056b3);
                color: white; 
                padding: 12px 20px; 
                border: none; 
                border-radius: 8px; 
                cursor: pointer; 
                font-size: 16px;
                font-weight: 600;
                width: 100%;
                transition: transform 0.2s;
            }
            button:hover {
                transform: translateY(-2px);
            }
            .error { 
                background: #f8d7da;
                color: #721c24; 
                padding: 12px;
                border-radius: 6px;
                margin-bottom: 20px;
                border-left: 4px solid #dc3545;
            }
        </style>
    </head>
    <body>
        <div class="login-container">
            <div class="login-header">
                <h2>🔐 Admin Login</h2>
                <p>File Locker Bot Control Panel</p>
            </div>
            <?php if ($error): ?>
                <div class="error"><?php echo htmlspecialchars($error); ?></div>
            <?php endif; ?>
            <form method="post">
                <div class="form-group">
                    <label for="admin_token">Admin Token:</label>
                    <input type="password" id="admin_token" name="admin_token" required placeholder="Enter your admin token">
                </div>
                <button type="submit">Login to Dashboard</button>
            </form>
        </div>
    </body>
    </html>
    <?php
    exit;
}

// Main admin panel
function show_admin_panel() {
    $action = $_GET['action'] ?? 'dashboard';
    
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Admin Panel - File Locker Bot</title>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
        <style>
            :root {
                --primary: #007bff;
                --secondary: #6c757d;
                --success: #28a745;
                --danger: #dc3545;
                --warning: #ffc107;
                --info: #17a2b8;
                --light: #f8f9fa;
                --dark: #343a40;
            }
            
            * { box-sizing: border-box; }
            body { 
                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; 
                margin: 0; 
                padding: 0; 
                background: #f5f7fa;
                color: #333;
            }
            .header { 
                background: linear-gradient(135deg, var(--primary), #0056b3);
                color: white; 
                padding: 20px; 
                box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            }
            .header h1 { 
                margin: 0; 
                font-size: 24px;
                display: flex;
                align-items: center;
                gap: 10px;
            }
            .nav { 
                background: white; 
                padding: 0 20px;
                border-bottom: 1px solid #e1e5e9;
                box-shadow: 0 2px 5px rgba(0,0,0,0.05);
                display: flex;
                flex-wrap: wrap;
            }
            .nav a { 
                margin-right: 5px;
                text-decoration: none; 
                color: var(--secondary); 
                padding: 12px 16px; 
                border-radius: 6px;
                transition: all 0.3s;
                font-weight: 500;
                display: flex;
                align-items: center;
                gap: 8px;
            }
            .nav a:hover { 
                background: var(--light);
                color: var(--primary);
            }
            .nav a.active { 
                background: var(--primary);
                color: white;
            }
            .nav a.logout { 
                margin-left: auto; 
                background: var(--danger);
                color: white;
            }
            .nav a.logout:hover {
                background: #c82333;
            }
            .container { 
                padding: 25px; 
                max-width: 1400px;
                margin: 0 auto;
            }
            .card { 
                background: white; 
                padding: 25px; 
                margin-bottom: 25px; 
                border-radius: 12px; 
                box-shadow: 0 3px 15px rgba(0,0,0,0.08);
                border: 1px solid #e1e5e9;
            }
            .card h2 {
                margin-top: 0;
                color: var(--dark);
                border-bottom: 2px solid var(--light);
                padding-bottom: 15px;
                display: flex;
                align-items: center;
                gap: 10px;
            }
            table { 
                width: 100%; 
                border-collapse: collapse;
                margin-top: 15px;
            }
            th, td { 
                padding: 12px 15px; 
                text-align: left; 
                border-bottom: 1px solid #e1e5e9; 
            }
            th { 
                background: var(--light);
                font-weight: 600;
                color: var(--dark);
            }
            tr:hover {
                background: #f8f9fa;
            }
            .btn { 
                padding: 8px 16px; 
                border: none; 
                border-radius: 6px; 
                cursor: pointer; 
                text-decoration: none; 
                display: inline-flex;
                align-items: center;
                gap: 6px;
                font-size: 14px;
                font-weight: 500;
                transition: all 0.3s;
            }
            .btn-sm {
                padding: 6px 12px;
                font-size: 13px;
            }
            .btn-primary { background: var(--primary); color: white; }
            .btn-success { background: var(--success); color: white; }
            .btn-danger { background: var(--danger); color: white; }
            .btn-warning { background: var(--warning); color: black; }
            .btn-info { background: var(--info); color: white; }
            .btn:hover {
                transform: translateY(-1px);
                box-shadow: 0 3px 8px rgba(0,0,0,0.2);
            }
            .form-group { 
                margin-bottom: 20px; 
            }
            label { 
                display: block; 
                margin-bottom: 8px; 
                font-weight: 600;
                color: var(--dark);
            }
            input, select, textarea { 
                width: 100%; 
                padding: 12px 15px; 
                border: 2px solid #e1e5e9; 
                border-radius: 8px; 
                font-size: 15px;
                transition: border-color 0.3s;
            }
            input:focus, select:focus, textarea:focus {
                outline: none;
                border-color: var(--primary);
            }
            .stats-grid { 
                display: grid; 
                grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); 
                gap: 20px; 
                margin-top: 20px; 
            }
            .stat-card { 
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                padding: 25px; 
                border-radius: 12px; 
                text-align: center;
                box-shadow: 0 5px 15px rgba(0,0,0,0.1);
                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);
                transform: rotate(30deg);
            }
            .stat-card h3 {
                margin: 0 0 10px 0;
                font-size: 14px;
                opacity: 0.9;
                text-transform: uppercase;
                letter-spacing: 1px;
            }
            .stat-card .number {
                font-size: 32px;
                font-weight: bold;
                margin: 0;
            }
            .stat-card .icon {
                font-size: 24px;
                margin-bottom: 10px;
            }
            .broadcast-status { 
                padding: 15px; 
                margin: 15px 0; 
                border-radius: 8px; 
                border-left: 4px solid;
            }
            .success { 
                background: #d4edda; 
                color: #155724; 
                border-left-color: var(--success);
            }
            .error { 
                background: #f8d7da; 
                color: #721c24; 
                border-left-color: var(--danger);
            }
            .warning { 
                background: #fff3cd; 
                color: #856404; 
                border-left-color: var(--warning);
            }
            .info {
                background: #d1ecf1;
                color: #0c5460;
                border-left-color: var(--info);
            }
            .notification-badge {
                background: var(--danger);
                color: white;
                border-radius: 50%;
                padding: 2px 6px;
                font-size: 12px;
                margin-left: 5px;
            }
            .user-avatar {
                width: 40px;
                height: 40px;
                border-radius: 50%;
                background: var(--primary);
                color: white;
                display: flex;
                align-items: center;
                justify-content: center;
                font-weight: bold;
                margin-right: 10px;
            }
            .file-type-badge {
                padding: 4px 8px;
                border-radius: 12px;
                font-size: 12px;
                font-weight: 600;
            }
            .file-free { background: #d4edda; color: #155724; }
            .file-paid { background: #fff3cd; color: #856404; }
        </style>
    </head>
    <body>
        <div class="header">
            <h1><i class="fas fa-robot"></i> File Locker Bot - Admin Panel</h1>
        </div>
        
        <div class="nav">
            <a href="?action=dashboard" class="<?php echo $action == 'dashboard' ? 'active' : ''; ?>">
                <i class="fas fa-tachometer-alt"></i> Dashboard
            </a>
            <a href="?action=files" class="<?php echo $action == 'files' ? 'active' : ''; ?>">
                <i class="fas fa-file"></i> Files
            </a>
            <a href="?action=upload" class="<?php echo $action == 'upload' ? 'active' : ''; ?>">
                <i class="fas fa-upload"></i> Upload File
            </a>
            <a href="?action=requests" class="<?php echo $action == 'requests' ? 'active' : ''; ?>">
                <i class="fas fa-unlock"></i> Unlock Requests
                <?php
                $pending_count = db_query("SELECT COUNT(*) as count FROM unlock_requests WHERE status = 'pending'")->fetch()['count'];
                if ($pending_count > 0): ?>
                    <span class="notification-badge"><?php echo $pending_count; ?></span>
                <?php endif; ?>
            </a>
            <a href="?action=broadcast" class="<?php echo $action == 'broadcast' ? 'active' : ''; ?>">
                <i class="fas fa-bullhorn"></i> Broadcast
            </a>
            <a href="?action=users" class="<?php echo $action == 'users' ? 'active' : ''; ?>">
                <i class="fas fa-users"></i> Users
            </a>
            <a href="?action=logout" class="logout">
                <i class="fas fa-sign-out-alt"></i> Logout
            </a>
        </div>
        
        <div class="container">
            <?php
            // Check for session notifications
            if (isset($_SESSION['notification'])) {
                $notification = $_SESSION['notification'];
                echo '<div class="broadcast-status ' . $notification['type'] . '">';
                echo '<i class="fas fa-' . ($notification['type'] == 'success' ? 'check-circle' : 
                                      ($notification['type'] == 'error' ? 'exclamation-circle' : 'exclamation-triangle')) . '"></i> ';
                echo $notification['message'];
                echo '</div>';
                unset($_SESSION['notification']);
            }
            
            switch ($action) {
                case 'dashboard':
                    show_dashboard();
                    break;
                case 'files':
                    show_files();
                    break;
                case 'upload':
                    show_upload_form();
                    break;
                case 'requests':
                    show_unlock_requests();
                    break;
                case 'broadcast':
                    show_broadcast_form();
                    break;
                case 'users':
                    show_users_list();
                    break;
                case 'send_broadcast':
                    send_broadcast_message();
                    break;
                case 'approve':
                    approve_request($_GET['id']);
                    break;
                case 'reject':
                    reject_request($_GET['id']);
                    break;
                case 'delete':
                    handle_delete_file($_GET['id']);
                    break;
                case 'delete_user':
                    handle_delete_user($_GET['id']);
                    break;
                case 'logout':
                    session_destroy();
                    echo '<script>window.location.href = "admin.php";</script>';
                    exit;
                default:
                    show_dashboard();
            }
            ?>
        </div>

        <script>
            // Auto-hide notifications after 5 seconds
            setTimeout(() => {
                const notifications = document.querySelectorAll('.broadcast-status');
                notifications.forEach(notification => {
                    notification.style.opacity = '0';
                    notification.style.transition = 'opacity 0.5s';
                    setTimeout(() => notification.remove(), 500);
                });
            }, 5000);

            // Confirmations for destructive actions
            document.addEventListener('DOMContentLoaded', function() {
                const deleteLinks = document.querySelectorAll('a[href*="action=delete"]');
                deleteLinks.forEach(link => {
                    link.addEventListener('click', function(e) {
                        if (!confirm('Are you sure you want to delete this? This action cannot be undone.')) {
                            e.preventDefault();
                        }
                    });
                });
            });

            // Toggle buttons section in broadcast form
            function toggleButtonsSection() {
                const includeButtons = document.getElementById('include_buttons');
                const buttonsSection = document.getElementById('buttons_section');
                if (includeButtons && buttonsSection) {
                    buttonsSection.style.display = includeButtons.checked ? 'block' : 'none';
                }
            }

            // Set default subjects based on message type
            function setDefaultSubject() {
                const type = document.getElementById('message_type').value;
                const subjectField = document.getElementById('subject');
                const subjects = {
                    'text': 'Important Message',
                    'announcement': 'Important Announcement',
                    'promotion': 'Special Promotion',
                    'update': 'System Update'
                };
                if (subjects[type] && subjectField) {
                    subjectField.value = subjects[type];
                }
            }

            // Initialize on page load
            document.addEventListener('DOMContentLoaded', function() {
                toggleButtonsSection();
                setDefaultSubject();
                
                // Add event listeners
                const includeButtons = document.getElementById('include_buttons');
                const messageType = document.getElementById('message_type');
                
                if (includeButtons) {
                    includeButtons.addEventListener('change', toggleButtonsSection);
                }
                if (messageType) {
                    messageType.addEventListener('change', setDefaultSubject);
                }
            });
        </script>
    </body>
    </html>
    <?php
}

// Dashboard
function show_dashboard() {
    $stats = get_system_stats();
    $notifications = get_admin_notifications();
    ?>
    <div class="card">
        <h2><i class="fas fa-tachometer-alt"></i> Dashboard Overview</h2>
        
        <?php if (!empty($notifications)): ?>
            <div class="notifications">
                <?php foreach ($notifications as $notification): ?>
                    <div class="broadcast-status warning">
                        <i class="fas fa-bell"></i> <?php echo $notification['message']; ?>
                        <a href="<?php echo $notification['url']; ?>" class="btn btn-sm btn-primary" style="margin-left: 10px;">View</a>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
        
        <div class="stats-grid">
            <div class="stat-card">
                <div class="icon"><i class="fas fa-users"></i></div>
                <h3>Total Users</h3>
                <p class="number"><?php echo $stats['total_users']; ?></p>
            </div>
            <div class="stat-card">
                <div class="icon"><i class="fas fa-file"></i></div>
                <h3>Total Files</h3>
                <p class="number"><?php echo $stats['total_files']; ?></p>
            </div>
            <div class="stat-card">
                <div class="icon"><i class="fas fa-unlock"></i></div>
                <h3>Pending Requests</h3>
                <p class="number"><?php echo $stats['pending_requests']; ?></p>
            </div>
            <div class="stat-card">
                <div class="icon"><i class="fas fa-chart-line"></i></div>
                <h3>Today's Activity</h3>
                <p class="number"><?php echo $stats['today_users'] + $stats['today_requests']; ?></p>
            </div>
        </div>
    </div>

    <div class="card">
        <h2><i class="fas fa-chart-bar"></i> Quick Statistics</h2>
        <div class="stats-grid">
            <div style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);" class="stat-card">
                <div class="icon"><i class="fas fa-file-download"></i></div>
                <h3>Free Files</h3>
                <p class="number"><?php echo $stats['free_files']; ?></p>
            </div>
            <div style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);" class="stat-card">
                <div class="icon"><i class="fas fa-file-invoice-dollar"></i></div>
                <h3>Paid Files</h3>
                <p class="number"><?php echo $stats['paid_files']; ?></p>
            </div>
            <div style="background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);" class="stat-card">
                <div class="icon"><i class="fas fa-check-circle"></i></div>
                <h3>Approved Requests</h3>
                <p class="number"><?php echo $stats['approved_requests']; ?></p>
            </div>
            <div style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);" class="stat-card">
                <div class="icon"><i class="fas fa-times-circle"></i></div>
                <h3>Rejected Requests</h3>
                <p class="number"><?php echo $stats['rejected_requests']; ?></p>
            </div>
        </div>
    </div>

    <div class="card">
        <h2><i class="fas fa-rocket"></i> Quick Actions</h2>
        <div style="display: flex; gap: 15px; flex-wrap: wrap;">
            <a href="?action=upload" class="btn btn-primary">
                <i class="fas fa-upload"></i> Upload New File
            </a>
            <a href="?action=requests" class="btn btn-warning">
                <i class="fas fa-unlock"></i> Manage Requests
            </a>
            <a href="?action=broadcast" class="btn btn-info">
                <i class="fas fa-bullhorn"></i> Send Broadcast
            </a>
            <a href="?action=users" class="btn btn-success">
                <i class="fas fa-users"></i> View Users
            </a>
        </div>
    </div>

    <div class="card">
        <h2><i class="fas fa-history"></i> Recent Activity</h2>
        <?php
        $recent_activity = get_recent_activity(10);
        if (empty($recent_activity)): ?>
            <p>No recent activity.</p>
        <?php else: ?>
            <table>
                <thead>
                    <tr>
                        <th>User</th>
                        <th>Action</th>
                        <th>Details</th>
                        <th>Time</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($recent_activity as $activity): ?>
                    <tr>
                        <td>
                            <?php if ($activity['username']): ?>
                                @<?php echo $activity['username']; ?>
                            <?php else: ?>
                                <?php echo htmlspecialchars($activity['first_name']); ?>
                            <?php endif; ?>
                        </td>
                        <td><?php echo ucfirst(str_replace('_', ' ', $activity['action'])); ?></td>
                        <td><?php echo htmlspecialchars($activity['details']); ?></td>
                        <td><?php echo date('M j, H:i', strtotime($activity['created_at'])); ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>
    <?php
}

// Show files list
function show_files() {
    if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['delete_file'])) {
        handle_delete_file($_POST['file_id']);
    }
    
    $files = get_all_files();
    ?>
    <div class="card">
        <h2><i class="fas fa-file"></i> Uploaded Files</h2>
        
        <?php if (empty($files)): ?>
            <div class="broadcast-status info">
                <i class="fas fa-info-circle"></i> No files uploaded yet. 
                <a href="?action=upload" class="btn btn-sm btn-primary">Upload Your First File</a>
            </div>
        <?php else: ?>
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Title</th>
                        <th>Public ID</th>
                        <th>Type</th>
                        <th>Required Channels</th>
                        <th>Downloads</th>
                        <th>Date</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($files as $file): 
                        $download_count = get_file_download_count($file['id']);
                    ?>
                    <tr>
                        <td><?php echo $file['id']; ?></td>
                        <td>
                            <strong><?php echo htmlspecialchars($file['title']); ?></strong>
                        </td>
                        <td><code><?php echo $file['public_id']; ?></code></td>
                        <td>
                            <span class="file-type-badge <?php echo $file['is_paid'] ? 'file-paid' : 'file-free'; ?>">
                                <?php echo $file['is_paid'] ? '💰 Paid' : '🆓 Free'; ?>
                            </span>
                            <?php if ($file['is_paid']): ?>
                                <br><small><?php echo htmlspecialchars($file['price_text']); ?></small>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if (!empty($file['required_channels'])): ?>
                                <?php 
                                $channels = explode(',', $file['required_channels']);
                                foreach ($channels as $channel): ?>
                                    <span style="display: block; font-size: 12px; color: #666;">@<?php echo trim($channel); ?></span>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <em>None</em>
                            <?php endif; ?>
                        </td>
                        <td><?php echo $download_count; ?></td>
                        <td><?php echo date('M j, Y', strtotime($file['created_at'])); ?></td>
                        <td>
                            <a href="?action=delete&id=<?php echo $file['id']; ?>" class="btn btn-danger btn-sm" 
                               onclick="return confirm('Are you sure you want to delete \"<?php echo addslashes($file['title']); ?>\"?')">
                                <i class="fas fa-trash"></i> Delete
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>
    <?php
}

// Show upload form
function show_upload_form() {
    if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['file'])) {
        handle_file_upload();
    }
    ?>
    <div class="card">
        <h2><i class="fas fa-upload"></i> Upload New File</h2>
        <form method="post" enctype="multipart/form-data">
            <div class="form-group">
                <label for="title">File Title:</label>
                <input type="text" id="title" name="title" required placeholder="Enter a descriptive title for the file">
            </div>
            
            <div class="form-group">
                <label for="file">Select File:</label>
                <input type="file" id="file" name="file" required 
                       accept="<?php echo implode(',', array_map(function($type) { return '.' . $type; }, ALLOWED_TYPES)); ?>">
                <small>Max size: <?php echo round(MAX_FILE_SIZE / 1024 / 1024); ?>MB | 
                Allowed types: <?php echo implode(', ', ALLOWED_TYPES); ?></small>
            </div>
            
            <div class="form-group">
                <label for="public_id">Public ID (for /fil command):</label>
                <input type="text" id="public_id" name="public_id" required 
                       pattern="[a-zA-Z0-9_]+" placeholder="e.g., python_course, ebook_2024">
                <small>Only letters, numbers, and underscore. No spaces or special characters.</small>
            </div>
            
            <div class="form-group">
                <label for="required_channels">Required Channels (comma separated):</label>
                <input type="text" id="required_channels" name="required_channels" 
                       placeholder="channel1, channel2 (without @)">
                <small>Users must join these channels to access the file. Separate multiple channels with commas.</small>
            </div>
            
            <div class="form-group">
                <label for="is_paid">
                    <input type="checkbox" id="is_paid" name="is_paid" value="1"> This is a paid file
                </label>
            </div>
            
            <div class="form-group" id="price_field" style="display: none;">
                <label for="price_text">Price Text:</label>
                <input type="text" id="price_text" name="price_text" placeholder="$10, 0.001 BTC, ₹500, etc.">
                <small>This text will be shown to users. You'll handle payments manually.</small>
            </div>
            
            <button type="submit" class="btn btn-primary">
                <i class="fas fa-upload"></i> Upload File
            </button>
        </form>
    </div>
    
    <script>
        document.getElementById('is_paid').addEventListener('change', function() {
            document.getElementById('price_field').style.display = this.checked ? 'block' : 'none';
        });
    </script>
    <?php
}

// Handle file upload
function handle_file_upload() {
    $title = trim($_POST['title']);
    $public_id = trim($_POST['public_id']);
    $required_channels = trim($_POST['required_channels']);
    $is_paid = isset($_POST['is_paid']);
    $price_text = $_POST['price_text'] ?? '';
    
    // Validate public_id format
    if (!preg_match('/^[a-zA-Z0-9_]+$/', $public_id)) {
        echo "<div class='broadcast-status error'>Error: Public ID can only contain letters, numbers, and underscore.</div>";
        return;
    }
    
    // Check if public_id already exists
    if (public_id_exists($public_id)) {
        echo "<div class='broadcast-status error'>Error: Public ID '{$public_id}' already exists! Please choose a different one.</div>";
        return;
    }
    
    $file = $_FILES['file'];
    
    // Validate file size
    if ($file['size'] > MAX_FILE_SIZE) {
        echo "<div class='broadcast-status error'>Error: File too large! Maximum size is " . round(MAX_FILE_SIZE / 1024 / 1024) . "MB</div>";
        return;
    }
    
    // Validate file type
    if (!validate_file_type($file['name'])) {
        echo "<div class='broadcast-status error'>Error: File type not allowed! Allowed types: " . implode(', ', ALLOWED_TYPES) . "</div>";
        return;
    }
    
    // Generate unique filename
    $filename = generate_unique_filename($file['name']);
    $upload_path = __DIR__ . '/uploads/' . $filename;
    
    if (move_uploaded_file($file['tmp_name'], $upload_path)) {
        // Save to database
        $file_id = save_file_info($title, $filename, $public_id, $required_channels, $is_paid, $price_text);
        
        echo "<div class='broadcast-status success'>";
        echo "<i class='fas fa-check-circle'></i> File uploaded successfully!<br>";
        echo "<strong>Title:</strong> {$title}<br>";
        echo "<strong>Access Command:</strong> <code>/fil{$public_id}</code><br>";
        echo "<strong>Type:</strong> " . ($is_paid ? "Paid ({$price_text})" : "Free");
        echo "</div>";
        
        // Log activity
        log_activity(0, 'file_uploaded', "Title: {$title}, Public ID: {$public_id}");
    } else {
        echo "<div class='broadcast-status error'>Error uploading file! Please check folder permissions or try again.</div>";
    }
}

// Show unlock requests
function show_unlock_requests() {
    $requests = get_pending_requests();
    ?>
    <div class="card">
        <h2><i class="fas fa-unlock"></i> Pending Unlock Requests</h2>
        
        <?php if (empty($requests)): ?>
            <div class="broadcast-status success">
                <i class="fas fa-check-circle"></i> No pending unlock requests. All clear!
            </div>
        <?php else: ?>
            <div class="broadcast-status warning">
                <i class="fas fa-exclamation-triangle"></i> 
                You have <?php echo count($requests); ?> pending unlock request(s) waiting for approval.
            </div>
            
            <table>
                <thead>
                    <tr>
                        <th>Request ID</th>
                        <th>User</th>
                        <th>File</th>
                        <th>Price</th>
                        <th>Request Date</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($requests as $request): ?>
                    <tr>
                        <td>#<?php echo $request['id']; ?></td>
                        <td>
                            <div style="display: flex; align-items: center;">
                                <div class="user-avatar">
                                    <?php echo strtoupper(substr($request['first_name'], 0, 1)); ?>
                                </div>
                                <div>
                                    <strong><?php echo htmlspecialchars($request['first_name'] . ' ' . $request['last_name']); ?></strong>
                                    <?php if ($request['username']): ?>
                                        <br><small>@<?php echo $request['username']; ?></small>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </td>
                        <td>
                            <strong><?php echo htmlspecialchars($request['title']); ?></strong>
                            <br><small>ID: <?php echo $request['public_id']; ?></small>
                        </td>
                        <td>
                            <?php
                            $file = get_file_by_public_id($request['public_id']);
                            echo $file && $file['is_paid'] ? $file['price_text'] : 'Free';
                            ?>
                        </td>
                        <td><?php echo date('M j, Y H:i', strtotime($request['created_at'])); ?></td>
                        <td>
                            <div style="display: flex; gap: 5px;">
                                <a href="?action=approve&id=<?php echo $request['id']; ?>" class="btn btn-success btn-sm"
                                   onclick="return confirm('Approve request from <?php echo addslashes($request['first_name']); ?>?')">
                                    <i class="fas fa-check"></i> Approve
                                </a>
                                <a href="?action=reject&id=<?php echo $request['id']; ?>" class="btn btn-danger btn-sm"
                                   onclick="return confirm('Reject request from <?php echo addslashes($request['first_name']); ?>?')">
                                    <i class="fas fa-times"></i> Reject
                                </a>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>
    <?php
}

// Show broadcast form
function show_broadcast_form() {
    // Get total users count
    $users_count = db_query("SELECT COUNT(*) as count FROM users")->fetch()['count'];
    $broadcast_stats = get_broadcast_stats();
    ?>
    <div class="card">
        <h2><i class="fas fa-bullhorn"></i> Broadcast Message</h2>
        <p>Send a message to <strong>all <?php echo $users_count; ?> users</strong> at once.</p>
        
        <?php
        // Show broadcast result if available
        if (isset($_SESSION['broadcast_result'])) {
            $result = $_SESSION['broadcast_result'];
            echo '<div class="broadcast-status ' . ($result['success'] ? 'success' : 'error') . '">';
            echo '<h4><i class="fas fa-' . ($result['success'] ? 'check-circle' : 'exclamation-circle') . '"></i> ' . 
                 ($result['success'] ? 'Broadcast Completed!' : 'Broadcast Failed') . '</h4>';
            echo '<p><strong>Total Users:</strong> ' . $result['total_users'] . '</p>';
            echo '<p><strong>Successful:</strong> ' . $result['success_count'] . '</p>';
            echo '<p><strong>Failed:</strong> ' . $result['failed_count'] . '</p>';
            if (!empty($result['error'])) {
                echo '<p><strong>Note:</strong> ' . $result['error'] . '</p>';
            }
            echo '</div>';
            unset($_SESSION['broadcast_result']);
        }
        ?>
        
        <form method="post" action="?action=send_broadcast">
            <div class="form-group">
                <label for="message_type">Message Type:</label>
                <select id="message_type" name="message_type" required onchange="setDefaultSubject()">
                    <option value="text">📝 Text Message</option>
                    <option value="announcement">📢 Announcement</option>
                    <option value="promotion">🎉 Promotion</option>
                    <option value="update">🔄 Update Notification</option>
                </select>
            </div>
            
            <div class="form-group">
                <label for="subject">Subject/Title:</label>
                <input type="text" id="subject" name="subject" placeholder="Enter message subject" required>
            </div>
            
            <div class="form-group">
                <label for="message">Message Content:</label>
                <textarea id="message" name="message" rows="8" placeholder="Enter your broadcast message here..." required></textarea>
                <small>You can use HTML formatting. Maximum 4096 characters.</small>
            </div>
            
            <div class="form-group">
                <label for="include_buttons">
                    <input type="checkbox" id="include_buttons" name="include_buttons" value="1"> Include Action Buttons
                </label>
            </div>
            
            <div id="buttons_section" style="display: none;">
                <div class="form-group">
                    <label>Button 1 Text:</label>
                    <input type="text" name="button1_text" placeholder="e.g., Visit Website">
                </div>
                <div class="form-group">
                    <label>Button 1 URL:</label>
                    <input type="url" name="button1_url" placeholder="https://example.com">
                </div>
                <div class="form-group">
                    <label>Button 2 Text:</label>
                    <input type="text" name="button2_text" placeholder="e.g., Contact Support">
                </div>
                <div class="form-group">
                    <label>Button 2 URL:</label>
                    <input type="url" name="button2_url" placeholder="https://t.me/username">
                </div>
            </div>
            
            <div class="form-group">
                <label>
                    <input type="checkbox" name="confirm" value="1" required> 
                    I confirm that I want to send this message to all <?php echo $users_count; ?> users.
                </label>
            </div>
            
            <button type="submit" class="btn btn-warning" 
                    onclick="return confirm('Are you absolutely sure you want to send this message to ALL <?php echo $users_count; ?> users? This action cannot be undone.')">
                <i class="fas fa-paper-plane"></i> Send Broadcast to All Users
            </button>
        </form>
    </div>
    
    <div class="card">
        <h3><i class="fas fa-chart-bar"></i> Broadcast Statistics</h3>
        <div class="stats-grid">
            <div class="stat-card">
                <div class="icon"><i class="fas fa-users"></i></div>
                <h3>Total Users</h3>
                <p class="number"><?php echo $users_count; ?></p>
            </div>
            <div class="stat-card">
                <div class="icon"><i class="fas fa-bullhorn"></i></div>
                <h3>Total Broadcasts</h3>
                <p class="number"><?php echo $broadcast_stats['total_broadcasts']; ?></p>
            </div>
            <div class="stat-card">
                <div class="icon"><i class="fas fa-paper-plane"></i></div>
                <h3>Messages Sent</h3>
                <p class="number"><?php echo $broadcast_stats['total_messages_sent']; ?></p>
            </div>
            <div class="stat-card">
                <div class="icon"><i class="fas fa-clock"></i></div>
                <h3>Last Broadcast</h3>
                <p class="number" style="font-size: 16px;">
                    <?php
                    echo $broadcast_stats['last_broadcast'] ? 
                         date('M j, H:i', strtotime($broadcast_stats['last_broadcast']['created_at'])) : 'Never';
                    ?>
                </p>
            </div>
        </div>
    </div>
    <?php
}

// Send broadcast message to all users
function send_broadcast_message() {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        $_SESSION['notification'] = [
            'type' => 'error',
            'message' => 'Invalid request method.'
        ];
        echo '<script>window.location.href = "?action=broadcast";</script>';
        exit;
    }
    
    if (!isset($_POST['confirm'])) {
        $_SESSION['broadcast_result'] = [
            'success' => false,
            'error' => 'Please confirm that you want to send this broadcast.',
            'total_users' => 0,
            'success_count' => 0,
            'failed_count' => 0
        ];
        echo '<script>window.location.href = "?action=broadcast";</script>';
        exit;
    }
    
    $subject = trim($_POST['subject']);
    $message_content = trim($_POST['message']);
    $message_type = $_POST['message_type'] ?? 'text';
    $include_buttons = isset($_POST['include_buttons']);
    
    if (empty($subject) || empty($message_content)) {
        $_SESSION['broadcast_result'] = [
            'success' => false,
            'error' => 'Subject and message content are required.',
            'total_users' => 0,
            'success_count' => 0,
            'failed_count' => 0
        ];
        echo '<script>window.location.href = "?action=broadcast";</script>';
        exit;
    }
    
    // Get all users
    $users = db_query("SELECT user_id, first_name, username FROM users")->fetchAll();
    $total_users = count($users);
    $success_count = 0;
    $failed_count = 0;
    
    if ($total_users === 0) {
        $_SESSION['broadcast_result'] = [
            'success' => false,
            'error' => 'No users found to send broadcast to.',
            'total_users' => 0,
            'success_count' => 0,
            'failed_count' => 0
        ];
        echo '<script>window.location.href = "?action=broadcast";</script>';
        exit;
    }
    
    // Prepare message with formatting
    $formatted_message = "📢 <b>{$subject}</b>\n\n";
    $formatted_message .= $message_content;
    $formatted_message .= "\n\n— <i>Admin</i>";
    
    // Prepare keyboard if buttons are included
    $keyboard = null;
    if ($include_buttons) {
        $buttons = [];
        
        if (!empty($_POST['button1_text']) && !empty($_POST['button1_url'])) {
            $buttons[] = [['text' => $_POST['button1_text'], 'url' => $_POST['button1_url']]];
        }
        
        if (!empty($_POST['button2_text']) && !empty($_POST['button2_url'])) {
            $buttons[] = [['text' => $_POST['button2_text'], 'url' => $_POST['button2_url']]];
        }
        
        if (!empty($buttons)) {
            $keyboard = ['inline_keyboard' => $buttons];
        }
    }
    
    // Send message to each user
    foreach ($users as $user) {
        try {
            $result = send_message($user['user_id'], $formatted_message, $keyboard);
            
            if ($result['ok']) {
                $success_count++;
                // Log successful send
                log_broadcast_message($user['user_id'], $subject, 'sent');
            } else {
                $failed_count++;
                // Log failed send
                log_broadcast_message($user['user_id'], $subject, 'failed', $result['description']);
            }
            
            // Small delay to avoid rate limits (20 messages per second)
            usleep(50000); // 0.05 seconds delay
            
        } catch (Exception $e) {
            $failed_count++;
            log_broadcast_message($user['user_id'], $subject, 'failed', $e->getMessage());
        }
    }
    
    // Save broadcast log
    save_broadcast_log($subject, $message_content, $total_users, $success_count, $failed_count);
    
    // Set result in session
    $_SESSION['broadcast_result'] = [
        'success' => $success_count > 0,
        'total_users' => $total_users,
        'success_count' => $success_count,
        'failed_count' => $failed_count,
        'error' => $failed_count > 0 ? "Some messages failed to send (usually because users blocked the bot)." : ""
    ];
    
    echo '<script>window.location.href = "?action=broadcast";</script>';
    exit;
}

// Show users list
function show_users_list() {
    $users = get_all_users();
    $total_users = count($users);
    ?>
    <div class="card">
        <h2><i class="fas fa-users"></i> Registered Users</h2>
        <p>Total: <strong><?php echo $total_users; ?></strong> registered users</p>
        
        <?php if (empty($users)): ?>
            <div class="broadcast-status info">
                <i class="fas fa-info-circle"></i> No users registered yet.
            </div>
        <?php else: ?>
            <table>
                <thead>
                    <tr>
                        <th>User</th>
                        <th>Username</th>
                        <th>User ID</th>
                        <th>Files Downloaded</th>
                        <th>Registered</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($users as $user): 
                        $download_history = get_user_download_history($user['user_id']);
                        $download_count = count($download_history);
                    ?>
                    <tr>
                        <td>
                            <div style="display: flex; align-items: center;">
                                <div class="user-avatar">
                                    <?php echo strtoupper(substr($user['first_name'], 0, 1)); ?>
                                </div>
                                <div>
                                    <strong><?php echo htmlspecialchars($user['first_name'] . ' ' . $user['last_name']); ?></strong>
                                </div>
                            </div>
                        </td>
                        <td>
                            <?php if ($user['username']): ?>
                                @<?php echo $user['username']; ?>
                            <?php else: ?>
                                <em>No username</em>
                            <?php endif; ?>
                        </td>
                        <td><code><?php echo $user['user_id']; ?></code></td>
                        <td>
                            <?php echo $download_count; ?>
                            <?php if ($download_count > 0): ?>
                                <br><small><?php echo $download_count; ?> file(s)</small>
                            <?php endif; ?>
                        </td>
                        <td><?php echo date('M j, Y', strtotime($user['created_at'])); ?></td>
                        <td>
                            <div style="display: flex; gap: 5px;">
                                <a href="?action=broadcast&user_id=<?php echo $user['user_id']; ?>" class="btn btn-primary btn-sm">
                                    <i class="fas fa-envelope"></i> Message
                                </a>
                                <a href="?action=delete_user&id=<?php echo $user['id']; ?>" class="btn btn-danger btn-sm"
                                   onclick="return confirm('Are you sure you want to delete user <?php echo addslashes($user['first_name']); ?>? This cannot be undone.')">
                                    <i class="fas fa-trash"></i> Delete
                                </a>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>
    <?php
}

// Approve unlock request
function approve_request($request_id) {
    $request = db_query("SELECT ur.*, u.user_id, f.title, f.filename FROM unlock_requests ur 
                        JOIN users u ON ur.user_id = u.user_id 
                        JOIN files f ON ur.file_id = f.id 
                        WHERE ur.id = ?", [$request_id])->fetch();
    
    if ($request) {
        // Update request status
        update_unlock_request($request_id, 'approved');
        
        // Send file to user
        $file_path = __DIR__ . '/uploads/' . $request['filename'];
        if (file_exists($file_path)) {
            send_document($request['user_id'], $file_path, "📁 <b>{$request['title']}</b>\n\nYour unlock request has been approved! 🎉");
            
            // Notify admin
            send_message(ADMIN_ID, "✅ Request #{$request_id} approved and file sent to user.");
            
            log_activity($request['user_id'], 'request_approved', "File: {$request['title']}");
            
            $_SESSION['notification'] = [
                'type' => 'success',
                'message' => "Request approved and file sent to user!"
            ];
        } else {
            send_message(ADMIN_ID, "❌ Error: File not found for request #{$request_id}");
            
            $_SESSION['notification'] = [
                'type' => 'error',
                'message' => "Error: File not found on server!"
            ];
        }
    } else {
        $_SESSION['notification'] = [
            'type' => 'error',
            'message' => "Error: Request not found!"
        ];
    }
    
    echo '<script>window.location.href = "?action=requests";</script>';
    exit;
}

// Reject unlock request
function reject_request($request_id) {
    $request = db_query("SELECT ur.*, u.user_id, f.title FROM unlock_requests ur 
                        JOIN users u ON ur.user_id = u.user_id 
                        JOIN files f ON ur.file_id = f.id 
                        WHERE ur.id = ?", [$request_id])->fetch();
    
    if ($request) {
        update_unlock_request($request_id, 'rejected');
        
        // Notify user
        send_message($request['user_id'], "❌ Your unlock request for '{$request['title']}' has been rejected by admin.");
        
        // Notify admin
        send_message(ADMIN_ID, "❌ Request #{$request_id} rejected.");
        
        log_activity($request['user_id'], 'request_rejected', "File: {$request['title']}");
        
        $_SESSION['notification'] = [
            'type' => 'warning',
            'message' => "Request rejected and user notified."
        ];
    } else {
        $_SESSION['notification'] = [
            'type' => 'error',
            'message' => "Error: Request not found!"
        ];
    }
    
    echo '<script>window.location.href = "?action=requests";</script>';
    exit;
}

// Handle file deletion
function handle_delete_file($file_id) {
    if (delete_file_by_id($file_id)) {
        $_SESSION['notification'] = [
            'type' => 'success',
            'message' => "File deleted successfully!"
        ];
    } else {
        $_SESSION['notification'] = [
            'type' => 'error',
            'message' => "Error: File not found!"
        ];
    }
    
    echo '<script>window.location.href = "?action=files";</script>';
    exit;
}

// Handle user deletion
function handle_delete_user($user_id) {
    // Delete user's activity logs
    db_query("DELETE FROM activity_logs WHERE user_id = (SELECT user_id FROM users WHERE id = ?)", [$user_id]);
    
    // Delete user's unlock requests
    db_query("DELETE FROM unlock_requests WHERE user_id = (SELECT user_id FROM users WHERE id = ?)", [$user_id]);
    
    // Delete user's message logs
    db_query("DELETE FROM user_messages WHERE user_id = (SELECT user_id FROM users WHERE id = ?)", [$user_id]);
    
    // Delete the user
    $result = db_query("DELETE FROM users WHERE id = ?", [$user_id]);
    
    if ($result->rowCount() > 0) {
        $_SESSION['notification'] = [
            'type' => 'success',
            'message' => "User deleted successfully!"
        ];
    } else {
        $_SESSION['notification'] = [
            'type' => 'error',
            'message' => "Error: User not found!"
        ];
    }
    
    echo '<script>window.location.href = "?action=users";</script>';
    exit;
}

// Main execution
check_admin_auth();
show_admin_panel();

// End output buffering and send output
ob_end_flush();
?>