<?php
// admin/banners.php - Banner/Advertisement Management
session_start();
require_once '../includes/config.php';

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

$message = '';
$msg_type = 'info';

// ==================== SAVE BANNER ====================
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save_banner'])) {
    $id = $_POST['id'] ?? null;
    $title = trim($_POST['title']);
    $subtitle = trim($_POST['subtitle'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $media_type = $_POST['media_type'] ?? 'image';
    $button_text = trim($_POST['button_text'] ?? '');
    $button_url = trim($_POST['button_url'] ?? '');
    $button_color = trim($_POST['button_color'] ?? '#ff4757');
    $second_button_text = trim($_POST['second_button_text'] ?? '');
    $second_button_url = trim($_POST['second_button_url'] ?? '');
    $second_button_color = trim($_POST['second_button_color'] ?? '#6C5CE7');
    $badge_text = trim($_POST['badge_text'] ?? '');
    $badge_color = trim($_POST['badge_color'] ?? '#ffc107');
    $position = $_POST['position'] ?? 'middle';
    $banner_style = $_POST['banner_style'] ?? 'gradient-purple';
    $order_number = (int)$_POST['order_number'];
    $start_date = $_POST['start_date'] ?? null;
    $end_date = $_POST['end_date'] ?? null;
    $is_active = isset($_POST['is_active']) ? 1 : 0;
    
    // Handle image upload
    $image_url = $_POST['existing_image'] ?? '';
    if(isset($_FILES['image_file']) && $_FILES['image_file']['error'] == 0) {
        $ext = strtolower(pathinfo($_FILES['image_file']['name'], PATHINFO_EXTENSION));
        if(in_array($ext, ['jpg','jpeg','png','gif','webp'])) {
            $upload_dir = '../uploads/banners/';
            if(!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
            $image_url = 'uploads/banners/' . time() . '_' . uniqid() . '.' . $ext;
            move_uploaded_file($_FILES['image_file']['tmp_name'], '../' . $image_url);
        }
    }
    
    $video_url = trim($_POST['video_url'] ?? '');
    
    if(empty($title)) {
        $message = 'টাইটেল প্রয়োজন';
        $msg_type = 'danger';
    } else {
        if($id) {
            $stmt = $pdo->prepare("UPDATE dashboard_banners SET title=?, subtitle=?, description=?, media_type=?, image_url=?, video_url=?, button_text=?, button_url=?, button_color=?, second_button_text=?, second_button_url=?, second_button_color=?, badge_text=?, badge_color=?, position=?, banner_style=?, order_number=?, start_date=?, end_date=?, is_active=? WHERE id=?");
            $stmt->execute([$title, $subtitle, $description, $media_type, $image_url, $video_url, $button_text, $button_url, $button_color, $second_button_text, $second_button_url, $second_button_color, $badge_text, $badge_color, $position, $banner_style, $order_number, $start_date, $end_date, $is_active, $id]);
        } else {
            $stmt = $pdo->prepare("INSERT INTO dashboard_banners (title, subtitle, description, media_type, image_url, video_url, button_text, button_url, button_color, second_button_text, second_button_url, second_button_color, badge_text, badge_color, position, banner_style, order_number, start_date, end_date, is_active) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
            $stmt->execute([$title, $subtitle, $description, $media_type, $image_url, $video_url, $button_text, $button_url, $button_color, $second_button_text, $second_button_url, $second_button_color, $badge_text, $badge_color, $position, $banner_style, $order_number, $start_date, $end_date, $is_active]);
        }
        $message = '✅ ব্যানার সংরক্ষিত হয়েছে!';
        $msg_type = 'success';
    }
}

// Delete
if(isset($_GET['delete'])) {
    $stmt = $pdo->prepare("SELECT image_url FROM dashboard_banners WHERE id = ?");
    $stmt->execute([$_GET['delete']]);
    $b = $stmt->fetch();
    if($b && !empty($b['image_url']) && file_exists('../' . $b['image_url'])) {
        unlink('../' . $b['image_url']);
    }
    $pdo->prepare("DELETE FROM dashboard_banners WHERE id = ?")->execute([$_GET['delete']]);
    header('Location: banners.php?msg=ব্যানার+ডিলিট+হয়েছে&type=success');
    exit;
}

$msg = $_GET['msg'] ?? $message;
$msg_type = $_GET['type'] ?? $msg_type;
$banners = $pdo->query("SELECT * FROM dashboard_banners ORDER BY order_number ASC")->fetchAll();

// Edit
$edit = null;
if(isset($_GET['edit'])) {
    $stmt = $pdo->prepare("SELECT * FROM dashboard_banners WHERE id = ?");
    $stmt->execute([$_GET['edit']]);
    $edit = $stmt->fetch();
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8"><title>ব্যানার ম্যানেজমেন্ট</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root { --primary: #6C5CE7; --gradient: linear-gradient(135deg, #667eea, #764ba2); --shadow: 0 3px 15px rgba(0,0,0,0.08); }
        body { background:#f0f2f8; font-family:'Segoe UI',Arial,sans-serif; }
        .navbar { background:white; padding:12px 0; box-shadow:0 2px 10px rgba(0,0,0,0.06); position:sticky; top:0; z-index:100; }
        .main-card { background:white; border-radius:15px; padding:25px; box-shadow:var(--shadow); margin-bottom:20px; }
        .banner-card { border:1px solid #eee; border-radius:12px; padding:15px; margin-bottom:10px; transition:0.3s; display:flex; gap:15px; align-items:center; }
        .banner-card:hover { box-shadow:var(--shadow); }
        .banner-preview { width:200px; height:100px; object-fit:cover; border-radius:8px; background:#f0f0f0; }
        .form-control,.form-select,textarea { border-radius:10px; padding:10px; border:2px solid #e0e0e0; width:100%; margin-bottom:8px; }
        .form-control:focus,.form-select:focus { border-color:var(--primary); outline:none; }
        .btn { border-radius:50px; padding:8px 20px; font-weight:600; cursor:pointer; border:none; }
        .btn-primary { background:var(--gradient); color:white; }
        .modal-header { background:var(--gradient); color:white; border-radius:15px 15px 0 0; }
        .modal-content { border-radius:15px; border:none; }
        .style-preview { width:100%; height:60px; border-radius:10px; display:flex; align-items:center; justify-content:center; color:white; font-weight:700; margin-top:5px; }
    </style>
</head>
<body>
<nav class="navbar"><div class="container"><div class="d-flex justify-content-between align-items-center">
    <a href="dashboard.php" class="text-decoration-none fw-bold" style="color:var(--primary);font-size:1.2rem;"><i class="fas fa-graduation-cap me-2"></i>অ্যাডমিন</a>
    <a href="../logout.php" class="btn btn-sm" style="background:#ff4757;color:white;">লগআউট</a>
</div></div></nav>

<div class="container py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h4><i class="fas fa-ad text-primary me-2"></i>ব্যানার / বিজ্ঞাপন ম্যানেজমেন্ট</h4>
        <button class="btn btn-primary" onclick="openModal()"><i class="fas fa-plus me-1"></i> নতুন ব্যানার</button>
    </div>
    
    <?php if($msg): ?><div class="alert alert-<?= $msg_type ?> rounded-3"><?= htmlspecialchars($msg) ?></div><?php endif; ?>
    
    <div class="main-card">
        <?php foreach($banners as $b): ?>
            <div class="banner-card">
                <?php if($b['image_url']): ?>
                    <img src="../<?= $b['image_url'] ?>" class="banner-preview" alt="">
                <?php else: ?>
                    <div class="banner-preview" style="background:<?= getBannerBg($b['banner_style']) ?>; display:flex; align-items:center; justify-content:center; color:white; font-weight:700;"><?= htmlspecialchars($b['title']) ?></div>
                <?php endif; ?>
                <div style="flex:1;">
                    <strong><?= htmlspecialchars($b['title']) ?></strong>
                    <br><small><?= htmlspecialchars($b['subtitle']) ?></small>
                    <br><span class="badge bg-info"><?= $b['media_type'] ?></span>
                    <span class="badge bg-secondary"><?= $b['position'] ?></span>
                    <span class="badge bg-<?= $b['is_active']?'success':'danger' ?>"><?= $b['is_active']?'সক্রিয়':'নিষ্ক্রিয়' ?></span>
                </div>
                <div class="d-flex gap-1">
                    <button class="btn btn-outline-primary btn-sm" onclick='editBanner(<?= json_encode($b) ?>)'><i class="fas fa-edit"></i></button>
                    <a href="?delete=<?= $b['id'] ?>" class="btn btn-outline-danger btn-sm" onclick="return confirm('ডিলিট?')"><i class="fas fa-trash"></i></a>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
</div>

<!-- Modal -->
<div class="modal fade" id="bannerModal" tabindex="-1">
    <div class="modal-dialog modal-lg"><div class="modal-content">
        <div class="modal-header"><h5 id="modalTitle"><i class="fas fa-ad me-2"></i>নতুন ব্যানার</h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
        <form method="POST" enctype="multipart/form-data">
            <input type="hidden" name="save_banner" value="1"><input type="hidden" name="id" id="bId">
            <input type="hidden" name="existing_image" id="existingImg">
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-6"><label>টাইটেল *</label><input type="text" name="title" id="title" class="form-control" required></div>
                    <div class="col-md-6"><label>সাব-টাইটেল</label><input type="text" name="subtitle" id="subtitle" class="form-control"></div>
                    <div class="col-12"><label>বিবরণ</label><textarea name="description" id="description" class="form-control" rows="2"></textarea></div>
                    <div class="col-md-4"><label>মিডিয়া টাইপ</label><select name="media_type" id="media_type" class="form-select" onchange="toggleMedia()"><option value="image">🖼️ ছবি</option><option value="video">🎬 ভিডিও</option><option value="both">🖼️+🎬 উভয়</option></select></div>
                    <div class="col-md-4"><label>পজিশন</label><select name="position" id="position" class="form-select"><option value="top">উপরে</option><option value="middle" selected>মাঝখানে</option><option value="bottom">নিচে</option></select></div>
                    <div class="col-md-4"><label>স্টাইল</label><select name="banner_style" id="banner_style" class="form-select" onchange="previewStyle()">
                        <option value="gradient-purple">🟣 পার্পল</option><option value="gradient-pink">🌸 পিঙ্ক</option><option value="gradient-blue">🔵 ব্লু</option><option value="gradient-green">🟢 গ্রীন</option><option value="gradient-orange">🟠 অরেঞ্জ</option><option value="dark">⬛ ডার্ক</option>
                    </select></div>
                    <div class="col-12" id="imageUpload"><label>ছবি আপলোড</label><input type="file" name="image_file" class="form-control" accept="image/*"></div>
                    <div class="col-12" id="videoUrl"><label>ভিডিও URL (YouTube)</label><input type="url" name="video_url" id="video_url" class="form-control" placeholder="https://youtube.com/watch?v=..."></div>
                    <div class="col-md-4"><label>ব্যাজ</label><input type="text" name="badge_text" id="badge_text" class="form-control" placeholder="অফার"></div>
                    <div class="col-md-2"><label>ব্যাজ রং</label><input type="color" name="badge_color" id="badge_color" class="form-control" value="#ffc107"></div>
                    <div class="col-md-3"><label>ক্রম</label><input type="number" name="order_number" id="order_number" class="form-control" value="1"></div>
                    <div class="col-md-3"><label>শুরু</label><input type="date" name="start_date" id="start_date" class="form-control"></div>
                    <div class="col-md-3"><label>শেষ</label><input type="date" name="end_date" id="end_date" class="form-control"></div>
                    <hr><h6>🔘 বাটন ১</h6>
                    <div class="col-md-4"><label>টেক্সট</label><input type="text" name="button_text" id="button_text" class="form-control" placeholder="কোর্স দেখুন"></div>
                    <div class="col-md-4"><label>URL</label><input type="text" name="button_url" id="button_url" class="form-control" placeholder="courses.php"></div>
                    <div class="col-md-4"><label>রং</label><input type="color" name="button_color" id="button_color" class="form-control" value="#ff4757"></div>
                    <hr><h6>🔘 বাটন ২ (ঐচ্ছিক)</h6>
                    <div class="col-md-4"><label>টেক্সট</label><input type="text" name="second_button_text" id="sbtn_text" class="form-control"></div>
                    <div class="col-md-4"><label>URL</label><input type="text" name="second_button_url" id="sbtn_url" class="form-control"></div>
                    <div class="col-md-4"><label>রং</label><input type="color" name="second_button_color" id="sbtn_color" class="form-control" value="#6C5CE7"></div>
                    <div class="col-12 mt-2"><div class="form-check"><input type="checkbox" name="is_active" id="is_active" class="form-check-input" checked><label>সক্রিয়</label></div></div>
                </div>
                <div class="style-preview" id="stylePreview">ব্যানার প্রিভিউ</div>
            </div>
            <div class="modal-footer"><button type="button" class="btn btn-secondary rounded-pill" data-bs-dismiss="modal">বাতিল</button><button type="submit" class="btn btn-primary rounded-pill"><i class="fas fa-save me-1"></i> সংরক্ষণ</button></div>
        </form>
    </div></div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
let modal; document.addEventListener('DOMContentLoaded',()=>modal=new bootstrap.Modal(document.getElementById('bannerModal')));

const styles={'gradient-purple':'linear-gradient(135deg,#667eea,#764ba2)','gradient-pink':'linear-gradient(135deg,#f093fb,#f5576c)','gradient-blue':'linear-gradient(135deg,#4facfe,#00f2fe)','gradient-green':'linear-gradient(135deg,#43e97b,#38f9d7)','gradient-orange':'linear-gradient(135deg,#fa709a,#fee140)','dark':'#1a1a2e'};

function getStyle(s){return styles[s]||styles['gradient-purple'];}

function previewStyle(){document.getElementById('stylePreview').style.background=getStyle(document.getElementById('banner_style').value);}

function toggleMedia(){
    const t=document.getElementById('media_type').value;
    document.getElementById('imageUpload').style.display=(t==='video'?'none':'block');
    document.getElementById('videoUrl').style.display=(t==='image'?'none':'block');
}

function openModal(){
    document.getElementById('modalTitle').innerHTML='<i class="fas fa-ad me-2"></i>নতুন ব্যানার';
    document.querySelector('#bannerModal form').reset();
    document.getElementById('bId').value=''; document.getElementById('existingImg').value='';
    toggleMedia(); previewStyle(); modal.show();
}

function editBanner(d){
    document.getElementById('modalTitle').innerHTML='<i class="fas fa-edit me-2"></i>এডিট ব্যানার';
    document.getElementById('bId').value=d.id; document.getElementById('title').value=d.title||'';
    document.getElementById('subtitle').value=d.subtitle||''; document.getElementById('description').value=d.description||'';
    document.getElementById('media_type').value=d.media_type||'image'; document.getElementById('position').value=d.position||'middle';
    document.getElementById('banner_style').value=d.banner_style||'gradient-purple'; document.getElementById('video_url').value=d.video_url||'';
    document.getElementById('badge_text').value=d.badge_text||''; document.getElementById('badge_color').value=d.badge_color||'#ffc107';
    document.getElementById('order_number').value=d.order_number||1; document.getElementById('start_date').value=d.start_date||'';
    document.getElementById('end_date').value=d.end_date||''; document.getElementById('existingImg').value=d.image_url||'';
    document.getElementById('button_text').value=d.button_text||''; document.getElementById('button_url').value=d.button_url||'';
    document.getElementById('button_color').value=d.button_color||'#ff4757'; document.getElementById('sbtn_text').value=d.second_button_text||'';
    document.getElementById('sbtn_url').value=d.second_button_url||''; document.getElementById('sbtn_color').value=d.second_button_color||'#6C5CE7';
    document.getElementById('is_active').checked=d.is_active==1;
    toggleMedia(); previewStyle(); modal.show();
}
</script>
</body>
</html>