<?php
declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| Course Materials 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 = flash('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();
}

/*
|--------------------------------------------------------------------------
| Manage Materials
|--------------------------------------------------------------------------
*/
if (isPost()) {
    $action = (string)($_POST['action'] ?? '');

    if ($action === 'delete_material') {
        try {
            $materialId = (int)($_POST['material_id'] ?? 0);
            $material = safeFetch(
                $pdo,
                'SELECT m.* FROM core_materials m INNER JOIN core_courses c ON c.id=m.course_id WHERE m.id=? AND c.teacher_id=? LIMIT 1',
                [$materialId, (int)$teacher['id']]
            );
            if (!$material) {
                throw new RuntimeException('Material not found.');
            }
            mustExecute($pdo, 'DELETE FROM core_materials WHERE id=?', [$materialId]);
            $storedPath = trim((string)($material['file_path'] ?? ''));
            if ($storedPath !== '' && str_starts_with($storedPath, 'uploads/materials/')) {
                $absolute = ROOT_PATH . '/' . $storedPath;
                $realUploads = realpath(UPLOADS_PATH);
                $realFile = realpath($absolute);
                if ($realUploads && $realFile && str_starts_with($realFile, $realUploads . DIRECTORY_SEPARATOR) && is_file($realFile)) {
                    @unlink($realFile);
                }
            }
            logActivity($pdo,'teacher',(int)$teacher['id'],'Material deleted','Deleted material ID '.$materialId,null,(int)$material['course_id']);
            flash('success','Material deleted successfully.');
            redirect('teacher/materials.php');
        } catch (Throwable $e) {
            error_log('[SMI teacher material delete] '.$e->getMessage());
            $error = APP_DEBUG ? $e->getMessage() : $e->getMessage();
        }
    }

    if ($action === 'upload_material') {
        $courseId = (int)($_POST['course_id'] ?? 0);
        $title = trim((string)($_POST['title'] ?? ''));
        $description = trim((string)($_POST['description'] ?? ''));
        $materialType = (string)($_POST['material_type'] ?? 'other');
        $externalLink = trim((string)($_POST['external_link'] ?? ''));
        $allowedTypes = ['book','pdf','video','link','audio','other'];
        $course = safeFetch($pdo,'SELECT id FROM core_courses WHERE id=? AND teacher_id=? LIMIT 1',[$courseId,(int)$teacher['id']]);

        if (!$course) {
            $error = 'Invalid course selected.';
        } elseif ($title === '' || !in_array($materialType,$allowedTypes,true)) {
            $error = 'Enter a title and choose a valid material type.';
        } elseif ($externalLink !== '' && !filter_var($externalLink,FILTER_VALIDATE_URL)) {
            $error = 'External link is invalid.';
        } else {
            $filePath = null;
            $hasUpload = !empty($_FILES['material_file']['name']);
            if ($hasUpload) {
                $filePath = uploadFile($_FILES['material_file'],'materials');
                if (!$filePath) {
                    $error = 'The uploaded file was rejected. Check its type and size.';
                }
            }
            if ($error === '' && !$filePath && $externalLink === '') {
                $error = 'Upload a file or provide an external link.';
            }
            if ($error === '') {
                try {
                    mustExecute(
                        $pdo,
                        "INSERT INTO core_materials (course_id,teacher_id,title,description,material_type,material_url,file_path,external_link,is_active,status,created_at) VALUES (?,?,?,?,?,?,?,?,1,'active',NOW())",
                        [$courseId,(int)$teacher['id'],$title,$description?:null,$materialType,$externalLink?:null,$filePath,$externalLink?:null]
                    );
                    logActivity($pdo,'teacher',(int)$teacher['id'],'Material uploaded','Uploaded course material: '.$title,null,$courseId);
                    flash('success','Material uploaded successfully.');
                    redirect('teacher/materials.php');
                } catch (Throwable $e) {
                    if ($filePath) {
                        @unlink(ROOT_PATH . '/' . $filePath);
                    }
                    error_log('[SMI teacher material upload] '.$e->getMessage());
                    $error = APP_DEBUG ? $e->getMessage() : 'Failed to upload material.';
                }
            }
        }
    }
}

/*
|--------------------------------------------------------------------------
| Materials
|--------------------------------------------------------------------------
*/

$materials = [];

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

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

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

    $materials =
        $materialStmt->fetchAll();
}

?>

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

<head>

<meta charset="UTF-8">

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

<title>
Course Materials
</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,#2563eb,#1e3a8a);
    color:#fff;
    border-radius:34px;
    padding:40px;
    margin-bottom:30px;
}

.hero h1{
    font-size:42px;
    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: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 #bfdbfe;
    font-family:inherit;
    font-size:15px;
}

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

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

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

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

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

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

.action-btn{
    display:inline-block;
    margin-top:14px;
    text-decoration:none;
    background:#2563eb;
    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">
            Course Materials
        </h1>

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

    </div>

    <div class="hero">

        <h1>
            Learning Materials
        </h1>

        <p>
            Upload books,
            PDFs,
            lesson files,
            external links,
            and all course materials
            for students.
        </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>
                Upload Material
            </h2>

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

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

                <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>
                        Material Title
                    </label>

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

                </div>

                <div class="group">

                    <label>
                        Material Type
                    </label>

                    <select
                    name="material_type"
                    required>

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

                        <option value="pdf">
                            PDF
                        </option>

                        <option value="book">
                            Book
                        </option>

                        <option value="worksheet">
                            Worksheet
                        </option>

                        <option value="video">
                            Video
                        </option>

                        <option value="link">
                            External Link
                        </option>

                    </select>

                </div>

                <div class="group">

                    <label>
                        Upload File
                    </label>

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

                </div>

                <div class="group">

                    <label>
                        External Link
                    </label>

                    <input
                    type="url"
                    name="external_link">

                </div>

                <div class="group">

                    <label>
                        Description
                    </label>

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

                </div>

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

                    Upload Material

                </button>

            </form>

        </div>

        <div class="card">

            <h2>
                Materials List
            </h2>

            <?php if($materials): ?>

                <?php foreach($materials as $material): ?>

                    <div class="material-card">

                        <h3>

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

                        </h3>

                        <p>

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

                        </p>

                        <p>

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

                        </p>

                        <div class="badge">

                            <?php
                            echo strtoupper(
                                $material['material_type']
                            );
                            ?>

                        </div>

                        <br>

                        <?php if(!empty($material['file_path'])): ?>

                            <a
                            href="../<?php echo e($material['file_path']); ?>"
                            target="_blank"
                            class="action-btn">

                                Open File

                            </a>

                        <?php endif; ?>

                        <?php if(!empty($material['external_link'])): ?>

                            <a
                            href="<?php echo e($material['external_link']); ?>"
                            target="_blank"
                            class="action-btn">

                                Open Link

                            </a>

                        <?php endif; ?>

                        <form method="post" style="margin-top:12px" onsubmit="return confirm('Delete this material?')">
                            <?php echo csrfField(); ?>
                            <input type="hidden" name="action" value="delete_material">
                            <input type="hidden" name="material_id" value="<?php echo (int)$material['id']; ?>">
                            <button type="submit" class="btn btn-danger" style="border:0;background:#fee2e2;color:#991b1b">Delete</button>
                        </form>

                    </div>

                <?php endforeach; ?>

            <?php else: ?>

                <div class="empty">

                    No materials uploaded yet.

                </div>

            <?php endif; ?>

        </div>

    </div>

</div>

</body>
</html>