<?php
session_start();
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(E_ALL);
include "../user/db.php";

/* ---------- AUTH ---------- */
if(!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin'){
    header("Location: ../login.php");
    exit;
}
include "back.php";
/* ---------- HANDLE DELETE ---------- */
if(isset($_GET['delete_course'])){
    $course_id = intval($_GET['delete_course']);
    
    // Delete modules, quizzes, files
    $modulesRes = $conn->query("SELECT * FROM modules WHERE course_id=$course_id");
    while($mod = $modulesRes->fetch_assoc()){
        if($mod['pdf_file'] && file_exists('../'.$mod['pdf_file'])) unlink('../'.$mod['pdf_file']);
        if($mod['video_file'] && file_exists('../'.$mod['video_file'])) unlink('../'.$mod['video_file']);
        $conn->query("DELETE FROM quizzes WHERE module_id=".$mod['id']);
        $conn->query("DELETE FROM modules WHERE id=".$mod['id']);
    }

    // Delete course files
    $course = $conn->query("SELECT * FROM courses WHERE id=$course_id")->fetch_assoc();
    if($course['cover'] && file_exists('../'.$course['cover'])) unlink('../'.$course['cover']);
    if($course['course_outline_pdf'] && file_exists('../'.$course['course_outline_pdf'])) unlink('../'.$course['course_outline_pdf']);

    $conn->query("DELETE FROM courses WHERE id=$course_id");

    header("Location: ".basename($_SERVER['PHP_SELF'])."?msg=deleted");
    exit;
}

/* ---------- FETCH COURSES ---------- */
$coursesRes = $conn->query("SELECT * FROM courses ORDER BY created_at DESC");
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Admin - Manage Courses</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://cdn.tailwindcss.com"></script>
<style>
body{background:#f3f4f6;}

/* Modal styling */
.modal{display:none;position:fixed;inset:0;background:rgba(0,0,0,.6);align-items:center;justify-content:center;z-index:50;padding:16px;}
.modal-content{background:#fff;width:100%;max-width:700px;border-radius:16px;padding:20px;max-height:90vh;overflow-y:auto;position:relative;}
.close-btn{position:absolute;top:10px;right:15px;font-size:24px;cursor:pointer;}

/* Unified Preloader */
#preloader{
    position: fixed;
    inset: 0;
    background: #fff;
    z-index: 9999;
    display: flex;
    justify-content: center;
    align-items: center;
}
#preloader .spinner{
    width: 60px;
    height: 60px;
    border: 6px solid #f3f3f3;
    border-top: 6px solid #f59e0b; /* Tailwind amber-400 */
    border-radius: 50%;
    animation: spin 1s linear infinite;
}
@keyframes spin{
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}
</style>
</head>
<body class="p-4">

<!-- Preloader -->
<div id="preloader">
    <div class="spinner"></div>
</div>

<h1 class="text-3xl font-bold mb-6 text-center">Manage Courses</h1>

<?php if(isset($_GET['msg'])): ?>
<div class="bg-green-400 text-white p-3 rounded mb-4 text-center">
<?php 
if($_GET['msg']=='deleted') echo "Course deleted successfully!";
if($_GET['msg']=='updated') echo "Course updated successfully!";
?>
</div>
<?php endif; ?>

<div class="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
<?php while($course = $coursesRes->fetch_assoc()): ?>
<div class="bg-white rounded-xl shadow p-4 flex flex-col">
<img src="<?= htmlspecialchars($course['cover']) ?>" class="rounded mb-3 h-40 object-cover" onerror="this.src='https://via.placeholder.com/300x200?text=No+Image'">
<h2 class="font-semibold text-lg mb-1"><?= htmlspecialchars($course['title']) ?></h2>
<p class="text-sm mb-2">Tutor: <?= htmlspecialchars($course['tutor']) ?></p>
<p class="text-sm mb-2">Price: ₦<?= number_format($course['price'],2) ?></p>
<p class="text-sm mb-2">Created: <?= date('d M, Y', strtotime($course['created_at'])) ?></p>

<div class="mt-auto flex gap-2">
<button class="bg-blue-500 text-white px-3 py-1 rounded" onclick="openEdit(<?= $course['id'] ?>)">Edit</button>

<!-- Fixed delete link -->
<a href="<?= htmlspecialchars($_SERVER['PHP_SELF']) ?>?delete_course=<?= $course['id'] ?>" 
   onclick="return confirm('Are you sure to delete this course?')" 
   class="bg-red-500 text-white px-3 py-1 rounded">
   Delete
</a>
</div>
</div>
<?php endwhile; ?>
</div>

<!-- EDIT COURSE MODAL -->
<div id="editModal" class="modal">
<div class="modal-content">
<span class="close-btn" onclick="closeModal()">&times;</span>
<h2 class="text-2xl font-semibold mb-4">Edit Course</h2>
<form id="editForm" method="post" enctype="multipart/form-data">
<input type="hidden" name="course_id" id="course_id">

<label class="block mb-2 font-medium">Course Title</label>
<input type="text" name="course_title" id="course_title" class="w-full p-2 mb-3 border rounded" required>

<label class="block mb-2 font-medium">Tutor</label>
<input type="text" name="tutor" id="tutor" class="w-full p-2 mb-3 border rounded" required>

<label class="block mb-2 font-medium">Price</label>
<input type="number" step="0.01" name="price" id="price" class="w-full p-2 mb-3 border rounded">

<label class="block mb-2 font-medium">Course Cover (optional)</label>
<input type="file" name="cover" class="w-full mb-3">

<label class="block mb-2 font-medium">Course PDF (optional)</label>
<input type="file" name="course_pdf" accept=".pdf" class="w-full mb-3">

<div id="modulesEditContainer" class="space-y-4"></div>

<button type="submit" class="bg-yellow-500 text-white px-4 py-2 rounded mt-3 w-full">Update Course</button>
</form>
</div>
</div>

<script>
// Unified preloader
function showPreloader(){ document.getElementById('preloader').style.display='flex'; }
function hidePreloader(){ document.getElementById('preloader').style.display='none'; }

// Hide preloader when page fully loads
window.addEventListener('load', hidePreloader);

function openEdit(id){
    showPreloader();
    fetch('fetch_course_admin.php?id='+id)
    .then(r=>r.json())
    .then(data=>{
        hidePreloader();
        document.getElementById('course_id').value = data.course.id;
        document.getElementById('course_title').value = data.course.title;
        document.getElementById('tutor').value = data.course.tutor;
        document.getElementById('price').value = data.course.price;

        const modContainer = document.getElementById('modulesEditContainer');
        modContainer.innerHTML = '';
        data.modules.forEach((m,i)=>{
            let div = document.createElement('div');
            div.className='border p-3 rounded bg-gray-50';
            div.innerHTML=`
<h3 class="font-semibold mb-2">Module ${i+1}</h3>
<label class="block mb-1">Module Title</label>
<input type="text" name="module_title[${m.id}]" value="${m.title}" class="w-full p-2 border mb-2 rounded" required>
<label class="block mb-1">Video (optional)</label>
<input type="file" name="module_video[${m.id}]" class="w-full mb-2">
${m.video_file?'<p class="text-sm text-gray-600">Current video: '+m.video_file+'</p>':''}
<label class="block mb-1">PDF (optional)</label>
<input type="file" name="module_pdf[${m.id}]" class="w-full mb-2">
${m.pdf_file?'<p class="text-sm text-gray-600">Current PDF: '+m.pdf_file+'</p>':''}
`;
            modContainer.appendChild(div);
        });

        document.getElementById('editModal').style.display='flex';
    });
}

function closeModal(){ document.getElementById('editModal').style.display='none'; }

// Handle form submission via POST with preloader
document.getElementById('editForm').addEventListener('submit', function(e){
    e.preventDefault();
    showPreloader();

    const fd = new FormData(this);
    fetch('update_course_admin.php',{method:'POST',body:fd})
    .then(r=>r.json())
    .then(d=>{
        hidePreloader();
        if(d.success){
            alert('Course updated!');
            location.reload();
        } else alert('Update failed');
    });
});
</script>

</body>
</html>
