<?php
/* ==========================
   STUDENT SECTION (SECURE)
========================== */

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

/* ==========================
   CSRF TOKEN INIT
========================== */
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

/* ==========================
   BASIC AUTH CHECK (IMPORTANT)
   (adjust to your system)
========================== */
if (!isset($_SESSION['user_id'])) {
    die("Unauthorized access");
}

/* OPTIONAL: ROLE CHECK (RBAC LIGHT)
if ($_SESSION['role'] !== 'admin') {
    die("Access denied");
}
*/

/* ==========================
   REQUEST HANDLER
========================== */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    /* ==========================
       CSRF VALIDATION (GLOBAL)
    ========================== */
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        die("Invalid CSRF token");
    }

    /* Keep current section after refresh */
    $_SESSION['active_section'] = 'studentsSection';

    /* ==========================
       RESET PASSWORD
    ========================== */
    if (isset($_POST['reset_student_password'])) {

        $student_id = filter_input(INPUT_POST, 'student_id', FILTER_VALIDATE_INT);
        $new_password = trim($_POST['new_password'] ?? '');

        if ($student_id && strlen($new_password) >= 6 && strlen($new_password) <= 100) {

            $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);

            $stmt = $conn->prepare("
                UPDATE users
                SET password = ?
                WHERE id = ?
                LIMIT 1
            ");

            $stmt->bind_param("si", $hashed_password, $student_id);
            $stmt->execute();
            $stmt->close();

            $_SESSION['success'] = "Password updated successfully.";
        }

        header("Location: ".$_SERVER['PHP_SELF']."#studentsSection");
        exit;
    }

    /* ==========================
       STUDENT ACTION (SAFE WHITELIST)
    ========================== */
    if (isset($_POST['student_action'])) {

        $student_id = filter_input(INPUT_POST, 'student_id', FILTER_VALIDATE_INT);

        // STRICT WHITELIST (prevents tampering)
        $allowed_actions = ['activate', 'suspend', 'delete'];

        $action = $_POST['action'] ?? '';

        if ($student_id && in_array($action, $allowed_actions, true)) {

            /* ==========================
               ACTIVATE
            ========================== */
            if ($action === "activate") {

                $stmt = $conn->prepare("
                    UPDATE users
                    SET status='active'
                    WHERE id=?
                    LIMIT 1
                ");

                $stmt->bind_param("i", $student_id);
                $stmt->execute();
                $stmt->close();

                $_SESSION['success'] = "Student activated successfully.";
            }

            /* ==========================
               SUSPEND
            ========================== */
            elseif ($action === "suspend") {

                $stmt = $conn->prepare("
                    UPDATE users
                    SET status='suspended'
                    WHERE id=?
                    LIMIT 1
                ");

                $stmt->bind_param("i", $student_id);
                $stmt->execute();
                $stmt->close();

                $_SESSION['success'] = "Student suspended successfully.";
            }

            /* ==========================
               DELETE (HIGH RISK ACTION)
            ========================== */
            elseif ($action === "delete") {

                // OPTIONAL SAFETY: prevent self-delete (if admin uses same table)
                if (isset($_SESSION['user_id']) && $_SESSION['user_id'] == $student_id) {
                    die("You cannot delete your own account");
                }

                $stmt = $conn->prepare("
                    DELETE FROM users
                    WHERE id=?
                    LIMIT 1
                ");

                $stmt->bind_param("i", $student_id);
                $stmt->execute();
                $stmt->close();

                $_SESSION['success'] = "Student deleted successfully.";
            }
        }

        header("Location: ".$_SERVER['PHP_SELF']);
        exit;
    }
}



/* =========================
CREATE COURSE SECTION
/* =========================
   CSRF SETUP
========================= */
$user_id = $_SESSION['user_id'] ?? 0;
$user_role = strtolower(trim($_SESSION['role'] ?? ''));
 
if (!$user_id) {
    die("Unauthorized");
}

/* ==========================
   CSRF TOKEN
========================== */
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

/* ==========================
   HELPERS
========================== */
function isValidVideo($tmpFile) {
    $allowed = ['video/mp4', 'video/webm', 'video/ogg'];
    return in_array(mime_content_type($tmpFile), $allowed);
}

function convertDriveLink($url) {
    if (strpos($url, 'drive.google.com') !== false) {
        preg_match('/\/d\/(.*?)\//', $url, $m);
        if (!empty($m[1])) {
            return "https://drive.google.com/file/d/{$m[1]}/preview";
        }
    }
    return $url;
}

/* ==========================
   EDIT FETCH
========================== */
$editVideo = null;

if (isset($_GET['edit'])) {
    $id = (int)$_GET['edit'];

    $stmt = $conn->prepare("SELECT * FROM course_videos WHERE id=?");
    $stmt->bind_param("i", $id);
    $stmt->execute();

    $editVideo = $stmt->get_result()->fetch_assoc();
}

/* ==========================
   UPLOAD VIDEO
========================== */
if (isset($_POST['upload_video'])) {

    if (!in_array($user_role, ['admin','teacher'])) {
        die("Unauthorized");
    }

    if ($_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        die("CSRF Error");
    }

    $course_id = (int)$_POST['course_id'];
    $title = trim($_POST['title']);
    $description = trim($_POST['description']);
    $access_type = $_POST['access_type'];
    $cloud_url = trim($_POST['cloud_url']);

    $local_path = null;
    $file_size = 0;
    $mime_type = null;
    $upload_status = 'cloud';

    /* FILE UPLOAD */
    if (!empty($_FILES['video']['name'])) {

        if (!isValidVideo($_FILES['video']['tmp_name'])) {
            die("Only MP4, WEBM, OGG allowed");
        }

        $upload_dir = "uploads/videos/";

        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }

        $filename = time() . "_" . basename($_FILES['video']['name']);
        $local_path = $upload_dir . $filename;

        move_uploaded_file($_FILES['video']['tmp_name'], $local_path);

        $file_size = $_FILES['video']['size'];
        $mime_type = mime_content_type($local_path);
        $upload_status = 'local';
    }

    $stmt = $conn->prepare("
        INSERT INTO course_videos
        (course_id, title, local_path, cloud_url, upload_status, file_size, mime_type, access_type, uploaded_by, description)
        VALUES (?,?,?,?,?,?,?,?,?,?)
    ");

    $stmt->bind_param(
        "issssissis",
        $course_id,
        $title,
        $local_path,
        $cloud_url,
        $upload_status,
        $file_size,
        $mime_type,
        $access_type,
        $user_id,
        $description
    );

    $stmt->execute();

    header("Location: videos.php");
    exit;
}

/* ==========================
   UPDATE VIDEO
========================== */
if (isset($_POST['update_video'])) {

    if ($_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        die("CSRF Error");
    }

    $id = (int)$_POST['video_id'];
    $course_id = (int)$_POST['course_id'];
    $title = trim($_POST['title']);
    $description = trim($_POST['description']);
    $cloud_url = trim($_POST['cloud_url']);
    $access_type = $_POST['access_type'];

    /* NEW FILE UPLOAD */
    if (!empty($_FILES['video']['name'])) {

        $stmt = $conn->prepare("SELECT local_path FROM course_videos WHERE id=?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $old = $stmt->get_result()->fetch_assoc();

        if (!empty($old['local_path']) && file_exists($old['local_path'])) {
            unlink($old['local_path']);
        }

        if (!isValidVideo($_FILES['video']['tmp_name'])) {
            die("Invalid video file");
        }

        $upload_dir = "uploads/videos/";
        $filename = time() . "_" . basename($_FILES['video']['name']);
        $local_path = $upload_dir . $filename;

        move_uploaded_file($_FILES['video']['tmp_name'], $local_path);

        $conn->query("
            UPDATE course_videos
            SET local_path='$local_path', upload_status='local'
            WHERE id=$id
        ");
    }

    $stmt = $conn->prepare("
        UPDATE course_videos
        SET course_id=?, title=?, description=?, cloud_url=?, access_type=?
        WHERE id=?
    ");

    $stmt->bind_param("issssi", $course_id, $title, $description, $cloud_url, $access_type, $id);
    $stmt->execute();

    header("Location: videos.php");
    exit;
}

/* ==========================
   DELETE VIDEO
========================== */
if (isset($_POST['delete_video'])) {

    if ($_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        die("CSRF Error");
    }

    $id = (int)$_POST['video_id'];

    $stmt = $conn->prepare("SELECT local_path FROM course_videos WHERE id=?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $video = $stmt->get_result()->fetch_assoc();

    if (!empty($video['local_path']) && file_exists($video['local_path'])) {
        unlink($video['local_path']);
    }

    $stmt = $conn->prepare("DELETE FROM course_videos WHERE id=?");
    $stmt->bind_param("i", $id);
    $stmt->execute();

    header("Location: videos.php");
    exit;
}

/* ==========================
   VIEW VIDEO
========================== */
if (isset($_GET['view'])) {

    $id = (int)$_GET['view'];

    $stmt = $conn->prepare("SELECT * FROM course_videos WHERE id=?");
    $stmt->bind_param("i", $id);
    $stmt->execute();

    $video = $stmt->get_result()->fetch_assoc();

    if (!$video) die("Video not found");

    /* PAID ACCESS CHECK */
    if ($video['access_type'] == 'paid') {

        $check = $conn->query("
            SELECT 1 FROM enrollments
            WHERE user_id=$user_id
            AND course_id={$video['course_id']}
        ");

        if ($check->num_rows == 0 && !in_array($user_role, ['admin','teacher'])) {
            die("You are not enrolled in this course");
        }
 
     
       }       }
     
       
       error_reporting(E_ALL);
ini_set('display_errors', 1);

/* =========================
   CSRF TOKEN
========================= */
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

/* =========================
   FETCH COURSES (SAFE)
========================= */
$stmt = $conn->prepare("SELECT * FROM courses ORDER BY id DESC");
$stmt->execute();
$courses = $stmt->get_result();

/* =========================
   FETCH TEACHERS (SAFE)
========================= */
$stmt2 = $conn->prepare("SELECT id, full_name FROM users WHERE role = ?");
$role = "teacher";
$stmt2->bind_param("s", $role);
$stmt2->execute();
$teachers = $stmt2->get_result();


/* =========================
   CREATE COURSE
========================= */

if (!isset($_SESSION['course_submission_id'])) {
    $_SESSION['course_submission_id'] = '';
}

if (isset($_POST['create_course'])) {

    if (
        !isset($_POST['csrf_token']) ||
        $_POST['csrf_token'] !== $_SESSION['csrf_token']
    ) {
        die("Invalid CSRF token");
    }

    /* =========================
       PREVENT DUPLICATE SUBMIT
    ========================= */
    $submission_id = md5(
        ($_POST['title'] ?? '') .
        ($_POST['description'] ?? '') .
        ($_POST['teacher_id'] ?? '') .
        session_id()
    );

    if ($_SESSION['course_submission_id'] === $submission_id) {
        $success = "Course already saved.";
    } else {

        $title = trim($_POST['title'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $category = trim($_POST['category'] ?? '');
        $custom_category = trim($_POST['custom_category'] ?? '');
        $course_type = trim($_POST['course_type'] ?? 'Free');
        $status = trim($_POST['status'] ?? 'Active');
        $price = (float)($_POST['price'] ?? 0);
        $teacher_id = (int)($_POST['teacher_id'] ?? 0);

        /* =========================
           THUMBNAIL UPLOAD (SECURE)
        ========================= */
        $thumbnail = "";

        if (
            isset($_FILES['thumbnail']) &&
            !empty($_FILES['thumbnail']['name'])
        ) {

            $allowed = ['image/jpeg', 'image/png', 'image/webp'];
            $mime = mime_content_type($_FILES['thumbnail']['tmp_name']);

            if (!in_array($mime, $allowed)) {
                die("Invalid image type");
            }

            if ($_FILES['thumbnail']['size'] > 2 * 1024 * 1024) {
                die("Image too large");
            }

            $dir = "uploads/";

            if (!is_dir($dir)) {
                mkdir($dir, 0755, true);
            }

            $extension = match ($mime) {
                'image/jpeg' => 'jpg',
                'image/png'  => 'png',
                'image/webp' => 'webp',
                default      => 'jpg'
            };

            $fileName = time() . "_" . bin2hex(random_bytes(5)) . "." . $extension;
            $thumbnail = $dir . $fileName;

            if (!move_uploaded_file(
                $_FILES['thumbnail']['tmp_name'],
                $thumbnail
            )) {
                die("Failed to upload image");
            }
        }

        /* =========================
           INSERT COURSE (SAFE)
        ========================= */
        $stmt = $conn->prepare("
            INSERT INTO courses
            (
                title,
                description,
                category,
                custom_category,
                thumbnail,
                course_type,
                status,
                price,
                teacher_id
            )
            VALUES (?,?,?,?,?,?,?,?,?)
        ");

        $stmt->bind_param(
            "sssssssdi",
            $title,
            $description,
            $category,
            $custom_category,
            $thumbnail,
            $course_type,
            $status,
            $price,
            $teacher_id
        );

        if ($stmt->execute()) {

            /* Mark this form submission as processed */
            $_SESSION['course_submission_id'] = $submission_id;

            $success = "Course created successfully.";

        } else {

            $error = "Failed to create course.";

        }

        $stmt->close();
    }
}

/* =========================
   DELETE / ARCHIVE COURSE
========================= */
if (isset($_POST['delete_course'])) {

    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        die("Invalid CSRF token");
    }

    $id = (int)$_POST['course_id'];
    $action = $_POST['action'];

    if ($action === "delete") {

        $stmt = $conn->prepare("DELETE FROM courses WHERE id=?");
        $stmt->bind_param("i", $id);
        $stmt->execute();

    } else {

        // FIX: use valid ENUM value from DB
        $status = "Inactive";

        $stmt = $conn->prepare("UPDATE courses SET status=? WHERE id=?");
        $stmt->bind_param("si", $status, $id);
        $stmt->execute();
    }
}
?>
