<?php
declare(strict_types=1);

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

/*
|--------------------------------------------------------------------------
| Add Vocabulary
|--------------------------------------------------------------------------
*/

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

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

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

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

    $exampleSentence =
        trim($_POST['example_sentence'] ?? '');

    $difficulty =
        trim($_POST['difficulty'] ?? 'medium');

    $cognitiveWeight =
        (int)($_POST['cognitive_weight'] ?? 1);

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

    $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 ($word === '' || $meaning === '') {
        $error = 'Please complete all required fields.';
    }
    elseif (!in_array($difficulty, ['easy','medium','hard'], true)) {
        $error = 'Invalid difficulty level.';
    }
    elseif ($cognitiveWeight < 1 || $cognitiveWeight > 10) {
        $error = 'Cognitive weight must be between 1 and 10.';
    }
    else {

        try {

            $insertStmt = $pdo->prepare("
                INSERT INTO core_vocabulary (
                    course_id,
                    teacher_id,
                    word,
                    meaning,
                    example_sentence,
                    difficulty,
                    cognitive_weight,
                    created_at
                )
                VALUES (
                    ?, ?, ?, ?, ?, ?, ?, ?
                )
            ");

            $insertStmt->execute([
                $courseId,
                $teacher['id'],
                $word,
                $meaning,
                $exampleSentence,
                $difficulty,
                $cognitiveWeight,
                now()
            ]);

            logActivity(
                $pdo,
                'teacher',
                (int)$teacher['id'],
                'Vocabulary Added',
                'Added vocabulary word: ' . $word
            );

            $success =
                'Vocabulary added successfully.';

        } catch(Throwable $e) {

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

            $error =
                'Failed to add vocabulary.';
        }
    }
}

/*
|--------------------------------------------------------------------------
| Vocabulary List
|--------------------------------------------------------------------------
*/

$vocabularyList = [];

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

    $vocabStmt = $pdo->prepare("
        SELECT
            v.*,
            c.title AS course_title
        FROM core_vocabulary v
        INNER JOIN core_courses c
            ON c.id = v.course_id
        WHERE v.teacher_id = ?
        ORDER BY v.id DESC
    ");

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

    $vocabularyList =
        $vocabStmt->fetchAll();
}

?>

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

<head>

<meta charset="UTF-8">

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

<title>
Vocabulary 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,#059669,#047857);
    color:#fff;
    border-radius:34px;
    padding:40px;
    margin-bottom:30px;
}

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

.hero p{
    color:#d1fae5;
    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 #a7f3d0;
    font-family:inherit;
    font-size:15px;
}

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

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

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

.word-card h3{
    font-size:26px;
    margin-bottom:10px;
    font-weight:900;
}

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

.badge{
    display:inline-block;
    margin-top:12px;
    background:#d1fae5;
    color:#047857;
    padding:10px 14px;
    border-radius:999px;
    font-size:12px;
    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">
            Vocabulary System
        </h1>

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

    </div>

    <div class="hero">

        <h1>
            Cognitive Vocabulary Training
        </h1>

        <p>
            Add vocabulary packs,
            organize cognitive difficulty,
            and build intelligent vocabulary systems
            connected to the course.
        </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>
                Add Vocabulary
            </h2>

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

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

                <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>
                        Word
                    </label>

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

                </div>

                <div class="group">

                    <label>
                        Meaning
                    </label>

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

                </div>

                <div class="group">

                    <label>
                        Example Sentence
                    </label>

                    <textarea
                    name="example_sentence"></textarea>

                </div>

                <div class="group">

                    <label>
                        Difficulty
                    </label>

                    <select
                    name="difficulty">

                        <option value="easy">
                            Easy
                        </option>

                        <option value="medium">
                            Medium
                        </option>

                        <option value="hard">
                            Hard
                        </option>

                        <option value="elite">
                            Elite
                        </option>

                    </select>

                </div>

                <div class="group">

                    <label>
                        Cognitive Weight
                    </label>

                    <input
                    type="number"
                    name="cognitive_weight"
                    value="1">

                </div>

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

                    Add Vocabulary

                </button>

            </form>

        </div>

        <div class="card">

            <h2>
                Vocabulary List
            </h2>

            <?php if($vocabularyList): ?>

                <?php foreach($vocabularyList as $word): ?>

                    <div class="word-card">

                        <h3>

                            <?php echo e($word['word']); ?>

                        </h3>

                        <p>

                            Meaning:
                            <?php echo e($word['meaning']); ?>

                        </p>

                        <p>

                            Example:
                            <?php
                            echo e(
                                $word['example_sentence']
                                ?? 'No example available.'
                            );
                            ?>

                        </p>

                        <p>

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

                        </p>

                        <div class="badge">

                            <?php
                            echo ucfirst(
                                $word['difficulty']
                            );
                            ?>

                            —
                            Weight:
                            <?php
                            echo e(
                                (string)$word['cognitive_weight']
                            );
                            ?>

                        </div>

                    </div>

                <?php endforeach; ?>

            <?php else: ?>

                <div class="empty">

                    No vocabulary added yet.

                </div>

            <?php endif; ?>

        </div>

    </div>

</div>

</body>
</html>