<?php
declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| Shadowing System
|--------------------------------------------------------------------------
*/

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

/*
|--------------------------------------------------------------------------
| 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();
}

/*
|--------------------------------------------------------------------------
| Create Shadowing Task
|--------------------------------------------------------------------------
*/

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

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

    $title =
        trim($_POST['title'] ?? '');

    $description =
        trim($_POST['description'] ?? '');

    $youtubeLink =
        trim($_POST['youtube_link'] ?? '');

    $shadowingLevel =
        (int)($_POST['shadowing_level'] ?? 1);

    $points =
        (float)($_POST['points'] ?? 5);

    /*
    |--------------------------------------------------------------------------
    | Validate
    |--------------------------------------------------------------------------
    */

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

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

    $course =
        $courseCheckStmt->fetch();

    if (!$course) {

        $error =
            'Invalid course selected.';
    }

    elseif ($title === '' || $youtubeLink === '') {
        $error = 'Please complete all required fields.';
    }
    elseif (!filter_var($youtubeLink, FILTER_VALIDATE_URL)) {
        $error = 'Video URL is invalid.';
    }
    elseif ($shadowingLevel < 1 || $shadowingLevel > 100 || $points < 0 || $points > 1000) {
        $error = 'Level or points are outside the allowed range.';
    }
    else {

        try {

            $insertStmt = $pdo->prepare("
                INSERT INTO core_shadowing (
                    course_id,
                    teacher_id,
                    title,
                    description,
                    youtube_link,
                    shadowing_level,
                    points,
                    created_at
                )
                VALUES (
                    ?, ?, ?, ?, ?, ?, ?, ?
                )
            ");

            $insertStmt->execute([
                $courseId,
                $teacher['id'],
                $title,
                $description,
                $youtubeLink,
                $shadowingLevel,
                $points,
                now()
            ]);

            logActivity(
                $pdo,
                'teacher',
                (int)$teacher['id'],
                'Shadowing Created',
                'Created shadowing task: ' . $title
            );

            $success =
                'Shadowing task created successfully.';

        } catch(Throwable $e) {

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

            $error =
                'Failed to create shadowing task.';
        }
    }
}

/*
|--------------------------------------------------------------------------
| Shadowing Tasks
|--------------------------------------------------------------------------
*/

$shadowingTasks = [];

if (tableExists($pdo, 'core_shadowing')) {

    $shadowStmt = $pdo->prepare("
        SELECT
            sh.*,
            c.title AS course_title
        FROM core_shadowing sh
        INNER JOIN core_courses c
            ON c.id = sh.course_id
        WHERE sh.teacher_id = ?
        ORDER BY sh.shadowing_level ASC
    ");

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

    $shadowingTasks =
        $shadowStmt->fetchAll();
}

?>

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

<head>

<meta charset="UTF-8">

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

<title>
Shadowing System
</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;
    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,#dc2626,#b91c1c);
    color:#fff;
    border-radius:34px;
    padding:40px;
    margin-bottom:30px;
}

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

.hero p{
    color:#fee2e2;
    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:420px 1fr;
    gap:24px;
}

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

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

.group{
    margin-bottom:20px;
}

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

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

.group textarea{
    min-height:150px;
    resize:vertical;
}

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

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

.shadow-card h3{
    font-size:24px;
    margin-bottom:12px;
    font-weight:900;
}

.shadow-card p{
    color:#64748b;
    line-height:1.9;
    margin-bottom:8px;
}

.badge{
    display:inline-block;
    margin-top:12px;
    background:#fee2e2;
    color:#dc2626;
    padding:10px 14px;
    border-radius:999px;
    font-size:12px;
    font-weight:900;
}

.youtube-btn{
    display:inline-block;
    margin-top:14px;
    text-decoration:none;
    background:#dc2626;
    color:#fff;
    padding:14px 18px;
    border-radius:16px;
    font-weight:900;
}

.empty{
    text-align:center;
    padding:60px;
    color:#64748b;
}

@media(max-width:1100px){

    .layout{
        grid-template-columns:1fr;
    }
}

@media(max-width:700px){

    .page{
        padding:20px;
    }

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

    .title{
        font-size:34px;
    }

    .hero h1{
        font-size:34px;
    }
}

</style>

</head>

<body>

<div class="page">

    <div class="topbar">

        <h1 class="title">
            Shadowing System
        </h1>

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

    </div>

    <div class="hero">

        <h1>
            YouTube Shadowing Training
        </h1>

        <p>
            Create sequential shadowing tasks.
            Students must finish each recording step
            before unlocking the next shadowing level.
        </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 Shadowing
            </h2>

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

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

                <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 e($course['title']); ?>

                            </option>

                        <?php endforeach; ?>

                    </select>

                </div>

                <div class="group">

                    <label>
                        Shadowing Title
                    </label>

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

                </div>

                <div class="group">

                    <label>
                        YouTube Link
                    </label>

                    <input
                    type="url"
                    name="youtube_link"
                    required>

                </div>

                <div class="group">

                    <label>
                        Shadowing Level
                    </label>

                    <input
                    type="number"
                    name="shadowing_level"
                    value="1"
                    required>

                </div>

                <div class="group">

                    <label>
                        Points
                    </label>

                    <input
                    type="number"
                    step="0.01"
                    name="points"
                    value="5">

                </div>

                <div class="group">

                    <label>
                        Instructions
                    </label>

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

                </div>

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

                    Create Shadowing

                </button>

            </form>

        </div>

        <div class="card">

            <h2>
                Shadowing Tasks
            </h2>

            <?php if($shadowingTasks): ?>

                <?php foreach($shadowingTasks as $task): ?>

                    <div class="shadow-card">

                        <h3>

                            Level
                            <?php echo e((string)$task['shadowing_level']); ?>

                            —
                            <?php echo e($task['title']); ?>

                        </h3>

                        <p>

                            Course:
                            <?php echo e($task['course_title']); ?>

                        </p>

                        <p>

                            <?php
                            echo e(
                                $task['description']
                                ?? 'No instructions available.'
                            );
                            ?>

                        </p>

                        <div class="badge">

                            <?php
                            echo e((string)$task['points']);
                            ?>

                            Points

                        </div>

                        <br>

                        <a
                        href="<?php echo e($task['youtube_link']); ?>"
                        target="_blank"
                        class="youtube-btn">

                            Open YouTube Video

                        </a>

                    </div>

                <?php endforeach; ?>

            <?php else: ?>

                <div class="empty">

                    No shadowing tasks created yet.

                </div>

            <?php endif; ?>

        </div>

    </div>

</div>

</body>
</html>