<?php
declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| Create Course
|--------------------------------------------------------------------------
*/

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

$pdo = db();

requireTeacher();

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

$teacher = currentTeacher($pdo);

if (!$teacher) {

    teacherLogout();

    redirectTo('teacher/login.php');
}

$error = '';
$success = flash('success') ?: '';

if (isPost()) {
    $title = trim((string)($_POST['title'] ?? ''));
    $description = trim((string)($_POST['description'] ?? ''));
    $level = (string)($_POST['level'] ?? '');
    $startDate = trim((string)($_POST['start_date'] ?? ''));

    if ($title === '' || !in_array($level, ['beginner','intermediate','advanced'], true) || !validDate($startDate)) {
        $error = 'Enter a title, valid level and start date.';
    } else {
        $imagePath = null;
        if (!empty($_FILES['image']['name'])) {
            $imagePath = uploadFile($_FILES['image'], 'course-images');
            if (!$imagePath) {
                $error = 'The course image was rejected. Use JPG, PNG or WEBP within the size limit.';
            }
        }
        if ($error === '') {
            try {
                $endDate = (new DateTimeImmutable($startDate))->modify('+27 days')->format('Y-m-d');
                $courseCode = '';
                for ($i=0; $i<12; $i++) {
                    $candidate = 'SMI-CORE-' . random_int(10000, 99999);
                    if (!safeFetch($pdo, 'SELECT id FROM core_courses WHERE course_code=?', [$candidate])) {
                        $courseCode = $candidate;
                        break;
                    }
                }
                if ($courseCode === '') throw new RuntimeException('Could not generate a unique course code.');
                mustExecute($pdo, "INSERT INTO core_courses (teacher_id,title,description,level,course_code,image,image_path,start_date,end_date,status,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,'draft',NOW(),NOW())", [(int)$teacher['id'],$title,$description?:null,$level,$courseCode,$imagePath,$imagePath,$startDate,$endDate]);
                $courseId=(int)$pdo->lastInsertId();
                logActivity($pdo,'teacher',(int)$teacher['id'],'Course created','Teacher created course: '.$title,null,$courseId);
                flash('success','Course created successfully as a draft.');
                redirect('teacher/courses.php');
            } catch(Throwable $e) {
                if ($imagePath) @unlink(ROOT_PATH . '/' . $imagePath);
                error_log('[SMI teacher create course] '.$e->getMessage());
                $error = APP_DEBUG ? $e->getMessage() : 'Failed to create course.';
            }
        }
    }
}

?>

<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="UTF-8">

<meta
name="viewport"
content="width=device-width, initial-scale=1.0">

<title>
Create Course
</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:#f3f6fb;

    color:#0f172a;
}

.page{

    max-width:1000px;

    margin:auto;

    padding:35px;
}

/*
|--------------------------------------------------------------------------
| Topbar
|--------------------------------------------------------------------------
*/

.topbar{

    display:flex;

    justify-content:space-between;

    align-items:center;

    margin-bottom:30px;
}

.title{

    font-size:42px;

    font-weight:900;
}

.back-btn{

    text-decoration:none;

    background:#eff6ff;

    color:#2563eb;

    padding:14px 22px;

    border-radius:18px;

    font-weight:900;
}

/*
|--------------------------------------------------------------------------
| Form Card
|--------------------------------------------------------------------------
*/

.card{

    background:#fff;

    border-radius:34px;

    padding:40px;

    border:1px solid #e2e8f0;

    box-shadow:
    0 20px 50px rgba(15,23,42,0.06);
}

.card h2{

    font-size:36px;

    margin-bottom:12px;

    font-weight:900;
}

.card p{

    color:#64748b;

    line-height:2;

    margin-bottom:35px;
}

/*
|--------------------------------------------------------------------------
| Alerts
|--------------------------------------------------------------------------
*/

.alert{

    padding:18px 22px;

    border-radius:18px;

    margin-bottom:24px;

    font-weight:700;
}

.alert.error{

    background:#fef2f2;

    color:#dc2626;
}

.alert.success{

    background:#dcfce7;

    color:#16a34a;
}

/*
|--------------------------------------------------------------------------
| Form
|--------------------------------------------------------------------------
*/

.grid{

    display:grid;

    grid-template-columns:
    1fr 1fr;

    gap:22px;
}

.group{

    margin-bottom:22px;
}

.group.full{

    grid-column:1 / -1;
}

.group label{

    display:block;

    margin-bottom:12px;

    font-weight:800;
}

.group input,
.group select,
.group textarea{

    width:100%;

    padding:18px;

    border-radius:18px;

    border:1px solid #dbeafe;

    background:#fff;

    font-family:inherit;

    font-size:15px;
}

.group textarea{

    min-height:160px;

    resize:vertical;
}

.group input:focus,
.group select:focus,
.group textarea:focus{

    outline:none;

    border-color:#2563eb;

    box-shadow:
    0 0 0 5px rgba(37,99,235,0.10);
}

/*
|--------------------------------------------------------------------------
| Button
|--------------------------------------------------------------------------
*/

.submit-btn{

    width:100%;

    border:none;

    background:
    linear-gradient(
        135deg,
        #2563eb,
        #1d4ed8
    );

    color:#fff;

    padding:20px;

    border-radius:22px;

    font-size:16px;

    font-weight:900;

    cursor:pointer;

    transition:0.25s;
}

.submit-btn:hover{

    transform:translateY(-2px);

    box-shadow:
    0 18px 35px rgba(37,99,235,0.20);
}

/*
|--------------------------------------------------------------------------
| Responsive
|--------------------------------------------------------------------------
*/

@media(max-width:700px){

    .page{

        padding:20px;
    }

    .grid{

        grid-template-columns:1fr;
    }

    .title{

        font-size:34px;
    }
}

</style>

</head>

<body>

<div class="page">

    <div class="topbar">

        <h1 class="title">

            Create Course

        </h1>

        <a
        href="courses.php"
        class="back-btn">

            ← Back

        </a>

    </div>

    <div class="card">

        <h2>

            New Academic Course

        </h2>

        <p>

            Create a new SMI course,
            generate a course code,
            and automatically calculate
            the course end date.

        </p>

        <?php if($error): ?>

            <div class="alert error">

                <?php
                echo e($error);
                ?>

            </div>

        <?php endif; ?>

        <?php if($success): ?>

            <div class="alert success">

                <?php
                echo e($success);
                ?>

            </div>

        <?php endif; ?>

        <form
        method="POST"
        enctype="multipart/form-data">
<?php echo csrfField(); ?>

            <div class="grid">

                <div class="group">

                    <label>

                        Course Title

                    </label>

                    <input
                    type="text"
                    name="title"
                    required>

                </div>

                <div class="group">

                    <label>

                        Course Level

                    </label>

                    <select
                    name="level"
                    required>

                        <option value="">
                            Select Level
                        </option>

                        <option value="beginner">
                            Beginner
                        </option>

                        <option value="intermediate">
                            Intermediate
                        </option>

                        <option value="advanced">
                            Advanced
                        </option>

                    </select>

                </div>

                <div class="group">

                    <label>

                        Course Start Date

                    </label>

                    <input
                    type="date"
                    name="start_date"
                    required>

                </div>

                <div class="group">

                    <label>

                        Course Image

                    </label>

                    <input
                    type="file"
                    name="image">

                </div>

                <div class="group full">

                    <label>

                        Course Description

                    </label>

                    <textarea
                    name="description"></textarea>

                </div>

            </div>

            <button
            type="submit"
            class="submit-btn">

                Create Course

            </button>

        </form>

    </div>

</div>

</body>
</html>