<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/admin-auth.php';

$pdo = db();
requireAdmin();

if (isPost()) { requireCsrf(); }

$success = flash('success') ?: '';
$error = '';
$admin = currentAdmin($pdo);
if(isPost()){$action=(string)($_POST['action']??'');try{
 if($action==='delete'){$id=(int)($_POST['delete_id']??0);$material=safeFetch($pdo,'SELECT * FROM core_materials WHERE id=?',[$id]);if(!$material)throw new RuntimeException('Material not found.');mustExecute($pdo,'DELETE FROM core_materials WHERE id=?',[$id]);$path=trim((string)($material['file_path']??''));if($path!==''&&str_starts_with($path,'uploads/materials/')){$file=realpath(ROOT_PATH.'/'.$path);$uploads=realpath(UPLOADS_PATH);if($file&&$uploads&&str_starts_with($file,$uploads.DIRECTORY_SEPARATOR)&&is_file($file))@unlink($file);}logActivity($pdo,'admin',(int)($admin['id']??0),'Material deleted','Material ID '.$id,null,(int)$material['course_id']);flash('success','Material deleted.');redirect('admin/materials.php');}
 if($action==='create'){$courseId=(int)($_POST['course_id']??0);$title=trim((string)($_POST['title']??''));$description=trim((string)($_POST['description']??''));$type=(string)($_POST['material_type']??'other');$link=trim((string)($_POST['external_link']??''));$status=(string)($_POST['status']??'active');$course=safeFetch($pdo,'SELECT id,teacher_id FROM core_courses WHERE id=?',[$courseId]);if(!$course||$title===''||!in_array($type,['book','pdf','video','link','audio','other'],true)||!in_array($status,['active','inactive'],true))throw new RuntimeException('Select a course and enter valid material details.');if($link!==''&&!filter_var($link,FILTER_VALIDATE_URL))throw new RuntimeException('External link is invalid.');$file=null;if(!empty($_FILES['material_file']['name'])){$file=uploadFile($_FILES['material_file'],'materials');if(!$file)throw new RuntimeException('The uploaded file was rejected.');}if(!$file&&$link==='')throw new RuntimeException('Upload a file or provide an external link.');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 (?,?,?,?,?,?,?,?,?,?,NOW())',[$courseId,(int)$course['teacher_id'],$title,$description?:null,$type,$link?:null,$file,$link?:null,$status==='active'?1:0,$status]);}catch(Throwable $e){if($file)@unlink(ROOT_PATH.'/'.$file);throw $e;}logActivity($pdo,'admin',(int)($admin['id']??0),'Material created','Created material: '.$title,null,$courseId);flash('success','Material created.');redirect('admin/materials.php');}
 }catch(Throwable $e){error_log('[SMI admin materials] '.$e->getMessage());$error=APP_DEBUG?$e->getMessage():$e->getMessage();}}

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

$courses = [];

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

    $courses = $pdo->query("
        SELECT id, title
        FROM core_courses
        ORDER BY id DESC
    ")->fetchAll();
}

/*
|--------------------------------------------------------------------------
| Teachers
|--------------------------------------------------------------------------
*/

$teachers = [];

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

    $teachers = $pdo->query("
        SELECT
            id,
            full_name,
            name,
            email
        FROM core_teachers
        ORDER BY id DESC
    ")->fetchAll();
}

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

$materials = [];

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

    $stmt = $pdo->query("
        SELECT

            m.*,

            c.title AS course_title,

            t.full_name AS teacher_full_name,
            t.name AS teacher_name

        FROM core_materials m

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

        LEFT JOIN core_teachers t
            ON t.id = m.teacher_id

        ORDER BY m.id DESC
    ");

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

?>

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

<meta charset="UTF-8">

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

<title>
Materials Management
</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:#f1f5f9;
    color:#0f172a;
}

.page{
    padding:34px;
}

.topbar{
    display:flex;
    justify-content:space-between;
    align-items:center;
    margin-bottom:30px;
}

.page-title{
    font-size:42px;
    font-weight:900;
}

.back-btn{
    background:#dbeafe;
    color:#1d4ed8;
    text-decoration:none;
    padding:14px 20px;
    border-radius:18px;
    font-weight:900;
}

.grid{
    display:grid;
    grid-template-columns:420px 1fr;
    gap:26px;
}

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

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

.form-group{
    margin-bottom:18px;
}

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

.form-control{
    width:100%;
    padding:16px;
    border-radius:18px;
    border:1px solid #cbd5e1;
}

textarea.form-control{
    min-height:120px;
}

.submit-btn{
    width:100%;
    border:none;

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

    color:#fff;

    padding:18px;

    border-radius:20px;

    font-weight:900;

    cursor:pointer;
}

.table-wrap{
    overflow:auto;
}

table{
    width:100%;
    border-collapse:collapse;
}

th{
    background:#f8fafc;

    padding:18px;

    text-align:left;

    font-size:13px;

    text-transform:uppercase;

    color:#64748b;
}

td{
    padding:18px;

    border-top:1px solid #e2e8f0;

    font-size:14px;
}

.badge{
    display:inline-block;

    padding:8px 12px;

    border-radius:999px;

    background:#ede9fe;

    color:#6d28d9;

    font-size:12px;

    font-weight:900;
}

.action-btn{
    padding:10px 14px;

    border-radius:14px;

    text-decoration:none;

    font-size:12px;

    font-weight:900;
}

.delete-btn{
    background:#fee2e2;
    color:#b91c1c;
}

.view-btn{
    background:#dbeafe;
    color:#1d4ed8;
}

.alert{
    padding:18px;

    border-radius:18px;

    margin-bottom:24px;

    font-weight:800;
}

.alert-success{
    background:#dcfce7;
    color:#166534;
}

.alert-danger{
    background:#fee2e2;
    color:#991b1b;
}

@media(max-width:1100px){

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

</style>

</head>

<body>

<div class="page">

    <div class="topbar">

        <h1 class="page-title">
            Materials Management
        </h1>

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

            ← Dashboard

        </a>

    </div>

    <?php if($success): ?>

        <div class="alert alert-success">

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

        </div>

    <?php endif; ?>

    <?php if($error): ?>

        <div class="alert alert-danger">

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

        </div>

    <?php endif; ?>

    <div class="grid">

        <div class="card">

            <h2>
                Upload Material
            </h2>

            <form
            method="POST"
            enctype="multipart/form-data">
<input type="hidden" name="action" value="create">
<?php echo csrfField(); ?>

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

                    <select
                    name="teacher_id"
                    class="form-control">

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

                        <?php foreach($teachers as $teacher): ?>

                            <option
                            value="<?php echo e((string)$teacher['id']); ?>">

                                <?php
                                echo e(
                                    $teacher['full_name']
                                    ?? $teacher['name']
                                    ?? $teacher['email']
                                );
                                ?>

                            </option>

                        <?php endforeach; ?>

                    </select>

                </div>

                <div class="form-group">

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

                    <select
                    name="material_type"
                    class="form-control">

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

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

                        <option value="audio">
                            Audio
                        </option>

                        <option value="shadowing">
                            Shadowing
                        </option>

                        <option value="obstacles">
                            Obstacles
                        </option>

                    </select>

                </div>

                <div class="form-group">

                    <label>
                        Upload File
                    </label>

                    <input
                    type="file"
                    name="material_file"
                    class="form-control">

                </div>

                <div class="form-group">

                    <label>
                        External Link
                    </label>

                    <input
                    type="url"
                    name="external_link"
                    class="form-control">

                </div>

                <div class="form-group">

                    <label>
                        Status
                    </label>

                    <select
                    name="status"
                    class="form-control">

                        <option value="active">
                            Active
                        </option>

                        <option value="hidden">
                            Hidden
                        </option>

                    </select>

                </div>

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

                    Upload Material

                </button>

            </form>

        </div>

        <div class="card">

            <h2>
                Materials List
            </h2>

            <div class="table-wrap">

                <table>

                    <thead>

                        <tr>

                            <th>Title</th>
                            <th>Course</th>
                            <th>Teacher</th>
                            <th>Type</th>
                            <th>File</th>
                            <th>Status</th>
                            <th>Action</th>

                        </tr>

                    </thead>

                    <tbody>

                    <?php if($materials): ?>

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

                            <tr>

                                <td>

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

                                </td>

                                <td>

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

                                </td>

                                <td>

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

                                </td>

                                <td>

                                    <span class="badge">

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

                                    </span>

                                </td>

                                <td>

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

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

                                            Open

                                        </a>

                                    <?php endif; ?>

                                </td>

                                <td>

                                    <?php
echo e(
    ucfirst(
        (string)($row['status'] ?? 'active')
    )
);
?>

                                </td>

                                <td>

                                    <form method="post" style="display:inline" onsubmit="return confirm('Delete this material?')">
<?php echo csrfField(); ?>
<input type="hidden" name="action" value="delete">
<input type="hidden" name="delete_id" value="<?php echo e((string)$row['id']); ?>">
<button type="submit" class="action-btn delete-btn">Delete</button>
</form>

                                </td>

                            </tr>

                        <?php endforeach; ?>

                    <?php else: ?>

                        <tr>

                            <td colspan="7">

                                No materials found.

                            </td>

                        </tr>

                    <?php endif; ?>

                    </tbody>

                </table>

            </div>

        </div>

    </div>

</div>

</body>
</html>