<?php
require_once dirname(__DIR__) . '/config/config.php';
requireLogin();
requireAdmin();

$pdo = getDBConnection();
$success = '';
$error = '';

// Get current settings
$slideInterval = 2;
try {
    $stmt = $pdo->query("SELECT setting_value FROM site_settings WHERE setting_key = 'banner_slide_interval'");
    $row = $stmt->fetch();
    if ($row) $slideInterval = intval($row['setting_value']);
} catch (Exception $e) {}

// Handle settings update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'settings' && verifyCSRFToken($_POST['csrf_token'] ?? '')) {
    $newInterval = intval($_POST['slide_interval'] ?? 2);
    if ($newInterval < 1) $newInterval = 1;
    if ($newInterval > 10) $newInterval = 10;
    
    try {
        $stmt = $pdo->prepare("INSERT INTO site_settings (setting_key, setting_value) VALUES ('banner_slide_interval', ?) ON DUPLICATE KEY UPDATE setting_value = ?");
        $stmt->execute([$newInterval, $newInterval]);
        $slideInterval = $newInterval;
        $success = 'Slide interval updated to ' . $newInterval . ' seconds!';
    } catch (Exception $e) {
        $error = 'Failed to update settings.';
    }
}

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && verifyCSRFToken($_POST['csrf_token'] ?? '')) {
    $bannerId = intval($_POST['banner_id'] ?? 0);
    $action = $_POST['action'] ?? '';
    
    if ($bannerId && $action) {
        $stmt = $pdo->prepare("SELECT * FROM banners WHERE id = ?");
        $stmt->execute([$bannerId]);
        $banner = $stmt->fetch();
        
        if ($banner) {
            if ($action === 'approve') {
                $expiresAt = date('Y-m-d H:i:s', strtotime('+' . ($banner['days'] ?? 7) . ' days'));
                $stmt = $pdo->prepare("UPDATE banners SET status = 'approved', expires_at = ? WHERE id = ?");
                $stmt->execute([$expiresAt, $bannerId]);
                $success = 'Banner approved successfully!';
            } elseif ($action === 'reject') {
                $reason = trim($_POST['admin_note'] ?? 'Does not meet guidelines');
                $stmt = $pdo->prepare("UPDATE banners SET status = 'rejected', admin_note = ? WHERE id = ?");
                $stmt->execute([$reason, $bannerId]);
                
                // Refund user
                $userModel = new User();
                $userModel->updateBalance($banner['user_id'], $banner['amount_paid'], 'add');
                $success = 'Banner rejected and user refunded $' . number_format($banner['amount_paid'], 2) . '!';
            }
        }
    }
}

// Get all banners
$banners = $pdo->query("SELECT b.*, u.name as user_name, u.email as user_email FROM banners b JOIN users u ON b.user_id = u.id ORDER BY b.created_at DESC")->fetchAll();

$pendingCount = 0;
foreach ($banners as $b) {
    if ($b['status'] === 'pending') $pendingCount++;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Banners - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Segoe UI', sans-serif; background: #0A1628; color: #fff; min-height: 100vh; }
        .sidebar { width: 260px; background: #0F2744; height: 100vh; position: fixed; left: 0; top: 0; z-index: 100; }
        .sidebar-header { padding: 1.5rem; display: flex; align-items: center; gap: 10px; border-bottom: 1px solid #1E3A5F; }
        .sidebar-header i { font-size: 1.5rem; color: #F5A623; }
        .sidebar-header span { font-weight: 700; color: #F5A623; font-size: 1.25rem; }
        .sidebar-nav { padding: 1rem 0; }
        .nav-link { display: flex; align-items: center; gap: 12px; padding: 0.875rem 1.5rem; color: #E5E7EB; text-decoration: none; border-left: 3px solid transparent; }
        .nav-link:hover, .nav-link.active { background: #1E3A5F; color: #F5A623; border-left-color: #F5A623; }
        .nav-link i { width: 20px; text-align: center; }
        .nav-divider { height: 1px; background: #1E3A5F; margin: 0.75rem 1.5rem; }
        .main { margin-left: 260px; padding: 1.5rem; }
        .header { background: #0F2744; padding: 1rem 1.5rem; margin: -1.5rem -1.5rem 1.5rem; display: flex; justify-content: space-between; align-items: center; }
        .page-title { font-size: 1.5rem; margin-bottom: 1.5rem; display: flex; align-items: center; gap: 0.5rem; }
        .page-title i { color: #F5A623; }
        
        .alert { padding: 1rem; border-radius: 8px; margin-bottom: 1rem; }
        .alert-success { background: rgba(16,185,129,0.2); color: #10B981; }
        .alert-danger { background: rgba(239,68,68,0.2); color: #EF4444; }
        
        .settings-box { background: #0F2744; border-radius: 8px; padding: 1rem; margin-bottom: 1rem; border: 1px solid #1E3A5F; }
        
        .tabs { display: flex; gap: 0.5rem; margin-bottom: 1.5rem; }
        .tab { padding: 0.75rem 1.5rem; background: #0F2744; border: none; color: #9CA3AF; border-radius: 8px; cursor: pointer; font-size: 0.9rem; }
        .tab.active { background: #F5A623; color: #0A1628; }
        .tab .badge { background: #EF4444; color: #fff; padding: 0.1rem 0.5rem; border-radius: 10px; font-size: 0.75rem; margin-left: 0.5rem; }
        
        .banner-grid { display: grid; gap: 1rem; }
        .banner-card { background: #0F2744; border-radius: 12px; padding: 1rem; border: 1px solid #1E3A5F; }
        .banner-image { width: 100%; max-height: 150px; object-fit: contain; border-radius: 8px; background: #1E3A5F; margin-bottom: 1rem; }
        .banner-info { display: flex; justify-content: space-between; align-items: start; margin-bottom: 1rem; }
        .banner-user { font-size: 0.9rem; }
        .banner-user .name { color: #F5A623; font-weight: 600; }
        .banner-user .email { color: #9CA3AF; font-size: 0.8rem; }
        .banner-user .date { color: #6B7280; font-size: 0.75rem; margin-top: 0.25rem; }
        .banner-status { padding: 0.25rem 0.75rem; border-radius: 20px; font-size: 0.75rem; font-weight: 600; text-transform: uppercase; }
        .status-pending { background: rgba(245,166,35,0.2); color: #F5A623; }
        .status-approved { background: rgba(16,185,129,0.2); color: #10B981; }
        .status-rejected { background: rgba(239,68,68,0.2); color: #EF4444; }
        
        .banner-link { font-size: 0.8rem; color: #9CA3AF; margin-bottom: 1rem; word-break: break-all; }
        .banner-link a { color: #60A5FA; }
        
        .banner-actions { display: flex; gap: 0.5rem; }
        .btn { padding: 0.5rem 1rem; border: none; border-radius: 6px; cursor: pointer; font-size: 0.85rem; font-weight: 500; }
        .btn-approve { background: #10B981; color: #fff; }
        .btn-reject { background: #EF4444; color: #fff; }
        .btn-sm { padding: 0.4rem 0.75rem; font-size: 0.8rem; }
        
        .rejection-form { margin-top: 0.5rem; display: none; }
        .rejection-form.active { display: block; }
        .rejection-form input { width: 100%; padding: 0.5rem; background: #1E3A5F; border: 1px solid #2D4A6F; border-radius: 6px; color: #fff; margin-bottom: 0.5rem; }
        
        .empty { text-align: center; padding: 3rem; color: #9CA3AF; }
        .empty i { font-size: 3rem; color: #1E3A5F; margin-bottom: 1rem; display: block; }
        
        @media (max-width: 768px) {
            .sidebar { transform: translateX(-260px); }
            .sidebar.active { transform: translateX(0); }
            .main { margin-left: 0; }
        }
    </style>
</head>
<body>
    <aside class="sidebar" id="sidebar">
        <div class="sidebar-header"><i class="fas fa-feather-alt"></i><span><?php echo SITE_NAME; ?></span></div>
        <nav class="sidebar-nav">
            <a href="dashboard.php" class="nav-link"><i class="fas fa-home"></i> Dashboard</a>
            <a href="users.php" class="nav-link"><i class="fas fa-users"></i> Users</a>
            <a href="orders.php" class="nav-link"><i class="fas fa-shopping-cart"></i> Orders</a>
            <a href="fund-requests.php" class="nav-link"><i class="fas fa-money-bill"></i> Fund Requests</a>
            <div class="nav-divider"></div>
            <a href="smm-services.php" class="nav-link"><i class="fas fa-rocket"></i> SMM Services</a>
            <a href="sms-services.php" class="nav-link"><i class="fas fa-sms"></i> SMS Services</a>
            <div class="nav-divider"></div>
            <a href="offers.php" class="nav-link"><i class="fas fa-tags"></i> Offers</a>
            <a href="banners.php" class="nav-link active"><i class="fas fa-ad"></i> Banners</a>
            <a href="support.php" class="nav-link"><i class="fas fa-headset"></i> Support</a>
            <div class="nav-divider"></div>
            <a href="<?php echo SITE_URL; ?>/logout.php" class="nav-link"><i class="fas fa-sign-out-alt"></i> Logout</a>
        </nav>
    </aside>
    
    <main class="main">
        <header class="header">
            <button onclick="document.getElementById('sidebar').classList.toggle('active')" style="background:none;border:none;color:#fff;font-size:1.25rem;cursor:pointer;display:none;" class="mobile-toggle"><i class="fas fa-bars"></i></button>
            <span><i class="fas fa-ad"></i> Banner Management</span>
            <span><?php echo htmlspecialchars($_SESSION['name']); ?></span>
        </header>
        
        <h1 class="page-title"><i class="fas fa-ad"></i> Banner Approvals</h1>
        
        <?php if ($success): ?><div class="alert alert-success"><?php echo $success; ?></div><?php endif; ?>
        <?php if ($error): ?><div class="alert alert-danger"><?php echo $error; ?></div><?php endif; ?>
        
        <div class="settings-box">
            <form method="POST" style="display:flex;align-items:center;gap:1rem;flex-wrap:wrap;">
                <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
                <input type="hidden" name="action" value="settings">
                <label style="color:#9CA3AF;">Slide Interval:</label>
                <select name="slide_interval" style="padding:0.5rem;background:#1E3A5F;border:1px solid #2D4A6F;border-radius:6px;color:#fff;">
                    <?php for ($i = 1; $i <= 10; $i++): ?>
                    <option value="<?php echo $i; ?>" <?php echo $slideInterval == $i ? 'selected' : ''; ?>><?php echo $i; ?> sec</option>
                    <?php endfor; ?>
                </select>
                <button type="submit" class="btn btn-sm" style="background:#F5A623;color:#0A1628;padding:0.5rem 1rem;border:none;border-radius:6px;cursor:pointer;">Save</button>
            </form>
        </div>
        
        <div class="tabs">
            <button class="tab active" onclick="filterBanners('all')">All</button>
            <button class="tab" onclick="filterBanners('pending')">Pending<?php if ($pendingCount > 0): ?><span class="badge"><?php echo $pendingCount; ?></span><?php endif; ?></button>
            <button class="tab" onclick="filterBanners('approved')">Approved</button>
            <button class="tab" onclick="filterBanners('rejected')">Rejected</button>
        </div>
        
        <?php if (empty($banners)): ?>
        <div class="empty">
            <i class="fas fa-image"></i>
            <h3>No Banners</h3>
            <p>No banner submissions yet</p>
        </div>
        <?php else: ?>
        <div class="banner-grid">
            <?php foreach ($banners as $banner): ?>
            <div class="banner-card" data-status="<?php echo $banner['status']; ?>">
                <img src="<?php echo UPLOADS_URL; ?>/banners/<?php echo htmlspecialchars($banner['image_path']); ?>" alt="Banner" class="banner-image">
                <div class="banner-info">
                    <div class="banner-user">
                        <div class="name"><?php echo htmlspecialchars($banner['user_name']); ?></div>
                        <div class="email"><?php echo htmlspecialchars($banner['user_email']); ?></div>
                        <div class="date"><?php echo date('M d, Y H:i', strtotime($banner['created_at'])); ?></div>
                    </div>
                    <span class="banner-status status-<?php echo $banner['status']; ?>"><?php echo ucfirst($banner['status']); ?></span>
                </div>
                
                <?php if ($banner['link_url']): ?>
                <div class="banner-link">Link: <a href="<?php echo htmlspecialchars($banner['link_url']); ?>" target="_blank"><?php echo htmlspecialchars($banner['link_url']); ?></a></div>
                <?php endif; ?>
                
                <div style="font-size:0.85rem;color:#9CA3AF;margin-bottom:0.5rem;">
                    <?php echo $banner['days']; ?> days • $<?php echo number_format($banner['amount_paid'], 2); ?> paid
                </div>
                
                <?php if ($banner['status'] === 'rejected' && $banner['admin_note']): ?>
                <div style="font-size:0.85rem;color:#EF4444;margin-bottom:1rem;">Reason: <?php echo htmlspecialchars($banner['admin_note']); ?></div>
                <?php endif; ?>
                
                <?php if ($banner['status'] === 'approved' && $banner['expires_at']): ?>
                <div style="font-size:0.85rem;color:#10B981;margin-bottom:1rem;">Expires: <?php echo date('M d, Y', strtotime($banner['expires_at'])); ?></div>
                <?php endif; ?>
                
                <?php if ($banner['status'] === 'pending'): ?>
                <div class="banner-actions">
                    <form method="POST" style="display:inline;">
                        <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
                        <input type="hidden" name="banner_id" value="<?php echo $banner['id']; ?>">
                        <input type="hidden" name="action" value="approve">
                        <button type="submit" class="btn btn-approve"><i class="fas fa-check"></i> Approve</button>
                    </form>
                    <button type="button" class="btn btn-reject" onclick="showRejectForm(<?php echo $banner['id']; ?>)"><i class="fas fa-times"></i> Reject</button>
                </div>
                <div class="rejection-form" id="reject-form-<?php echo $banner['id']; ?>">
                    <form method="POST">
                        <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
                        <input type="hidden" name="banner_id" value="<?php echo $banner['id']; ?>">
                        <input type="hidden" name="action" value="reject">
                        <input type="text" name="admin_note" placeholder="Reason for rejection..." required>
                        <button type="submit" class="btn btn-reject btn-sm">Confirm Reject</button>
                    </form>
                </div>
                <?php endif; ?>
            </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </main>
    
    <script>
    function showRejectForm(id) {
        document.getElementById('reject-form-' + id).classList.toggle('active');
    }
    
    function filterBanners(status) {
        document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
        event.target.classList.add('active');
        
        document.querySelectorAll('.banner-card').forEach(card => {
            if (status === 'all' || card.dataset.status === status) {
                card.style.display = 'block';
            } else {
                card.style.display = 'none';
            }
        });
    }
    </script>
</body>
</html>