<?php
// admin/packages.php - Dynamic Package 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';
$edit = null;

// ==================== SAVE PACKAGE ====================
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save_package'])) {
    $id = $_POST['id'] ?? null;
    $name_bn = trim($_POST['name_bn']);
    $name_en = trim($_POST['name_en']);
    $price = (float)$_POST['price'];
    $duration = (int)$_POST['duration_months'];
    $package_type = $_POST['package_type'];
    $category_id = $_POST['category_id'] ?? null;
    $description_bn = trim($_POST['description_bn'] ?? '');
    $features = trim($_POST['features'] ?? '');
    $is_popular = isset($_POST['is_popular']) ? 1 : 0;
    $is_active = isset($_POST['is_active']) ? 1 : 0;
    $badge_text = trim($_POST['badge_text'] ?? '');
    $badge_color = trim($_POST['badge_color'] ?? '#ff4757');
    $individual_courses = $_POST['individual_courses'] ?? [];
    
    if(empty($name_bn) || $price < 0) {
        $message = 'নাম ও মূল্য প্রয়োজন';
        $msg_type = 'danger';
    } else {
        try {
            if($id) {
                $stmt = $pdo->prepare("UPDATE packages SET name_bn=?, name_en=?, price=?, duration_months=?, package_type=?, category_id=?, description_bn=?, features=?, is_popular=?, is_active=?, badge_text=?, badge_color=? WHERE id=?");
                $stmt->execute([$name_bn, $name_en, $price, $duration, $package_type, $category_id, $description_bn, $features, $is_popular, $is_active, $badge_text, $badge_color, $id]);
            } else {
                $stmt = $pdo->prepare("INSERT INTO packages (name_bn, name_en, price, duration_months, package_type, category_id, description_bn, features, is_popular, is_active, badge_text, badge_color) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)");
                $stmt->execute([$name_bn, $name_en, $price, $duration, $package_type, $category_id, $description_bn, $features, $is_popular, $is_active, $badge_text, $badge_color]);
                $id = $pdo->lastInsertId();
            }
            
            // Handle individual courses
            if($package_type == 'individual') {
                $pdo->prepare("DELETE FROM package_individual_courses WHERE package_id = ?")->execute([$id]);
                if(!empty($individual_courses)) {
                    $stmt = $pdo->prepare("INSERT INTO package_individual_courses (package_id, course_id) VALUES (?,?)");
                    foreach($individual_courses as $cid) {
                        $stmt->execute([$id, $cid]);
                    }
                }
            }
            
            $message = '✅ প্যাকেজ সংরক্ষিত হয়েছে!';
            $msg_type = 'success';
        } catch(PDOException $e) {
            $message = 'ত্রুটি: ' . $e->getMessage();
            $msg_type = 'danger';
        }
    }
}

// ==================== DELETE ====================
if(isset($_GET['delete'])) {
    $pdo->prepare("DELETE FROM package_individual_courses WHERE package_id = ?")->execute([$_GET['delete']]);
    $pdo->prepare("DELETE FROM packages WHERE id = ?")->execute([$_GET['delete']]);
    header('Location: packages.php?msg=প্যাকেজ+ডিলিট+হয়েছে&type=success');
    exit;
}

// ==================== EDIT ====================
if(isset($_GET['edit'])) {
    $stmt = $pdo->prepare("SELECT * FROM packages WHERE id = ?");
    $stmt->execute([$_GET['edit']]);
    $edit = $stmt->fetch();
    
    if($edit && $edit['package_type'] == 'individual') {
        $stmt = $pdo->prepare("SELECT course_id FROM package_individual_courses WHERE package_id = ?");
        $stmt->execute([$edit['id']]);
        $edit['individual_courses'] = $stmt->fetchAll(PDO::FETCH_COLUMN);
    }
}

$msg = $_GET['msg'] ?? $message;
$msg_type = $_GET['type'] ?? $msg_type;

$packages = $pdo->query("SELECT p.*, c.name_bn as category_name FROM packages p LEFT JOIN categories c ON p.category_id = c.id ORDER BY p.price ASC")->fetchAll();
$categories = $pdo->query("SELECT * FROM categories ORDER BY name_bn")->fetchAll();
$courses = $pdo->query("SELECT id, title_bn, category_id FROM courses WHERE status='published' ORDER BY title_bn")->fetchAll();
?>
<!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); }
        * { margin:0; padding:0; box-sizing:border-box; }
        body { background:#f0f2f8; font-family:'Segoe UI','Hind Siliguri',Arial,sans-serif; }
        .navbar { background:white; box-shadow:0 2px 10px rgba(0,0,0,0.06); padding:12px 0; position:sticky; top:0; z-index:100; }
        .main-card { background:white; border-radius:15px; padding:25px; box-shadow:var(--shadow); margin-bottom:20px; }
        .package-card { border:1px solid #eee; border-radius:12px; padding:18px; margin-bottom:12px; transition:0.3s; }
        .package-card:hover { box-shadow:var(--shadow); border-color:var(--primary); }
        .package-card.popular { border-left:4px solid #ff4757; }
        .type-badge { padding:4px 10px; border-radius:20px; font-size:0.7rem; font-weight:600; display:inline-block; }
        .type-all { background:#e8f0fe; color:#1967d2; }
        .type-category { background:#fff3e0; color:#e67e22; }
        .type-individual { background:#d4f5e9; color:#11998e; }
        .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; transition:0.3s; border:none; }
        .btn-primary { background:var(--gradient); color:white; }
        .btn-primary:hover { transform:translateY(-2px); box-shadow:0 8px 20px rgba(108,92,231,0.3); }
        .btn-sm { padding:5px 12px; font-size:0.8rem; }
        .modal-header { background:var(--gradient); color:white; border-radius:15px 15px 0 0; }
        .modal-content { border-radius:15px; border:none; }
        .course-check-list { max-height:200px; overflow-y:auto; border:2px solid #e0e0e0; border-radius:10px; padding:10px; }
        .course-check-list label { display:block; padding:5px; cursor:pointer; border-radius:5px; }
        .course-check-list label:hover { background:#f0f0f0; }
    </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-box text-primary me-2"></i>প্যাকেজ ম্যানেজমেন্ট</h4>
        <button class="btn btn-primary" onclick="openAddModal()"><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($packages as $pkg): ?>
            <div class="package-card <?= $pkg['is_popular']?'popular':'' ?> d-flex justify-content-between align-items-center flex-wrap">
                <div>
                    <div class="d-flex gap-2 align-items-center mb-1">
                        <strong><?= htmlspecialchars($pkg['name_bn']) ?></strong>
                        <?php if($pkg['is_popular']): ?><span class="badge bg-danger">জনপ্রিয়</span><?php endif; ?>
                        <?php if($pkg['badge_text']): ?><span class="badge" style="background:<?= $pkg['badge_color'] ?>"><?= $pkg['badge_text'] ?></span><?php endif; ?>
                    </div>
                    <small class="text-muted"><?= htmlspecialchars($pkg['name_en']) ?> | ৳<?= number_format($pkg['price']) ?> | <?= $pkg['duration_months'] ?> মাস</small>
                    <br>
                    <span class="type-badge type-<?= $pkg['package_type'] ?>">
                        <?= $pkg['package_type']=='all'?'🌐 সকল কোর্স':($pkg['package_type']=='category'?'📂 '.($pkg['category_name']??'ক্যাটাগরি'):'📚 নির্দিষ্ট কোর্স') ?>
                    </span>
                    <span class="badge bg-<?= $pkg['is_active']?'success':'secondary' ?> ms-1"><?= $pkg['is_active']?'✅ সক্রিয়':'❌ নিষ্ক্রিয়' ?></span>
                </div>
                <div class="d-flex gap-1 mt-2 mt-md-0">
                    <button class="btn btn-outline-primary btn-sm" onclick='editPackage(<?= json_encode($pkg) ?>)'><i class="fas fa-edit"></i></button>
                    <a href="?delete=<?= $pkg['id'] ?>" class="btn btn-outline-danger btn-sm" onclick="return confirm('ডিলিট করবেন?')"><i class="fas fa-trash"></i></a>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
</div>

<!-- Add/Edit Modal -->
<div class="modal fade" id="packageModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header"><h5 class="modal-title" id="modalTitle"><i class="fas fa-box me-2"></i>নতুন প্যাকেজ</h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
            <form method="POST" id="packageForm">
                <input type="hidden" name="save_package" value="1"><input type="hidden" name="id" id="pkgId">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6"><label>নাম (বাংলা) *</label><input type="text" name="name_bn" id="name_bn" class="form-control" required></div>
                        <div class="col-md-6"><label>Name (English) *</label><input type="text" name="name_en" id="name_en" class="form-control" required></div>
                        <div class="col-md-4"><label>মূল্য (৳) *</label><input type="number" name="price" id="price" class="form-control" required></div>
                        <div class="col-md-4"><label>সময়কাল (মাস)</label><input type="number" name="duration_months" id="duration_months" class="form-control" value="1"></div>
                        <div class="col-md-4"><label>প্যাকেজ টাইপ *</label><select name="package_type" id="package_type" class="form-select" onchange="togglePackageType()"><option value="all">🌐 সকল কোর্স</option><option value="category">📂 ক্যাটাগরি অনুযায়ী</option><option value="individual">📚 নির্দিষ্ট কোর্স</option></select></div>
                        <div class="col-md-6" id="categorySelect" style="display:none;"><label>ক্যাটাগরি</label><select name="category_id" class="form-select"><?php foreach($categories as $c): ?><option value="<?=$c['id']?>"><?=htmlspecialchars($c['name_bn'])?></option><?php endforeach; ?></select></div>
                        <div class="col-12" id="courseSelect" style="display:none;"><label>কোর্স সিলেক্ট করুন</label><div class="course-check-list"><?php foreach($courses as $c): ?><label><input type="checkbox" name="individual_courses[]" value="<?=$c['id']?>"> <?=htmlspecialchars($c['title_bn'])?></label><?php endforeach; ?></div></div>
                        <div class="col-12"><label>বিবরণ</label><textarea name="description_bn" id="description_bn" class="form-control" rows="2"></textarea></div>
                        <div class="col-12"><label>ফিচারসমূহ (কমা দিয়ে আলাদা করুন)</label><textarea name="features" id="features" class="form-control" rows="2" placeholder="ফিচার ১, ফিচার ২, ফিচার ৩"></textarea></div>
                        <div class="col-md-6"><label>ব্যাজ টেক্সট</label><input type="text" name="badge_text" id="badge_text" class="form-control" placeholder="যেমন: ২০% ছাড়"></div>
                        <div class="col-md-3"><label>ব্যাজ কালার</label><input type="color" name="badge_color" id="badge_color" class="form-control" value="#ff4757"></div>
                        <div class="col-md-3 d-flex align-items-end gap-3">
                            <div class="form-check"><input type="checkbox" name="is_popular" id="is_popular" class="form-check-input"><label>জনপ্রিয়</label></div>
                            <div class="form-check"><input type="checkbox" name="is_active" id="is_active" class="form-check-input" checked><label>সক্রিয়</label></div>
                        </div>
                    </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 pkgModal;
document.addEventListener('DOMContentLoaded', () => pkgModal = new bootstrap.Modal(document.getElementById('packageModal')));

function openAddModal(){
    document.getElementById('modalTitle').innerHTML='<i class="fas fa-box me-2"></i>নতুন প্যাকেজ';
    document.getElementById('packageForm').reset();
    document.getElementById('pkgId').value='';
    document.getElementById('package_type').value='all';
    togglePackageType();
    pkgModal.show();
}

function editPackage(data){
    document.getElementById('modalTitle').innerHTML='<i class="fas fa-edit me-2"></i>প্যাকেজ এডিট';
    document.getElementById('pkgId').value=data.id;
    document.getElementById('name_bn').value=data.name_bn||'';
    document.getElementById('name_en').value=data.name_en||'';
    document.getElementById('price').value=data.price||0;
    document.getElementById('duration_months').value=data.duration_months||1;
    document.getElementById('package_type').value=data.package_type||'all';
    document.getElementById('description_bn').value=data.description_bn||'';
    document.getElementById('features').value=data.features||'';
    document.getElementById('badge_text').value=data.badge_text||'';
    document.getElementById('badge_color').value=data.badge_color||'#ff4757';
    document.getElementById('is_popular').checked=data.is_popular==1;
    document.getElementById('is_active').checked=data.is_active==1;
    
    if(data.package_type=='category') document.querySelector('select[name=category_id]').value=data.category_id||'';
    
    // Individual courses
    document.querySelectorAll('input[name="individual_courses[]"]').forEach(cb=>cb.checked=false);
    if(data.individual_courses) data.individual_courses.forEach(cid=>{
        let cb=document.querySelector(`input[name="individual_courses[]"][value="${cid}"]`);
        if(cb) cb.checked=true;
    });
    
    togglePackageType();
    pkgModal.show();
}

function togglePackageType(){
    const type=document.getElementById('package_type').value;
    document.getElementById('categorySelect').style.display=type==='category'?'block':'none';
    document.getElementById('courseSelect').style.display=type==='individual'?'block':'none';
}
</script>
</body>
</html>