<?php
// admin/add-course.php - Add New Course
session_start();
require_once '../includes/config.php';

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

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

// Handle form submission
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_course'])) {
    $category_id = $_POST['category_id'] ?? 0;
    $title_bn = trim($_POST['title_bn'] ?? '');
    $title_en = trim($_POST['title_en'] ?? '');
    $description_bn = $_POST['description_bn'] ?? '';
    $description_en = $_POST['description_en'] ?? '';
    $price = $_POST['price'] ?? 0;
    $duration = $_POST['duration'] ?? '';
    $level = $_POST['level'] ?? 'beginner';
    $status = $_POST['status'] ?? 'published';
    
    // Create unique slug using config.php function
    $base_slug = createSlug($title_en);
    if(empty($base_slug)) {
        $base_slug = createSlug($title_bn);
    }
    if(empty($base_slug)) {
        $base_slug = 'course-' . time();
    }
    
    // Make slug unique
    $slug = $base_slug;
    $counter = 1;
    while(true) {
        $stmt = $pdo->prepare("SELECT id FROM courses WHERE slug = ?");
        $stmt->execute([$slug]);
        if(!$stmt->fetch()) {
            break;
        }
        $slug = $base_slug . '-' . $counter;
        $counter++;
    }
    
    // Handle thumbnail upload
    $thumbnail = '';
    if(isset($_FILES['thumbnail']) && $_FILES['thumbnail']['error'] == 0) {
        $allowed = ['jpg', 'jpeg', 'png', 'webp'];
        $ext = strtolower(pathinfo($_FILES['thumbnail']['name'], PATHINFO_EXTENSION));
        
        if(in_array($ext, $allowed)) {
            if(!is_dir('../uploads/courses')) {
                mkdir('../uploads/courses', 0755, true);
            }
            $thumbnail = time() . '_' . uniqid() . '.' . $ext;
            move_uploaded_file($_FILES['thumbnail']['tmp_name'], '../uploads/courses/' . $thumbnail);
        }
    }
    
    if(empty($title_bn) || empty($title_en) || $category_id == 0) {
        $error = 'অনুগ্রহ করে প্রয়োজনীয় তথ্য পূরণ করুন';
    } else {
        try {
            $stmt = $pdo->prepare("
                INSERT INTO courses (category_id, instructor_id, title_bn, title_en, slug, description_bn, description_en, thumbnail, price, duration, level, status) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                $category_id,
                $_SESSION['user_id'],
                $title_bn,
                $title_en,
                $slug,
                $description_bn,
                $description_en,
                $thumbnail,
                $price,
                $duration,
                $level,
                $status
            ]);
            
            $course_id = $pdo->lastInsertId();
            
            // Redirect to add lessons
            header("Location: add-lesson.php?course_id=$course_id&success=1");
            exit;
            
        } catch(PDOException $e) {
            $error = 'কোর্স তৈরি করতে ব্যর্থ: ' . $e->getMessage();
        }
    }
}

// Get categories
$categories = $pdo->query("SELECT * FROM categories ORDER BY name_bn")->fetchAll();

// Get instructors
$instructors = $pdo->query("SELECT id, full_name FROM users WHERE role = 'instructor'")->fetchAll();

// ⚠️ createSlug() function REMOVED - It's already defined in includes/config.php
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <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); }
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { background: #f5f6fa; font-family: 'Segoe UI', 'Hind Siliguri', Arial, sans-serif; min-height: 100vh; }
        
        .navbar { background: white; box-shadow: 0 2px 15px rgba(0,0,0,0.08); padding: 15px 0; position: sticky; top: 0; z-index: 100; }
        .navbar-brand { font-weight: 700; color: var(--primary) !important; text-decoration: none; font-size: 1.3rem; }
        
        .main-card { background: white; border-radius: 20px; padding: 30px; box-shadow: 0 5px 25px rgba(0,0,0,0.08); }
        
        .section-card { background: #f8f9ff; border-radius: 15px; padding: 25px; margin-bottom: 25px; border: 1px solid #e8e8ff; }
        .section-title { font-size: 1.1rem; font-weight: 700; margin-bottom: 20px; color: #333; }
        .section-title i { color: var(--primary); margin-right: 8px; }
        
        .form-label { font-weight: 600; margin-bottom: 6px; font-size: 0.9rem; color: #444; }
        .form-control, .form-select { 
            border-radius: 12px; padding: 12px 16px; 
            border: 2px solid #e8e8e8; font-size: 0.95rem;
            transition: all 0.3s ease; width: 100%;
        }
        .form-control:focus, .form-select:focus { 
            border-color: var(--primary); 
            box-shadow: 0 0 0 4px rgba(108,92,231,0.08); 
            outline: none; 
        }
        
        .btn-primary { 
            background: var(--gradient); border: none; 
            border-radius: 50px; padding: 12px 30px; 
            font-weight: 600; font-size: 1rem; color: white;
            transition: all 0.3s ease; cursor: pointer; text-decoration: none; display: inline-block;
        }
        .btn-primary:hover { transform: translateY(-2px); box-shadow: 0 8px 25px rgba(108,92,231,0.35); }
        .btn-outline-secondary { 
            border-radius: 50px; padding: 12px 30px; 
            border: 2px solid #6c757d; color: #6c757d; 
            text-decoration: none; display: inline-block; font-weight: 600;
        }
        .btn-sm { padding: 6px 15px; font-size: 0.85rem; }
        .rounded-pill { border-radius: 50px !important; }
        
        .thumbnail-preview { 
            max-width: 250px; border-radius: 12px; 
            margin-top: 12px; display: none;
            border: 3px solid #e0e0e0;
        }
        
        .alert { border-radius: 12px; padding: 15px 20px; margin-bottom: 20px; }
        .alert-danger { background: #ffeaea; color: #c33; border: 1px solid #fcc; }
        .alert-success { background: #eaffea; color: #3a3; border: 1px solid #cfc; }
        
        .slug-display {
            background: #f0f0f0; padding: 8px 12px; 
            border-radius: 8px; font-size: 0.85rem; 
            color: #666; margin-top: 5px;
        }
        
        .badge { padding: 5px 12px; border-radius: 50px; font-size: 0.8rem; }
        .bg-primary { background: var(--primary) !important; color: white; }
        
        textarea.form-control { resize: vertical; }
        
        @media (max-width: 768px) {
            .main-card { padding: 20px; }
            .btn-lg { width: 100%; margin-bottom: 10px; }
        }
    </style>
</head>
<body>

<nav class="navbar">
    <div class="container">
        <div class="d-flex justify-content-between align-items-center">
            <div>
                <a href="../dashboard.php" class="navbar-brand">
                    <i class="fas fa-graduation-cap me-2"></i>বাংলা LMS
                </a>
                <span class="badge bg-primary ms-2">অ্যাডমিন</span>
            </div>
            <div class="d-flex gap-2">
                <a href="../dashboard.php" class="btn btn-outline-secondary btn-sm rounded-pill">
                    <i class="fas fa-tachometer-alt me-1"></i> ড্যাশবোর্ড
                </a>
                <a href="courses.php" class="btn btn-outline-secondary btn-sm rounded-pill">
                    <i class="fas fa-list me-1"></i> সব কোর্স
                </a>
                <a href="../logout.php" class="btn btn-outline-secondary btn-sm rounded-pill" style="border-color:#dc3545;color:#dc3545;">
                    <i class="fas fa-sign-out-alt me-1"></i> লগআউট
                </a>
            </div>
        </div>
    </div>
</nav>

<div class="container py-4">
    <div class="row justify-content-center">
        <div class="col-lg-10">
            
            <!-- Page Title -->
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h3><i class="fas fa-plus-circle text-primary me-2"></i>নতুন কোর্স তৈরি করুন</h3>
                <a href="courses.php" class="btn btn-outline-secondary rounded-pill">
                    <i class="fas fa-arrow-left me-2"></i>ফিরে যান
                </a>
            </div>
            
            <!-- Alerts -->
            <?php if($error): ?>
                <div class="alert alert-danger alert-dismissible fade show">
                    <i class="fas fa-exclamation-triangle me-2"></i><?= htmlspecialchars($error) ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            
            <?php if($success): ?>
                <div class="alert alert-success alert-dismissible fade show">
                    <i class="fas fa-check-circle me-2"></i><?= htmlspecialchars($success) ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            
            <form method="POST" enctype="multipart/form-data" id="courseForm">
                <input type="hidden" name="add_course" value="1">
                
                <div class="row g-4">
                    <!-- Left Column -->
                    <div class="col-lg-8">
                        <div class="main-card">
                            <div class="section-card">
                                <div class="section-title"><i class="fas fa-info-circle"></i>মৌলিক তথ্য</div>
                                
                                <div class="mb-3">
                                    <label class="form-label">কোর্সের নাম (বাংলা) <span class="text-danger">*</span></label>
                                    <input type="text" name="title_bn" class="form-control" 
                                           placeholder="যেমন: সম্পূর্ণ ওয়েব ডেভেলপমেন্ট কোর্স" required>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">Course Name (English) <span class="text-danger">*</span></label>
                                    <input type="text" name="title_en" class="form-control" 
                                           placeholder="e.g., Complete Web Development Course" required
                                           oninput="updateSlugPreview()" id="titleEnInput">
                                    <div class="slug-display">
                                        স্লাগ: <span id="slugText">course-slug</span>
                                    </div>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">বিবরণ (বাংলা)</label>
                                    <textarea name="description_bn" class="form-control" rows="5" 
                                              placeholder="কোর্স সম্পর্কে বিস্তারিত লিখুন..."></textarea>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">Description (English)</label>
                                    <textarea name="description_en" class="form-control" rows="3" 
                                              placeholder="Write course description in English..."></textarea>
                                </div>
                            </div>
                            
                            <div class="section-card">
                                <div class="section-title"><i class="fas fa-video"></i>কন্টেন্ট তথ্য</div>
                                <p class="text-muted small">
                                    <i class="fas fa-info-circle me-1"></i>
                                    কোর্স তৈরি করার পর আলাদাভাবে লেসন ও কুইজ যোগ করতে পারবেন।
                                </p>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Right Column -->
                    <div class="col-lg-4">
                        <div class="main-card">
                            <div class="section-card">
                                <div class="section-title"><i class="fas fa-cog"></i>সেটিংস</div>
                                
                                <div class="mb-3">
                                    <label class="form-label">ক্যাটাগরি <span class="text-danger">*</span></label>
                                    <select name="category_id" class="form-select" required>
                                        <option value="">-- সিলেক্ট করুন --</option>
                                        <?php foreach($categories as $cat): ?>
                                            <option value="<?= $cat['id'] ?>">
                                                <?= htmlspecialchars($cat['name_bn']) ?> (<?= htmlspecialchars($cat['name_en']) ?>)
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">লেভেল</label>
                                    <select name="level" class="form-select">
                                        <option value="beginner">🟢 বিগিনার</option>
                                        <option value="intermediate">🟡 ইন্টারমিডিয়েট</option>
                                        <option value="advanced">🔴 অ্যাডভান্সড</option>
                                    </select>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">মূল্য (টাকা)</label>
                                    <input type="number" name="price" class="form-control" value="0" placeholder="০ = ফ্রি কোর্স">
                                    <small class="text-muted">০ রাখলে ফ্রি কোর্স হিসেবে দেখাবে</small>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">সময়কাল</label>
                                    <input type="text" name="duration" class="form-control" placeholder="যেমন: ৩ মাস, ৪০ ঘন্টা">
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">স্ট্যাটাস</label>
                                    <select name="status" class="form-select">
                                        <option value="published">✅ পাবলিশড</option>
                                        <option value="draft">📝 ড্রাফট</option>
                                    </select>
                                </div>
                            </div>
                            
                            <div class="section-card">
                                <div class="section-title"><i class="fas fa-image"></i>থাম্বনেইল</div>
                                <input type="file" name="thumbnail" class="form-control" accept="image/*" onchange="previewImage(this)">
                                <small class="text-muted">রিকমেন্ডেড: 1280×720 পিক্সেল</small>
                                <img id="thumbnailPreview" class="thumbnail-preview img-fluid" alt="প্রিভিউ">
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="text-center mt-4">
                    <button type="submit" class="btn btn-primary btn-lg px-5">
                        <i class="fas fa-save me-2"></i>কোর্স তৈরি করুন
                    </button>
                    <a href="courses.php" class="btn btn-outline-secondary btn-lg px-5 ms-2">বাতিল</a>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function previewImage(input) {
    const preview = document.getElementById('thumbnailPreview');
    if(input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = function(e) {
            preview.src = e.target.result;
            preview.style.display = 'block';
        }
        reader.readAsDataURL(input.files[0]);
    }
}

function updateSlugPreview() {
    const title = document.getElementById('titleEnInput').value;
    let slug = title.toLowerCase()
        .replace(/[^a-z0-9\s-]/g, '')
        .trim()
        .replace(/[\s_]+/g, '-')
        .replace(/-+/g, '-')
        .replace(/^-+|-+$/g, '');
    document.getElementById('slugText').textContent = slug || 'course-slug';
}
</script>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>