<?php 
ini_set('display_errors', 1); error_reporting(E_ALL);
require_once '../db_connect.php'; 

$id = $_GET['id'] ?? null;
if (!$id) { echo "<script>window.location.href='manage_courses.php';</script>"; exit; }

// বর্তমান কোর্সের তথ্য সংগ্রহ করা
$stmt = $pdo->prepare("SELECT * FROM courses WHERE id = ?");
$stmt->execute([$id]);
$course = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$course) { die("<div class='container py-5'><div class='alert alert-danger shadow-sm fw-bold text-center border-0'>Sorry! Course not found.</div></div>"); }

$error = "";

// ডাটাবেস থেকে সব অ্যাক্টিভ টিচারদের লিস্ট নিয়ে আসা
try {
    $teachers_stmt = $pdo->query("SELECT id, name FROM teachers WHERE status = 'active' ORDER BY name ASC");
    $teachers_list = $teachers_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $teachers_list = [];
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $title = trim($_POST['title']);
    $teacher_id = !empty($_POST['teacher_id']) ? $_POST['teacher_id'] : null; // টিচার আইডি ফিল্ড
    $duration = trim($_POST['duration']);
    $fee = trim($_POST['fee']) ?: 0;
    $description = trim($_POST['description']);
    $status = $_POST['status'];
    
    $language = trim($_POST['language']) ?: 'English, Bengali';
    $platform = trim($_POST['platform']) ?: 'Zoom, Google Meet';
    $level = trim($_POST['level']) ?: 'Beginner to Advanced';
    $assessment = trim($_POST['assessment']) ?: 'Quizzes & Assignments';
    $has_certificate = $_POST['has_certificate'] ?? 'Yes';

    $image_url = $course['image_url'];
    if (isset($_FILES['course_image']) && $_FILES['course_image']['error'] == 0) {
        $allowed_ext = ['jpg', 'jpeg', 'png', 'webp'];
        $file_ext = strtolower(pathinfo($_FILES['course_image']['name'], PATHINFO_EXTENSION));
        if (in_array($file_ext, $allowed_ext)) {
            $upload_dir = '../uploads/';
            if (!is_dir($upload_dir)) { mkdir($upload_dir, 0777, true); }
            $new_name = 'course_' . time() . '_' . rand(100, 999) . '.' . $file_ext;
            if (move_uploaded_file($_FILES['course_image']['tmp_name'], $upload_dir . $new_name)) {
                $image_url = 'uploads/' . $new_name;
            }
        }
    }

    try {
        // UPDATE কুয়েরিতে teacher_id যোগ করা হয়েছে
        $update = $pdo->prepare("UPDATE courses SET teacher_id=?, title=?, duration=?, fee=?, description=?, status=?, image_url=?, language=?, platform=?, level=?, assessment=?, has_certificate=? WHERE id=?");
        if ($update->execute([$teacher_id, $title, $duration, $fee, $description, $status, $image_url, $language, $platform, $level, $assessment, $has_certificate, $id])) {
            echo "<script>window.location.href='manage_courses.php?msg=updated';</script>";
            exit;
        }
    } catch (PDOException $e) {
        $error = "Failed to update course: " . $e->getMessage();
    }
}

include 'includes/header.php'; 
include 'includes/sidebar.php'; 
?>

<style>
    :root { --theme-green: #064e3b; --theme-dark: #022c22; --theme-gold: #d4af37; }
    .dashboard-header { background: #fff; padding: 20px 30px; border-radius: 15px; box-shadow: 0 5px 20px rgba(0,0,0,0.03); margin-bottom: 35px; border-left: 5px solid var(--theme-green); }
    .form-card { background: #fff; border: 1px solid #e2e8f0; border-radius: 15px; box-shadow: 0 10px 40px rgba(0,0,0,0.03); padding: 40px; border-top: 6px solid var(--theme-green); }
    .section-title { font-weight: 800; color: var(--theme-dark); border-left: 4px solid var(--theme-gold); padding-left: 12px; margin-bottom: 25px; font-size: 16px; text-transform: uppercase; letter-spacing: 1px; margin-top:30px;}
    .form-label { font-weight: 700; color: var(--theme-dark); margin-bottom: 8px; font-size: 14px; }
    .form-control, .form-select { border-radius: 10px; padding: 14px 20px; border: 1px solid #cbd5e1; background-color: #f8fafc; transition: 0.3s; font-size: 15px; }
    .form-control:focus, .form-select:focus { border-color: var(--theme-green); background-color: #fff; box-shadow: 0 0 0 4px rgba(6, 78, 59, 0.1); outline: none; }
    .input-group-text { background-color: rgba(6, 78, 59, 0.05); border: 1px solid #cbd5e1; color: var(--theme-green); font-weight: 800; border-radius: 10px 0 0 10px !important; }
    .input-group .form-control { border-radius: 0 10px 10px 0 !important; }
    .btn-save { background: var(--theme-green); color: #fff; padding: 16px; border-radius: 12px; font-weight: 800; font-size: 16px; border: none; transition: 0.3s; box-shadow: 0 8px 20px rgba(6,78,59,0.2); }
    .btn-save:hover { background: var(--theme-dark); color: var(--theme-gold); transform: translateY(-3px); }

    /* --- 📱 Mobile Responsive Fixes --- */
    @media (max-width: 768px) {
        .main-content { padding: 15px !important; }
        .dashboard-header { flex-direction: column; align-items: flex-start !important; gap: 15px; padding: 15px 20px; }
        .dashboard-header .d-flex { width: 100%; align-items: center; }
        .dashboard-header > a.btn { width: 100%; justify-content: center; } 
        
        /* EXACT FIX FOR MENU BUTTON */
        #sidebarToggle { width: 42px !important; height: 42px !important; padding: 0; display: inline-flex !important; align-items: center; justify-content: center; flex-shrink: 0; border-radius: 8px;}
        .form-card { padding: 20px !important; }
    }
</style>

<div class="main-content p-4" style="background: #f8fafc; min-height: 100vh;">
    
    <div class="dashboard-header d-flex justify-content-between align-items-center">
        <div class="d-flex align-items-center">
            <button class="btn btn-light border d-md-none me-3 shadow-sm" id="sidebarToggle">
                <i class="fas fa-bars text-dark"></i>
            </button>
            <h4 class="mb-0 fw-bold" style="color: var(--theme-green);"><i class="fas fa-edit me-2" style="color: var(--theme-gold);"></i> Edit Course</h4>
        </div>
        <a href="manage_courses.php" class="btn btn-light border px-4 py-2 rounded-pill fw-bold shadow-sm text-dark text-decoration-none mt-3 mt-md-0"><i class="fas fa-arrow-left me-2"></i> List</a>
    </div>

    <div class="row justify-content-center">
        <div class="col-xl-9">
            <div class="form-card">
                <?php if($error): ?> <div class="alert alert-danger d-flex align-items-center mb-4 rounded-3 border-0 border-start border-4 border-danger shadow-sm bg-white"><i class="fas fa-exclamation-triangle me-3 fa-2x text-danger"></i> <div><strong class="d-block text-danger">Error!</strong> <span class="text-muted"><?= $error; ?></span></div></div> <?php endif; ?>

                <form method="POST" enctype="multipart/form-data">
                    <div class="section-title" style="margin-top:0;">1. Basic Info</div>
                    <div class="row g-4 mb-4">
                        <div class="col-md-12">
                            <label class="form-label">Course Title <span class="text-danger">*</span></label>
                            <input type="text" name="title" class="form-control" value="<?= htmlspecialchars($course['title']); ?>" required>
                        </div>

                        <div class="col-md-12">
                            <label class="form-label">Assign Course Teacher <span class="text-muted small fw-normal">(Optional)</span></label>
                            <select name="teacher_id" class="form-select fw-bold text-dark">
                                <option value="">-- Do Not Assign Yet --</option>
                                <?php foreach($teachers_list as $t): ?>
                                    <option value="<?= $t['id'] ?>" <?= ($course['teacher_id'] == $t['id']) ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($t['name']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label">Course Duration <span class="text-danger">*</span></label>
                            <input type="text" name="duration" class="form-control" value="<?= htmlspecialchars($course['duration']); ?>" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Course Fee</label>
                            <div class="input-group">
                                <span class="input-group-text">$</span>
                                <input type="number" name="fee" step="0.01" class="form-control fw-bold" style="color: var(--theme-green);" value="<?= $course['fee']; ?>">
                            </div>
                        </div>
                    </div>

                    <div class="section-title">2. Course Details Page Options</div>
                    <div class="row mb-4 g-4">
                        <div class="col-md-6">
                            <label class="form-label">Language(s)</label>
                            <input type="text" name="language" class="form-control" value="<?= htmlspecialchars($course['language'] ?? 'English, Bengali'); ?>" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Platform(s)</label>
                            <input type="text" name="platform" class="form-control" value="<?= htmlspecialchars($course['platform'] ?? 'Zoom, Google Meet'); ?>" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Course Level</label>
                            <input type="text" name="level" class="form-control" value="<?= htmlspecialchars($course['level'] ?? 'Beginner to Advanced'); ?>" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Assessment Type</label>
                            <input type="text" name="assessment" class="form-control" value="<?= htmlspecialchars($course['assessment'] ?? 'Quizzes & Assignments'); ?>" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Provides Certificate?</label>
                            <select name="has_certificate" class="form-select">
                                <option value="Yes" <?= ($course['has_certificate'] ?? '') == 'Yes' ? 'selected' : '' ?>>Yes</option>
                                <option value="No" <?= ($course['has_certificate'] ?? '') == 'No' ? 'selected' : '' ?>>No</option>
                            </select>
                        </div>
                    </div>

                    <div class="section-title">3. Content & Media</div>
                    <div class="mb-4">
                        <label class="form-label d-block">Current Image</label>
                        <img src="../<?= htmlspecialchars($course['image_url'] ?? 'assets/images/logo.png') ?>" style="height: 100px; border-radius: 8px; border: 2px solid var(--theme-green); margin-bottom: 10px;">
                        <input type="file" name="course_image" class="form-control" accept="image/*">
                    </div>

                    <div class="mb-4">
                        <label class="form-label">Course Description</label>
                        <textarea name="description" class="form-control" rows="6"><?= htmlspecialchars($course['description'] ?? ''); ?></textarea>
                    </div>

                    <div class="mb-5">
                        <label class="form-label">Publish Status</label>
                        <select name="status" class="form-select fw-bold text-dark">
                            <option value="active" <?= ($course['status'] == 'active') ? 'selected' : '' ?>>Active (Visible on website)</option>
                            <option value="inactive" <?= ($course['status'] == 'inactive') ? 'selected' : '' ?>>Inactive (Saved as draft)</option>
                        </select>
                    </div>

                    <div class="text-center pt-3 border-top">
                        <button type="submit" class="btn btn-save w-100"><i class="fas fa-check-circle me-2"></i> Save Changes</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    document.addEventListener("DOMContentLoaded", function() {
        const toggleBtn = document.getElementById('sidebarToggle');
        if (toggleBtn) {
            toggleBtn.addEventListener('click', function(e) {
                e.preventDefault();
                const sidebar = document.querySelector('.sidebar');
                if (sidebar) { sidebar.classList.toggle('active'); }
            });
        }
    });
</script>

<?php include 'includes/footer.php'; ?>