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

$auth = new Auth();
$userModel = new User();
$currentBalance = $auth->refreshBalance($_SESSION['user_id']);
$pdo = getDBConnection();

// Ensure banners directory exists
if (!is_dir(UPLOADS_PATH . 'banners/')) {
    mkdir(UPLOADS_PATH . 'banners/', 0755, true);
}

$error = '';
$success = '';

// Fetch banner pricing from site_settings (database)
$bannerPrices = [
    1 => 5.00,
    7 => 25.00,
    14 => 40.00,
    30 => 75.00,
    365 => 500.00
];

try {
    $stmt = $pdo->query("SELECT setting_key, setting_value FROM site_settings WHERE setting_key LIKE 'banner_price_%'");
    while ($row = $stmt->fetch()) {
        if ($row['setting_key'] === 'banner_price_1_day') $bannerPrices[1] = floatval($row['setting_value']);
        if ($row['setting_key'] === 'banner_price_7_days') $bannerPrices[7] = floatval($row['setting_value']);
        if ($row['setting_key'] === 'banner_price_14_days') $bannerPrices[14] = floatval($row['setting_value']);
        if ($row['setting_key'] === 'banner_price_30_days') $bannerPrices[30] = floatval($row['setting_value']);
        if ($row['setting_key'] === 'banner_price_365_days') $bannerPrices[365] = floatval($row['setting_value']);
    }
} catch (Exception $e) {}

// Fetch banner dimensions from banner_settings (database)
$maxWidth = 800;
$maxHeight = 200;
try {
    $stmt = $pdo->query("SELECT banner_width, banner_height FROM banner_settings LIMIT 1");
    $bannerSettings = $stmt->fetch();
    if ($bannerSettings) {
        $maxWidth = intval($bannerSettings['banner_width']) ?: 800;
        $maxHeight = intval($bannerSettings['banner_height']) ?: 200;
    }
} catch (Exception $e) {}

$maxFileSize = 2 * 1024 * 1024; // 2MB

// Handle banner submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && verifyCSRFToken($_POST['csrf_token'] ?? '')) {
    $linkUrl = trim($_POST['link_url'] ?? '');
    $days = intval($_POST['days'] ?? 7);
    
    // Validate days - must be one of the allowed durations
    $allowedDays = [1, 7, 14, 30, 365];
    if (!in_array($days, $allowedDays)) {
        $days = 7;
    }
    
    // Get price from database settings
    $totalPrice = $bannerPrices[$days] ?? ($bannerPrices[1] * $days);
    
    // Check balance
    if ($currentBalance < $totalPrice) {
        $error = 'Insufficient balance. Please add funds first.';
    } elseif (!isset($_FILES['banner_image']) || $_FILES['banner_image']['error'] !== UPLOAD_ERR_OK) {
        $error = 'Please select a banner image to upload.';
    } else {
        $file = $_FILES['banner_image'];
        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
        
        if (!in_array($file['type'], $allowedTypes)) {
            $error = 'Invalid file type. Only JPG, PNG, and GIF are allowed.';
        } elseif ($file['size'] > $maxFileSize) {
            $error = 'File too large. Maximum size is ' . ($maxFileSize / 1024 / 1024) . 'MB.';
        } else {
            // Check image dimensions
            $imageInfo = getimagesize($file['tmp_name']);
            if ($imageInfo[0] > $maxWidth || $imageInfo[1] > $maxHeight) {
                $error = "Image too large. Maximum dimensions are {$maxWidth}x{$maxHeight} pixels.";
            } else {
                // Generate unique filename
                $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
                $filename = 'banner_' . $_SESSION['user_id'] . '_' . time() . '.' . $ext;
                $uploadPath = UPLOADS_PATH . 'banners/' . $filename;
                
                if (move_uploaded_file($file['tmp_name'], $uploadPath)) {
                    try {
                        $pdo->beginTransaction();
                        
                        // Deduct balance
                        $userModel->updateBalance($_SESSION['user_id'], $totalPrice, 'subtract');
                        
                        // Insert banner record
                        $stmt = $pdo->prepare("INSERT INTO banners (user_id, image_path, link_url, status, days, amount_paid, created_at) VALUES (?, ?, ?, 'pending', ?, ?, NOW())");
                        $stmt->execute([$_SESSION['user_id'], $filename, $linkUrl, $days, $totalPrice]);
                        
                        $pdo->commit();
                        
                        $currentBalance = $auth->refreshBalance($_SESSION['user_id']);
                        $success = 'Banner submitted successfully! It will be reviewed by our team within 24 hours.';
                    } catch (Exception $e) {
                        $pdo->rollBack();
                        // Delete uploaded file if database insert fails
                        if (file_exists($uploadPath)) {
                            unlink($uploadPath);
                        }
                        $error = 'Failed to submit banner. Please try again.';
                    }
                } else {
                    $error = 'Failed to upload image. Please try again.';
                }
            }
        }
    }
}

// Get user's banner submissions
$stmt = $pdo->prepare("SELECT * FROM banners WHERE user_id = ? ORDER BY created_at DESC LIMIT 10");
$stmt->execute([$_SESSION['user_id']]);
$myBanners = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Banner Service - <?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; padding-bottom: 80px; }
        .header { background: #0F2744; padding: 1rem; display: flex; justify-content: space-between; align-items: center; position: sticky; top: 0; z-index: 100; }
        .header-logo { display: flex; align-items: center; gap: 0.5rem; color: #F5A623; font-weight: 700; }
        .header-logo img { width: 48px; height: 48px; min-width: 48px; min-height: 48px; object-fit: contain; }
        .header-balance { background: #F5A623; color: #0A1628; padding: 0.5rem 1rem; border-radius: 20px; font-weight: 600; }
        .hamburger { background: none; border: none; color: #fff; font-size: 1.5rem; cursor: pointer; }
        .menu-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 200; display: none; }
        .menu-overlay.active { display: block; }
        .side-menu { position: fixed; top: 0; left: -280px; width: 280px; height: 100%; background: #0F2744; z-index: 300; transition: left 0.3s; padding: 1.5rem 0; overflow-y: auto; }
        .side-menu.active { left: 0; }
        .menu-header { display: flex; justify-content: space-between; align-items: center; padding: 0 1.5rem 1.5rem; border-bottom: 1px solid #1E3A5F; }
        .menu-close { background: none; border: none; color: #9CA3AF; font-size: 1.5rem; cursor: pointer; }
        .menu-items { padding: 1rem 0; }
        .menu-item { display: flex; align-items: center; gap: 1rem; padding: 1rem 1.5rem; color: #E5E7EB; text-decoration: none; }
        .menu-item:hover, .menu-item.active { background: #1E3A5F; color: #F5A623; }
        .menu-item i { width: 20px; text-align: center; }
        .menu-divider { height: 1px; background: #1E3A5F; margin: 0.5rem 1.5rem; }
        
        .content { padding: 1rem; max-width: 600px; margin: 0 auto; }
        .page-title { font-size: 1.25rem; margin-bottom: 1rem; display: flex; align-items: center; gap: 0.5rem; }
        .page-title i { color: #F5A623; }
        
        .alert { padding: 1rem; border-radius: 8px; margin-bottom: 1rem; }
        .alert-danger { background: rgba(239,68,68,0.2); color: #EF4444; border: 1px solid rgba(239,68,68,0.3); }
        .alert-success { background: rgba(16,185,129,0.2); color: #10B981; border: 1px solid rgba(16,185,129,0.3); }
        
        .card { background: #0F2744; border-radius: 12px; padding: 1.5rem; margin-bottom: 1rem; border: 1px solid #1E3A5F; }
        .card-title { font-size: 1rem; color: #F5A623; margin-bottom: 1rem; display: flex; align-items: center; gap: 0.5rem; }
        
        .pricing-box { text-align: center; padding: 1rem; background: rgba(245,166,35,0.1); border-radius: 8px; margin-bottom: 1rem; }
        .pricing-box .price { font-size: 2rem; color: #F5A623; font-weight: 700; }
        .pricing-box .duration { color: #9CA3AF; }
        .total-price { font-size: 1.5rem; color: #10B981; font-weight: 700; margin-top: 0.5rem; }
        
        .info-list { list-style: none; margin-bottom: 1rem; }
        .info-list li { padding: 0.5rem 0; color: #9CA3AF; display: flex; align-items: center; gap: 0.5rem; }
        .info-list li i { color: #F5A623; width: 16px; }
        
        .form-group { margin-bottom: 1rem; }
        .form-label { display: block; margin-bottom: 0.5rem; color: #E5E7EB; font-weight: 500; }
        .form-control { width: 100%; padding: 0.75rem; background: #1E3A5F; border: 1px solid #2D4A6F; border-radius: 8px; color: #fff; font-size: 16px; }
        .form-control:focus { outline: none; border-color: #F5A623; }
        .form-hint { font-size: 0.8rem; color: #9CA3AF; margin-top: 0.25rem; }
        
        .days-selector { display: flex; gap: 0.5rem; flex-wrap: wrap; margin-bottom: 0.5rem; }
        .day-btn { padding: 0.5rem 1rem; background: #1E3A5F; border: 1px solid #2D4A6F; border-radius: 8px; color: #fff; cursor: pointer; transition: all 0.2s; }
        .day-btn:hover { border-color: #F5A623; }
        .day-btn.active { background: #F5A623; color: #0A1628; border-color: #F5A623; }
        
        .file-upload { position: relative; border: 2px dashed #2D4A6F; border-radius: 8px; padding: 2rem; text-align: center; cursor: pointer; transition: all 0.2s; }
        .file-upload:hover { border-color: #F5A623; }
        .file-upload input { position: absolute; top: 0; left: 0; width: 100%; height: 100%; opacity: 0; cursor: pointer; }
        .file-upload i { font-size: 2rem; color: #F5A623; margin-bottom: 0.5rem; display: block; }
        .file-upload p { color: #9CA3AF; }
        .file-upload .selected { color: #10B981; margin-top: 0.5rem; }
        
        .preview-container { margin-top: 1rem; display: none; }
        .preview-container img { max-width: 100%; border-radius: 8px; border: 1px solid #2D4A6F; }
        
        .btn { display: block; width: 100%; padding: 1rem; border: none; border-radius: 8px; font-size: 1rem; font-weight: 600; cursor: pointer; transition: all 0.2s; }
        .btn-gold { background: #F5A623; color: #0A1628; }
        .btn-gold:hover { background: #FFD93D; }
        .btn-gold:disabled { background: #4B5563; color: #9CA3AF; cursor: not-allowed; }
        
        .section-title { font-size: 1rem; color: #F5A623; margin: 1.5rem 0 1rem; display: flex; align-items: center; gap: 0.5rem; }
        
        .banner-list { display: flex; flex-direction: column; gap: 0.75rem; }
        .banner-item { background: #0F2744; border-radius: 8px; padding: 1rem; display: flex; gap: 1rem; align-items: center; border: 1px solid #1E3A5F; }
        .banner-thumb { width: 80px; height: 40px; border-radius: 4px; object-fit: cover; background: #1E3A5F; }
        .banner-info { flex: 1; }
        .banner-date { font-size: 0.8rem; color: #9CA3AF; }
        .banner-details { font-size: 0.75rem; color: #6B7280; margin-top: 0.25rem; }
        .banner-status { padding: 0.25rem 0.5rem; border-radius: 20px; font-size: 0.7rem; 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; }
        .status-expired { background: rgba(107,114,128,0.2); color: #6B7280; }
        
        .empty { text-align: center; padding: 2rem; color: #9CA3AF; }
        .empty i { font-size: 2rem; color: #1E3A5F; margin-bottom: 0.5rem; display: block; }
        
        .bottom-nav { position: fixed; bottom: 0; left: 0; right: 0; background: #0F2744; display: flex; justify-content: space-around; padding: 0.75rem 0; border-top: 1px solid #1E3A5F; z-index: 100; }
        .bottom-nav a { display: flex; flex-direction: column; align-items: center; text-decoration: none; color: #9CA3AF; font-size: 0.7rem; gap: 0.25rem; }
        .bottom-nav a i { font-size: 1.25rem; }
        .bottom-nav a.active { color: #F5A623; }
    </style>
    <link rel="stylesheet" href="/assets/css/premium-dark.css">
</head>
<body>
    <header class="header">
        <button class="hamburger" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
        <div class="header-logo"><img src="/assets/images/logo.png" alt="<?php echo SITE_NAME; ?>"></div>
        <div class="header-balance"><?php echo formatCurrency($currentBalance); ?></div>
    </header>
    
    <div class="menu-overlay" id="menuOverlay" onclick="toggleMenu()"></div>
    <nav class="side-menu" id="sideMenu">
        <div class="menu-header">
            <div class="header-logo"><img src="/assets/images/logo.png" alt="<?php echo SITE_NAME; ?>"></div>
            <button class="menu-close" onclick="toggleMenu()"><i class="fas fa-times"></i></button>
        </div>
        <div class="menu-items">
            <a href="dashboard.php" class="menu-item"><i class="fas fa-home"></i> Dashboard</a>
            <a href="sms.php" class="menu-item"><i class="fas fa-sms"></i> SMS Service</a>
            <a href="smm.php" class="menu-item"><i class="fas fa-rocket"></i> SMM Service</a>
            <a href="banner.php" class="menu-item active"><i class="fas fa-ad"></i> Banner Service</a>
            <a href="orders.php" class="menu-item"><i class="fas fa-history"></i> Orders</a>
            <a href="add-funds.php" class="menu-item"><i class="fas fa-wallet"></i> Add Funds</a>
            <a href="transactions.php" class="menu-item"><i class="fas fa-exchange-alt"></i> Transactions</a>
            <a href="profile.php" class="menu-item"><i class="fas fa-user"></i> Profile</a>
            <div class="menu-divider"></div>
            <a href="<?php echo SITE_URL; ?>/logout.php" class="menu-item"><i class="fas fa-sign-out-alt"></i> Log Out</a>
        </div>
    </nav>
    
    <main class="content">
        <h1 class="page-title"><i class="fas fa-ad"></i> Banner Advertising</h1>
        
        <?php if ($error): ?><div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> <?php echo htmlspecialchars($error); ?></div><?php endif; ?>
        <?php if ($success): ?><div class="alert alert-success"><i class="fas fa-check-circle"></i> <?php echo htmlspecialchars($success); ?></div><?php endif; ?>
        
        <div class="card">
            <h3 class="card-title"><i class="fas fa-bullhorn"></i> Advertise Your Business</h3>
            
            <div class="pricing-box">
                <div class="price">$<?php echo number_format($bannerPrices[1], 2); ?></div>
                <div class="duration">per day</div>
                <div class="total-price" id="totalPrice">Total: $<?php echo number_format($bannerPrices[7], 2); ?></div>
            </div>
            
            <ul class="info-list">
                <li><i class="fas fa-check"></i> Banner displayed on dashboard</li>
                <li><i class="fas fa-check"></i> Maximum size: <?php echo $maxWidth; ?> x <?php echo $maxHeight; ?> pixels</li>
                <li><i class="fas fa-check"></i> Formats: JPG, PNG, GIF</li>
                <li><i class="fas fa-check"></i> Max file size: <?php echo $maxFileSize / 1024 / 1024; ?>MB</li>
                <li><i class="fas fa-check"></i> Review within 24 hours</li>
                <li><i class="fas fa-check"></i> Full refund if rejected</li>
            </ul>
            
            <form method="POST" enctype="multipart/form-data">
                <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
                
                <div class="form-group">
                    <label class="form-label">Duration (Days) *</label>
                    <div class="days-selector">
                        <button type="button" class="day-btn" data-days="1" data-price="<?php echo $bannerPrices[1]; ?>">1 Day</button>
                        <button type="button" class="day-btn active" data-days="7" data-price="<?php echo $bannerPrices[7]; ?>">7 Days</button>
                        <button type="button" class="day-btn" data-days="14" data-price="<?php echo $bannerPrices[14]; ?>">14 Days</button>
                        <button type="button" class="day-btn" data-days="30" data-price="<?php echo $bannerPrices[30]; ?>">30 Days</button>
                        <button type="button" class="day-btn" data-days="365" data-price="<?php echo $bannerPrices[365]; ?>">1 Year</button>
                    </div>
                    <input type="hidden" name="days" id="daysInput" value="7">
                </div>
                
                <div class="form-group">
                    <label class="form-label">Banner Image *</label>
                    <div class="file-upload" id="fileUpload">
                        <input type="file" name="banner_image" id="bannerImage" accept="image/jpeg,image/png,image/gif" required>
                        <i class="fas fa-cloud-upload-alt"></i>
                        <p>Click or drag to upload</p>
                        <p class="selected" id="fileName"></p>
                    </div>
                    <p class="form-hint">Recommended: <?php echo $maxWidth; ?>x<?php echo $maxHeight; ?> pixels</p>
                    <div class="preview-container" id="previewContainer">
                        <img id="imagePreview" src="" alt="Preview">
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Link URL (optional)</label>
                    <input type="url" name="link_url" class="form-control" placeholder="https://example.com">
                    <p class="form-hint">Where should users go when they click your banner?</p>
                </div>
                
                <button type="submit" class="btn btn-gold" id="submitBtn">
                    <i class="fas fa-paper-plane"></i> Submit Banner - <span id="btnPrice">$<?php echo number_format($bannerPrices[7], 2); ?></span>
                </button>
                
                <p id="insufficientMsg" style="text-align:center;color:#EF4444;margin-top:0.5rem;font-size:0.9rem;display:none;">
                    Insufficient balance. <a href="add-funds.php" style="color:#F5A623;">Add funds</a>
                </p>
            </form>
        </div>
        
        <h3 class="section-title"><i class="fas fa-history"></i> My Submissions</h3>
        
        <?php if (empty($myBanners)): ?>
        <div class="empty">
            <i class="fas fa-image"></i>
            <p>No banner submissions yet</p>
        </div>
        <?php else: ?>
        <div class="banner-list">
            <?php foreach ($myBanners as $banner): ?>
            <div class="banner-item">
                <img src="<?php echo UPLOADS_URL; ?>/banners/<?php echo htmlspecialchars($banner['image_path']); ?>" alt="Banner" class="banner-thumb">
                <div class="banner-info">
                    <div class="banner-date"><?php echo date('M d, Y', strtotime($banner['created_at'])); ?></div>
                    <div class="banner-details"><?php echo $banner['days'] == 365 ? '1 Year' : $banner['days'] . ' days'; ?> • $<?php echo number_format($banner['amount_paid'], 2); ?></div>
                    <?php if ($banner['status'] === 'rejected' && $banner['admin_note']): ?>
                    <div style="font-size:0.8rem;color:#EF4444;margin-top:0.25rem;"><?php echo htmlspecialchars($banner['admin_note']); ?></div>
                    <?php endif; ?>
                    <?php if ($banner['status'] === 'approved' && $banner['expires_at']): ?>
                    <div style="font-size:0.75rem;color:#10B981;margin-top:0.25rem;">Expires: <?php echo date('M d, Y', strtotime($banner['expires_at'])); ?></div>
                    <?php endif; ?>
                </div>
                <span class="banner-status status-<?php echo $banner['status']; ?>"><?php echo ucfirst($banner['status']); ?></span>
            </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </main>
    
    <nav class="bottom-nav">
        <a href="dashboard.php"><i class="fas fa-home"></i> Home</a>
        <a href="sms.php"><i class="fas fa-sms"></i> SMS</a>
        <a href="smm.php"><i class="fas fa-rocket"></i> SMM</a>
        <a href="orders.php"><i class="fas fa-history"></i> Orders</a>
        <a href="profile.php"><i class="fas fa-user"></i> Profile</a>
    </nav>
    
    <script>
        // Prices from database
        var bannerPrices = {
            1: <?php echo $bannerPrices[1]; ?>,
            7: <?php echo $bannerPrices[7]; ?>,
            14: <?php echo $bannerPrices[14]; ?>,
            30: <?php echo $bannerPrices[30]; ?>,
            365: <?php echo $bannerPrices[365]; ?>
        };
        var userBalance = <?php echo $currentBalance; ?>;
        
        function toggleMenu() { 
            document.getElementById('sideMenu').classList.toggle('active'); 
            document.getElementById('menuOverlay').classList.toggle('active'); 
        }
        
        // Days selector
        document.querySelectorAll('.day-btn').forEach(function(btn) {
            btn.addEventListener('click', function() {
                document.querySelectorAll('.day-btn').forEach(function(b) { b.classList.remove('active'); });
                this.classList.add('active');
                
                var days = parseInt(this.dataset.days);
                document.getElementById('daysInput').value = days;
                updatePrice(days);
            });
        });
        
        function updatePrice(days) {
            var total = bannerPrices[days];
            var formatted = '$' + total.toFixed(2);
            
            document.getElementById('totalPrice').textContent = 'Total: ' + formatted;
            document.getElementById('btnPrice').textContent = formatted;
            
            var submitBtn = document.getElementById('submitBtn');
            var insufficientMsg = document.getElementById('insufficientMsg');
            
            if (userBalance < total) {
                submitBtn.disabled = true;
                insufficientMsg.style.display = 'block';
            } else {
                submitBtn.disabled = false;
                insufficientMsg.style.display = 'none';
            }
        }
        
        // File upload preview
        document.getElementById('bannerImage').addEventListener('change', function() {
            var file = this.files[0];
            if (file) {
                document.getElementById('fileName').textContent = file.name;
                
                var reader = new FileReader();
                reader.onload = function(e) {
                    document.getElementById('imagePreview').src = e.target.result;
                    document.getElementById('previewContainer').style.display = 'block';
                };
                reader.readAsDataURL(file);
            } else {
                document.getElementById('fileName').textContent = '';
                document.getElementById('previewContainer').style.display = 'none';
            }
        });
        
        // Initialize price check
        updatePrice(7);
    </script>
</body>
</html>