<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/admin-auth.php';

$pdo = db();
requireAdmin();

if (isPost()) { requireCsrf(); }

$success = flash('success') ?: '';
$error = '';
$admin = currentAdmin($pdo);
if (isPost()) {
    $action=(string)($_POST['action']??'');
    try {
        if($action==='delete'){
            $id=(int)($_POST['delete_id']??0);$course=safeFetch($pdo,'SELECT id,title FROM core_courses WHERE id=?',[$id]);if(!$course)throw new RuntimeException('Course not found.');
            $related=0;foreach(['core_course_students','core_sessions','core_exams','core_homework','core_materials'] as $table){if(tableExists($pdo,$table))$related+=safeCount($pdo,"SELECT COUNT(*) FROM `$table` WHERE course_id=?",[$id]);}
            if($related>0){mustExecute($pdo,"UPDATE core_courses SET status='closed',updated_at=NOW() WHERE id=?",[$id]);flash('success','The course has records, so it was closed instead of deleted.');}
            else{mustExecute($pdo,'DELETE FROM core_courses WHERE id=?',[$id]);flash('success','Course deleted successfully.');}
            logActivity($pdo,'admin',(int)($admin['id']??0),'Course removed','Course ID '.$id,null,$id);redirect('admin/courses.php');
        }
        if($action==='add_course'){
            $teacherId=(int)($_POST['teacher_id']??0);$title=trim((string)($_POST['title']??''));$description=trim((string)($_POST['description']??''));$level=(string)($_POST['level']??'beginner');$courseCode=strtoupper(trim((string)($_POST['course_code']??'')));$startDate=trim((string)($_POST['start_date']??''));$status=(string)($_POST['status']??'draft');
            if(!$teacherId||!safeFetch($pdo,"SELECT id FROM core_teachers WHERE id=? AND status='active'",[$teacherId]))throw new RuntimeException('Select an active teacher.');
            if($title===''||!validDate($startDate)||!in_array($level,['beginner','intermediate','advanced'],true)||!in_array($status,['draft','open','active','completed','closed'],true))throw new RuntimeException('Enter a title, valid level, date and status.');
            if($courseCode===''){$courseCode='SMI-CORE-'.random_int(10000,99999);}if(!preg_match('/^[A-Z0-9_-]{4,30}$/',$courseCode))throw new RuntimeException('Course code may contain letters, numbers, underscores and hyphens only.');
            if(safeFetch($pdo,'SELECT id FROM core_courses WHERE course_code=?',[$courseCode]))throw new RuntimeException('Course code already exists.');$endDate=(new DateTimeImmutable($startDate))->modify('+27 days')->format('Y-m-d');
            mustExecute($pdo,'INSERT INTO core_courses (teacher_id,title,description,level,course_code,start_date,end_date,status,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,NOW(),NOW())',[$teacherId,$title,$description?:null,$level,$courseCode,$startDate,$endDate,$status]);
            $id=(int)$pdo->lastInsertId();logActivity($pdo,'admin',(int)($admin['id']??0),'Course created','Created course: '.$title,null,$id);flash('success','Course added successfully.');redirect('admin/courses.php');
        }
    }catch(Throwable $e){error_log('[SMI admin courses] '.$e->getMessage());$error=APP_DEBUG?$e->getMessage():$e->getMessage();}
}

/*
|--------------------------------------------------------------------------
| Teachers
|--------------------------------------------------------------------------
*/

$teachers = [];

if (tableExists($pdo, 'core_teachers')) {
    $teachers = $pdo->query("
        SELECT id, full_name, name, email
        FROM core_teachers
        ORDER BY id DESC
    ")->fetchAll();
}

/*
|--------------------------------------------------------------------------
| Courses
|--------------------------------------------------------------------------
*/

$courses = [];

if (tableExists($pdo, 'core_courses')) {
    $courses = $pdo->query("
        SELECT c.*, t.full_name AS teacher_full_name, t.name AS teacher_name
        FROM core_courses c
        LEFT JOIN core_teachers t ON t.id = c.teacher_id
        ORDER BY c.id DESC
    ")->fetchAll();
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Courses Management</title>

<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">

<style>
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:'Inter',sans-serif;background:#f1f5f9;color:#0f172a}
.page{padding:34px}
.topbar{display:flex;justify-content:space-between;align-items:center;margin-bottom:30px;gap:20px}
.page-title{font-size:42px;font-weight:900}
.back-btn{background:#dbeafe;color:#1d4ed8;text-decoration:none;padding:14px 20px;border-radius:18px;font-weight:900}
.grid{display:grid;grid-template-columns:420px 1fr;gap:26px}
.card{background:#fff;border-radius:34px;padding:30px;border:1px solid #e2e8f0;box-shadow:0 18px 45px rgba(15,23,42,.05)}
.card h2{font-size:30px;margin-bottom:22px;font-weight:900}
.form-group{margin-bottom:18px}
.form-group label{display:block;margin-bottom:10px;font-weight:800}
.form-control{width:100%;padding:16px;border-radius:18px;border:1px solid #cbd5e1;outline:none;font-size:14px}
textarea.form-control{min-height:120px;resize:vertical}
.submit-btn{width:100%;border:none;background:linear-gradient(135deg,#2563eb,#7c3aed);color:#fff;padding:18px;border-radius:20px;font-weight:900;cursor:pointer}
.table-wrap{overflow:auto}
table{width:100%;border-collapse:collapse}
th{background:#f8fafc;padding:18px;text-align:left;font-size:13px;text-transform:uppercase;color:#64748b}
td{padding:18px;border-top:1px solid #e2e8f0;font-size:14px;vertical-align:top}
.badge{display:inline-block;padding:8px 12px;border-radius:999px;background:#dbeafe;color:#1d4ed8;font-size:12px;font-weight:900}
.action-btn{padding:10px 14px;border-radius:14px;text-decoration:none;font-size:12px;font-weight:900}
.delete-btn{background:#fee2e2;color:#b91c1c}
.alert{padding:18px;border-radius:18px;margin-bottom:24px;font-weight:800}
.alert-success{background:#dcfce7;color:#166534}
.alert-danger{background:#fee2e2;color:#991b1b}
@media(max-width:1100px){.grid{grid-template-columns:1fr}}
</style>
</head>

<body>

<div class="page">

    <div class="topbar">
        <h1 class="page-title">Courses Management</h1>
        <a href="dashboard.php" class="back-btn">← Dashboard</a>
    </div>

    <?php if($success): ?>
        <div class="alert alert-success"><?php echo e($success); ?></div>
    <?php endif; ?>

    <?php if($error): ?>
        <div class="alert alert-danger"><?php echo e($error); ?></div>
    <?php endif; ?>

    <div class="grid">

        <div class="card">

            <h2>Add Course</h2>

            <form method="POST">
<?php echo csrfField(); ?>

                <input type="hidden" name="action" value="add_course">

                <div class="form-group">
                    <label>Teacher</label>
                    <select name="teacher_id" class="form-control">
                        <option value="">Select teacher</option>
                        <?php foreach($teachers as $teacher): ?>
                            <option value="<?php echo e((string)$teacher['id']); ?>">
                                <?php echo e($teacher['full_name'] ?? $teacher['name'] ?? $teacher['email']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="form-group">
                    <label>Course Title</label>
                    <input type="text" name="title" class="form-control" required>
                </div>

                <div class="form-group">
                    <label>Course Code</label>
                    <input type="text" name="course_code" class="form-control" placeholder="Auto if empty">
                </div>

                <div class="form-group">
                    <label>Level</label>
                    <select name="level" class="form-control">
                        <option value="beginner">Beginner</option>
                        <option value="intermediate">Intermediate</option>
                        <option value="advanced">Advanced</option>
                    </select>
                </div>

                <div class="form-group">
                    <label>Start Date</label>
                    <input type="date" name="start_date" class="form-control">
                </div>

                <div class="form-group">
                    <label>Status</label>
                    <select name="status" class="form-control">
                        <option value="active">Active</option>
                        <option value="draft">Draft</option>
                        <option value="closed">Closed</option>
                    </select>
                </div>

                <div class="form-group">
                    <label>Description</label>
                    <textarea name="description" class="form-control"></textarea>
                </div>

                <button type="submit" class="submit-btn">Add Course</button>

            </form>

        </div>

        <div class="card">

            <h2>Courses List</h2>

            <div class="table-wrap">

                <table>
                    <thead>
                        <tr>
                            <th>Course</th>
                            <th>Code</th>
                            <th>Teacher</th>
                            <th>Level</th>
                            <th>Dates</th>
                            <th>Status</th>
                            <th>Action</th>
                        </tr>
                    </thead>

                    <tbody>

                    <?php if($courses): ?>

                        <?php foreach($courses as $course): ?>

                            <tr>
                                <td><?php echo e($course['title']); ?></td>

                                <td><?php echo e($course['course_code'] ?? 'N/A'); ?></td>

                                <td>
                                    <?php
                                    echo e(
                                        $course['teacher_full_name']
                                        ?? $course['teacher_name']
                                        ?? 'N/A'
                                    );
                                    ?>
                                </td>

                                <td>
                                    <span class="badge">
                                        <?php echo e(ucfirst($course['level'] ?? 'general')); ?>
                                    </span>
                                </td>

                                <td>
                                    <?php echo e($course['start_date'] ?? '-'); ?>
                                    <br>
                                    <?php echo e($course['end_date'] ?? '-'); ?>
                                </td>

                                <td><?php echo e($course['status'] ?? 'active'); ?></td>

                                <td>
                                    <form method="post" style="display:inline" onsubmit="return confirm('Delete this course?')">
<?php echo csrfField(); ?>
<input type="hidden" name="action" value="delete">
<input type="hidden" name="delete_id" value="<?php echo e((string)$course['id']); ?>">
<button type="submit" class="action-btn delete-btn">Delete</button>
</form>
                                </td>
                            </tr>

                        <?php endforeach; ?>

                    <?php else: ?>

                        <tr>
                            <td colspan="7">No courses found.</td>
                        </tr>

                    <?php endif; ?>

                    </tbody>
                </table>

            </div>

        </div>

    </div>

</div>

</body>
</html>