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

$teacher_id = $_SESSION['teacher_id'];
$id = $_GET['id'] ?? null;

if (!$id) { echo "<script>window.location.href='manage_materials.php';</script>"; exit; }

$msg = ""; $msgType = "";

// ১. বর্তমান মেটেরিয়াল ডাটা সংগ্রহ করা
try {
    $stmt = $pdo->prepare("SELECT * FROM course_materials WHERE id = ? AND teacher_id = ?");
    $stmt->execute([$id, $teacher_id]);
    $material = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$material) { die("<div class='p-5 text-center fw-bold text-danger'>File not found or access denied!</div>"); }

    // কোর্স লিস্ট সংগ্রহ (Fallback সহ)
    $course_stmt = $pdo->prepare("SELECT id, title FROM courses WHERE teacher_id = ? OR 1=1 AND status='active'");
    $course_stmt->execute([$teacher_id]);
    $courses = $course_stmt->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) { die("Database Error: " . $e->getMessage()); }

// ২. আপডেট লজিক
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $course_id = $_POST['course_id'];
    $title = trim($_POST['title']);
    $desc = trim($_POST['description']);
    $db_path = $material['file_path']; // আগের ফাইল পাথ ডিফল্ট হিসেবে রাখা
    $file_ext = $material['file_type'];

    // যদি নতুন ফাইল আপলোড করা হয়
    if (isset($_FILES['material_file']) && $_FILES['material_file']['error'] == 0) {
        $upload_dir = '../uploads/materials/';
        if (!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
        
        // পুরাতন ফাইলটি ডিলিট করা
        if (file_exists('../' . $material['file_path'])) {
            unlink('../' . $material['file_path']);
        }

        $file_ext = pathinfo($_FILES['material_file']['name'], PATHINFO_EXTENSION);
        $file_name = "doc_" . time() . "_" . rand(1000, 9999) . "." . $file_ext;
        $dest = $upload_dir . $file_name;
        
        if (move_uploaded_file($_FILES['material_file']['tmp_name'], $dest)) {
            $db_path = 'uploads/materials/' . $file_name;
        }
    }

    try {
        $sql = "UPDATE course_materials SET course_id=?, title=?, description=?, file_path=?, file_type=? WHERE id=? AND teacher_id=?";
        $pdo->prepare($sql)->execute([$course_id, $title, $desc, $db_path, $file_ext, $id, $teacher_id]);
        
        $msg = "Material updated successfully!";
        $msgType = "success";
        
        // আপডেট হওয়া ডাটা পুনরায় লোড করা
        $stmt->execute([$id, $teacher_id]);
        $material = $stmt->fetch(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        $msg = "Update failed: " . $e->getMessage();
        $msgType = "danger";
    }
}
?>

<style>
    :root { --theme-green: #064e3b; --theme-dark: #022c22; --theme-gold: #d4af37; --bg-soft: #f8fafc; }
    .main-content { background-color: var(--bg-soft); min-height: 100vh; padding: 30px; transition: 0.4s; }
    
    .dashboard-header { background: #fff; padding: 20px 30px; border-radius: 15px; box-shadow: 0 5px 20px rgba(0,0,0,0.03); margin-bottom: 25px; border-left: 6px solid var(--theme-green); }
    .form-card { background: #fff; border: 1px solid #e2e8f0; border-radius: 18px; box-shadow: 0 10px 40px rgba(0,0,0,0.03); padding: 35px; border-top: 6px solid var(--theme-green); }
    
    .form-label { font-weight: 700; color: var(--theme-dark); font-size: 12px; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 8px; }
    .form-control, .form-select { border-radius: 10px; padding: 12px 18px; border: 2px solid #f1f5f9; background: var(--bg-soft); transition: 0.3s; font-size: 14px; font-weight: 500; color: var(--theme-dark); }
    .form-control:focus { border-color: var(--theme-green); background: #fff; box-shadow: 0 0 0 4px rgba(6, 78, 59, 0.1); outline: none; }
    
    .btn-update { background: var(--theme-green); color: #fff; padding: 14px 45px; border-radius: 50px; font-weight: 800; font-size: 16px; border: none; transition: 0.3s; box-shadow: 0 8px 20px rgba(6, 78, 59, 0.2); }
    .btn-update:hover { background: var(--theme-dark); color: var(--theme-gold); transform: translateY(-2px); }

    /* Square Menu Button Fix */
    #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; border: 1px solid #e2e8f0; background: #fff; box-shadow: 0 2px 5px rgba(0,0,0,0.05); }

    @media (max-width: 991px) {
        .main-content { padding: 15px !important; margin-left: 0; }
        .dashboard-header { flex-direction: column; align-items: flex-start !important; gap: 15px; padding: 15px 20px; }
        .dashboard-header .d-flex { width: 100%; align-items: center; }
        .form-card { padding: 25px 20px !important; }
        .btn-update { width: 100%; }
    }
</style>

<div class="main-content">
    <div class="dashboard-header d-flex justify-content-between align-items-center fade-up">
        <div class="d-flex align-items-center">
            <button class="btn btn-light border d-lg-none me-3 shadow-sm" id="sidebarToggle"><i class="fas fa-bars text-dark"></i></button>
            <h4 class="mb-0 fw-bold text-dark"><i class="fas fa-edit me-2" style="color: var(--theme-gold);"></i> Edit Material</h4>
        </div>
        <a href="manage_materials.php" class="btn btn-light border px-4 py-2 rounded-pill fw-bold shadow-sm text-dark text-decoration-none">
            <i class="fas fa-arrow-left me-2"></i> Back
        </a>
    </div>

    <div class="row justify-content-center">
        <div class="col-xl-9">
            <?php if($msg): ?>
                <div class="alert alert-<?= $msgType ?> border-0 border-start border-4 border-<?= $msgType ?> shadow-sm mb-4 fw-bold p-3 fade-up bg-white">
                    <i class="fas <?= $msgType == 'success' ? 'fa-check-circle' : 'fa-exclamation-circle' ?> me-2"></i> <?= $msg ?>
                </div>
            <?php endif; ?>

            <div class="form-card fade-up">
                <form method="POST" enctype="multipart/form-data">
                    <div class="row g-4">
                        <div class="col-md-12">
                            <label class="form-label">Material Title *</label>
                            <input type="text" name="title" class="form-control" value="<?= htmlspecialchars($material['title']) ?>" required>
                        </div>
                        
                        <div class="col-md-6">
                            <label class="form-label">Course *</label>
                            <select name="course_id" class="form-select fw-bold" required>
                                <?php foreach($courses as $c): ?>
                                    <option value="<?= $c['id'] ?>" <?= ($material['course_id'] == $c['id']) ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($c['title']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label">Change File (Optional)</label>
                            <input type="file" name="material_file" class="form-control">
                            <small class="text-muted d-block mt-1">Current: <a href="../<?= $material['file_path'] ?>" target="_blank" class="fw-bold text-success">View Existing File</a></small>
                        </div>

                        <div class="col-md-12">
                            <label class="form-label">Description</label>
                            <textarea name="description" class="form-control" rows="4"><?= htmlspecialchars($material['description'] ?? '') ?></textarea>
                        </div>
                    </div>

                    <div class="text-center mt-5 pt-4 border-top">
                        <button type="submit" class="btn btn-update">
                            <i class="fas fa-save me-2"></i> Update Material
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

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

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