<?php
declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| Teacher Homework Management
|--------------------------------------------------------------------------
*/

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');
}

$success = '';
$error = '';

/*
|--------------------------------------------------------------------------
| Create Homework
|--------------------------------------------------------------------------
*/

if (isPost() && ($_POST['action'] ?? '') === 'create_homework') {
    $courseId = (int)($_POST['course_id'] ?? 0);
    $title = trim((string)($_POST['title'] ?? ''));
    $description = trim((string)($_POST['description'] ?? ''));
    $dueDate = trim((string)($_POST['due_date'] ?? ''));
    $points = max(0.5, min(1000, (float)($_POST['points'] ?? 10)));
    $weight = max(0, min(100, (float)($_POST['weight'] ?? 10)));

    $ownedCourse = safeFetch($pdo, 'SELECT id FROM core_courses WHERE id=? AND teacher_id=? LIMIT 1', [$courseId, (int)$teacher['id']]);
    if (!$ownedCourse) {
        $error = 'Invalid course selected.';
    } elseif ($title === '') {
        $error = 'Homework title is required.';
    } elseif ($dueDate !== '' && !validDate($dueDate)) {
        $error = 'Due date is invalid.';
    } else {
        try {
            mustExecute(
                $pdo,
                "INSERT INTO core_homework (course_id,teacher_id,title,description,due_date,max_points,max_score,points,weight,status,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,'active',NOW(),NOW())",
                [$courseId,(int)$teacher['id'],$title,$description?:null,$dueDate?:null,$points,$points,$points,$weight]
            );
            logActivity($pdo,'teacher',(int)$teacher['id'],'Homework created','Created homework: '.$title,null,$courseId);
            $success = 'Homework created successfully.';
        } catch (Throwable $e) {
            error_log('[SMI teacher homework] '.$e->getMessage());
            $error = APP_DEBUG ? $e->getMessage() : 'Failed to create homework.';
        }
    }
}

/*
|--------------------------------------------------------------------------
| Homework List
|--------------------------------------------------------------------------
*/

$homework = [];

$stmt = $pdo->prepare("

    SELECT
        h.*,
        c.title AS course_title

    FROM core_homework h

    LEFT JOIN core_courses c
        ON c.id = h.course_id

    WHERE h.teacher_id = ?

    ORDER BY h.id DESC

");

$stmt->execute([

    $teacher['id']

]);

$homework =
    $stmt->fetchAll();

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

$courses = [];

$stmt = $pdo->prepare("

    SELECT *
    FROM core_courses

    WHERE teacher_id = ?

    ORDER BY id DESC

");

$stmt->execute([

    $teacher['id']

]);

$courses =
    $stmt->fetchAll();

?>

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

<head>

<meta charset="UTF-8">

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

<title>
Homework Management
</title>

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

<link
rel="stylesheet"
href="../assets/css/style.css">

<style>

.hero{

    background:
    linear-gradient(
        135deg,
        #2563eb,
        #7c3aed
    );

    color:#fff;
}

.layout{

    display:grid;

    grid-template-columns:420px 1fr;

    gap:28px;
}

.form-card,
.list-card{

    background:#fff;

    border-radius:34px;

    padding:32px;

    border:1px solid #e2e8f0;

    box-shadow:
        0 18px 40px rgba(15,23,42,0.05);
}

.form-card h2,
.list-card h2{

    font-size:32px;

    margin-bottom:20px;

    font-weight:900;
}

.submit-btn{

    width:100%;

    border:none;

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

    color:#fff;

    padding:18px;

    border-radius:22px;

    font-size:16px;

    font-weight:900;

    cursor:pointer;
}

.homework-grid{

    display:grid;

    gap:22px;
}

.homework-card{

    background:#f8fafc;

    border-radius:28px;

    padding:24px;

    border:1px solid #e2e8f0;
}

.homework-card h3{

    font-size:26px;

    margin-bottom:12px;

    font-weight:900;
}

.homework-card p{

    color:#64748b;

    line-height:1.9;
}

.meta{

    display:grid;

    grid-template-columns:
        repeat(auto-fit,minmax(160px,1fr));

    gap:14px;

    margin-top:20px;
}

.meta-box{

    background:#fff;

    border-radius:18px;

    padding:16px;

    border:1px solid #e2e8f0;
}

.meta-box h4{

    font-size:12px;

    color:#64748b;

    margin-bottom:8px;

    text-transform:uppercase;
}

.meta-box p{

    font-size:18px;

    font-weight:800;

    color:#0f172a;
}

.back-btn{

    background:#fff;

    color:#2563eb;

    padding:14px 22px;

    border-radius:18px;

    font-weight:900;
}

@media(max-width:1000px){

    .layout{

        grid-template-columns:1fr;
    }
}

</style>

</head>

<body>

<div class="container page-padding">

    <div class="topbar">

        <h1 class="page-title">

            Homework Management

        </h1>

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

            ← Dashboard

        </a>

    </div>

    <div class="hero card">

        <h1 style="font-size:50px;font-weight:900;margin-bottom:16px;">

            Academic Homework System

        </h1>

        <p style="line-height:2;color:#dbeafe;max-width:850px;">

            Create assignments,
            manage homework submissions,
            and monitor academic performance
            inside the SMI Gateway.

        </p>

    </div>

    <?php if($error): ?>

        <div class="alert alert-danger">

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

        </div>

    <?php endif; ?>

    <?php if($success): ?>

        <div class="alert alert-success">

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

        </div>

    <?php endif; ?>

    <div class="layout">

        <div class="form-card">

            <h2>

                Create Homework

            </h2>

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

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

                <div class="form-group">

                    <label>
                        Course
                    </label>

                    <select
                    name="course_id"
                    class="form-control"
                    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="form-group">

                    <label>
                        Homework Title
                    </label>

                    <input
                    type="text"
                    name="title"
                    class="form-control"
                    required>

                </div>

                <div class="form-group">

                    <label>
                        Description
                    </label>

                    <textarea
                    name="description"
                    class="form-control"></textarea>

                </div>

                <div class="form-group">

                    <label>
                        Due Date
                    </label>

                    <input
                    type="date"
                    name="due_date"
                    class="form-control">

                </div>

                <div class="form-group">

                    <label>
                        Points
                    </label>

                    <input
                    type="number"
                    step="0.1"
                    name="points"
                    class="form-control"
                    value="100">

                </div>

                <div class="form-group">

                    <label>
                        Weight %
                    </label>

                    <input
                    type="number"
                    step="0.1"
                    name="weight"
                    class="form-control"
                    value="10">

                </div>

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

                    Create Homework

                </button>

            </form>

        </div>

        <div class="list-card">

            <h2>

                Homework List

            </h2>

            <div class="homework-grid">

                <?php if($homework): ?>

                    <?php foreach($homework as $row): ?>

                        <div class="homework-card">

                            <h3>

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

                            </h3>

                            <p>

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

                            </p>

                            <div class="meta">

                                <div class="meta-box">

                                    <h4>
                                        Course
                                    </h4>

                                    <p>

                                        <?php
                                        echo e(
                                            $row['course_title']
                                            ?? 'N/A'
                                        );
                                        ?>

                                    </p>

                                </div>

                                <div class="meta-box">

                                    <h4>
                                        Due Date
                                    </h4>

                                    <p>

                                        <?php
                                        echo formatDate(
                                            $row['due_date']
                                            ?? null
                                        );
                                        ?>

                                    </p>

                                </div>

                                <div class="meta-box">

                                    <h4>
                                        Points
                                    </h4>

                                    <p>

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

                                    </p>

                                </div>

                                <div class="meta-box">

                                    <h4>
                                        Weight
                                    </h4>

                                    <p>

                                        <?php
                                        echo e(
                                            (string)(
                                                $row['weight']
                                                ?? 0
                                            )
                                        );
                                        ?>%

                                    </p>

                                </div>

                            </div>

                        </div>

                    <?php endforeach; ?>

                <?php else: ?>

                    <div class="empty-state">

                        No homework created yet.

                    </div>

                <?php endif; ?>

            </div>

        </div>

    </div>

</div>

<script src="../assets/js/app.js"></script>

</body>
</html>