<?php
declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| Teacher Course Sessions
|--------------------------------------------------------------------------
*/

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 = '';

$courseId = (int)($_GET['course'] ?? $_POST['course_id'] ?? 0);

/*
|--------------------------------------------------------------------------
| Get Teacher Courses
|--------------------------------------------------------------------------
*/

$courses = [];

if (tableExists($pdo, 'core_courses')) {
    $courseStmt = $pdo->prepare("
        SELECT *
        FROM core_courses
        WHERE teacher_id = ?
        ORDER BY id DESC
    ");

    $courseStmt->execute([
        $teacher['id']
    ]);

    $courses = $courseStmt->fetchAll();
}

/*
|--------------------------------------------------------------------------
| Validate Selected Course
|--------------------------------------------------------------------------
*/

$selectedCourse = null;

if ($courseId > 0) {
    $checkCourseStmt = $pdo->prepare("
        SELECT *
        FROM core_courses
        WHERE id = ?
        AND teacher_id = ?
        LIMIT 1
    ");

    $checkCourseStmt->execute([
        $courseId,
        $teacher['id']
    ]);

    $selectedCourse = $checkCourseStmt->fetch();

    if (!$selectedCourse) {
        $courseId = 0;
    }
}

/*
|--------------------------------------------------------------------------
| Create Session
|--------------------------------------------------------------------------
*/

if (isPost() && ($_POST['action'] ?? '') === 'create_session') {

    $courseId = (int)($_POST['course_id'] ?? 0);
    $title = trim($_POST['title'] ?? '');
    $sessionDate = trim($_POST['session_date'] ?? '');
    $sessionTime = trim($_POST['session_time'] ?? '');
    $zoomLink = trim($_POST['zoom_link'] ?? '');
    $lessonLink = trim($_POST['lesson_link'] ?? '');
    $teacherNotes = trim($_POST['teacher_notes'] ?? '');

    $courseCheckStmt = $pdo->prepare("
        SELECT *
        FROM core_courses
        WHERE id = ?
        AND teacher_id = ?
        LIMIT 1
    ");

    $courseCheckStmt->execute([
        $courseId,
        $teacher['id']
    ]);

    $selectedCourse = $courseCheckStmt->fetch();

    if (!$selectedCourse) {

        $error = 'Invalid course selected.';

    } elseif ($title === '' || !validDate($sessionDate) || !preg_match('/^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?$/', $sessionTime)) {

        $error = 'Enter a title and valid session date/time.';

    } elseif ($zoomLink !== '' && !filter_var($zoomLink, FILTER_VALIDATE_URL)) {

        $error = 'Zoom link is invalid.';

    } elseif ($lessonLink !== '' && !filter_var($lessonLink, FILTER_VALIDATE_URL)) {

        $error = 'Lesson link is invalid.';

    } else {

        try {

            $insertStmt = $pdo->prepare("
                INSERT INTO core_sessions (
                    course_id,
                    teacher_id,
                    title,
                    session_date,
                    session_time,
                    zoom_link,
                    lesson_link,
                    teacher_notes,
                    created_at
                )
                VALUES (
                    ?, ?, ?, ?, ?, ?, ?, ?, ?
                )
            ");

            $insertStmt->execute([
                $courseId,
                $teacher['id'],
                $title,
                $sessionDate,
                $sessionTime,
                $zoomLink,
                $lessonLink,
                $teacherNotes,
                now()
            ]);

            logActivity(
                $pdo,
                'teacher',
                (int)$teacher['id'],
                'Core Session Created',
                'Created session: ' . $title
            );

            $success = 'Session created successfully.';

        } catch (Throwable $e) {

            if (APP_DEBUG) {
                die($e->getMessage());
            }

            $error = 'Failed to create session.';
        }
    }
}

/*
|--------------------------------------------------------------------------
| Sessions
|--------------------------------------------------------------------------
*/

$sessions = [];

if ($courseId > 0 && tableExists($pdo, 'core_sessions')) {

    $stmt = $pdo->prepare("
        SELECT *
        FROM core_sessions
        WHERE course_id = ?
        AND teacher_id = ?
        ORDER BY session_date DESC, session_time DESC
    ");

    $stmt->execute([
        $courseId,
        $teacher['id']
    ]);

    $sessions = $stmt->fetchAll();
}

?>

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

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

<title>Teacher Sessions</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{
    padding:35px;
}

.topbar{
    display:flex;
    justify-content:space-between;
    align-items:center;
    gap:18px;
    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;
}

.hero{
    background:linear-gradient(135deg,#0f172a,#1d4ed8);
    color:#fff;
    border-radius:34px;
    padding:40px;
    margin-bottom:30px;
    box-shadow:0 35px 70px rgba(37,99,235,0.18);
}

.hero h1{
    font-size:44px;
    margin-bottom:14px;
    font-weight:900;
}

.hero p{
    color:#dbeafe;
    line-height:2;
}

.alert{
    padding:18px 22px;
    border-radius:18px;
    margin-bottom:24px;
    font-weight:800;
}

.alert.error{
    background:#fef2f2;
    color:#dc2626;
}

.alert.success{
    background:#dcfce7;
    color:#16a34a;
}

.layout{
    display:grid;
    grid-template-columns:430px 1fr;
    gap:24px;
}

.card{
    background:#fff;
    border-radius:32px;
    padding:30px;
    border:1px solid #e2e8f0;
    box-shadow:0 18px 50px rgba(15,23,42,0.06);
}

.card h2{
    font-size:28px;
    margin-bottom:22px;
    font-weight:900;
}

.group{
    margin-bottom:20px;
}

.group label{
    display:block;
    margin-bottom:10px;
    font-weight:800;
    color:#334155;
}

.group input,
.group select,
.group textarea{
    width:100%;
    padding:16px 18px;
    border-radius:18px;
    border:1px solid #dbeafe;
    font-family:inherit;
    font-size:15px;
}

.group textarea{
    min-height:125px;
    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);
}

.submit-btn{
    width:100%;
    border:none;
    background:linear-gradient(135deg,#2563eb,#1d4ed8);
    color:#fff;
    padding:18px;
    border-radius:20px;
    font-size:16px;
    font-weight:900;
    cursor:pointer;
}

.session{
    background:#f8fafc;
    border:1px solid #e2e8f0;
    border-radius:24px;
    padding:22px;
    margin-bottom:18px;
}

.session h3{
    font-size:22px;
    margin-bottom:10px;
    font-weight:900;
}

.session p{
    color:#64748b;
    line-height:1.8;
    margin-bottom:6px;
}

.session-actions{
    display:flex;
    gap:12px;
    flex-wrap:wrap;
    margin-top:16px;
}

.session-actions a{
    text-decoration:none;
    padding:12px 16px;
    border-radius:14px;
    font-weight:900;
    font-size:13px;
}

.zoom{
    background:#2563eb;
    color:#fff;
}

.attendance{
    background:#dcfce7;
    color:#16a34a;
}

.empty{
    padding:50px;
    text-align:center;
    border:1px dashed #cbd5e1;
    border-radius:24px;
    color:#64748b;
    line-height:1.9;
}

@media(max-width:1100px){
    .layout{
        grid-template-columns:1fr;
    }
}

@media(max-width:700px){
    .page{
        padding:20px;
    }

    .topbar{
        flex-direction:column;
        align-items:flex-start;
    }

    .title{
        font-size:34px;
    }

    .hero h1{
        font-size:34px;
    }
}
</style>

</head>

<body>

<div class="page">

    <div class="topbar">

        <h1 class="title">
            Course Sessions
        </h1>

        <a href="dashboard.php" class="back-btn">
            ← Dashboard
        </a>

    </div>

    <div class="hero">

        <h1>
            Zoom Sessions & Lessons
        </h1>

        <p>
            Create course sessions, add Zoom links, set dates and times,
            attach lesson links, and later generate attendance from each session.
        </p>

    </div>

    <?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; ?>

    <div class="layout">

        <div class="card">

            <h2>
                Create Session
            </h2>

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

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

                <div class="group">
                    <label>Course</label>

                    <select name="course_id" required>
                        <option value="">Select Course</option>

                        <?php foreach($courses as $course): ?>
                            <option
                                value="<?php echo e((string)$course['id']); ?>"
                                <?php echo ((int)$course['id'] === $courseId) ? 'selected' : ''; ?>
                            >
                                <?php echo e($course['title']); ?>
                                —
                                <?php echo e($course['course_code']); ?>
                            </option>
                        <?php endforeach; ?>

                    </select>
                </div>

                <div class="group">
                    <label>Session Title</label>
                    <input type="text" name="title" required>
                </div>

                <div class="group">
                    <label>Session Date</label>
                    <input type="date" name="session_date" required>
                </div>

                <div class="group">
                    <label>Session Time</label>
                    <input type="time" name="session_time" required>
                </div>

                <div class="group">
                    <label>Zoom Link</label>
                    <input type="url" name="zoom_link" required>
                </div>

                <div class="group">
                    <label>Lesson Link</label>
                    <input type="url" name="lesson_link">
                </div>

                <div class="group">
                    <label>Teacher Notes</label>
                    <textarea name="teacher_notes"></textarea>
                </div>

                <button type="submit" class="submit-btn">
                    Create Session
                </button>

            </form>

        </div>

        <div class="card">

            <h2>
                Sessions List
            </h2>

            <?php if($sessions): ?>

                <?php foreach($sessions as $session): ?>

                    <div class="session">

                        <h3>
                            <?php echo e($session['title']); ?>
                        </h3>

                        <p>
                            Date:
                            <?php echo formatDate($session['session_date']); ?>
                            —
                            Time:
                            <?php echo e($session['session_time']); ?>
                        </p>

                        <p>
                            <?php echo e($session['teacher_notes'] ?? 'No notes available.'); ?>
                        </p>

                        <div class="session-actions">

                            <a
                                href="<?php echo e($session['zoom_link']); ?>"
                                target="_blank"
                                class="zoom"
                            >
                                Open Zoom
                            </a>

                            <a
                                href="attendance.php?session=<?php echo e((string)$session['id']); ?>"
                                class="attendance"
                            >
                                Attendance
                            </a>

                        </div>

                    </div>

                <?php endforeach; ?>

            <?php else: ?>

                <div class="empty">
                    Select a course and create sessions.
                    Sessions for the selected course will appear here.
                </div>

            <?php endif; ?>

        </div>

    </div>

</div>

</body>
</html>