<?php
session_start();
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    die("Akses ditolak.");
}

require 'config/db.php';

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["scorm_file"])) {
    
    // Validasi dasar...
    $file = $_FILES["scorm_file"];
    if ($file["error"] !== UPLOAD_ERR_OK) die("Error saat upload: " . $file["error"]);
    if ($file["size"] > 100 * 1024 * 1024) die("Error: Ukuran file maks 100MB.");
    
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mime_type = $finfo->file($file["tmp_name"]);
    if ($mime_type !== "application/zip") die("Error: Format file harus .zip.");

    // Buat folder unik
    $upload_dir = "uploads/";
    $course_id = uniqid('course_');
    $course_path = $upload_dir . $course_id . "/";
    if (!mkdir($course_path, 0777, true)) die("Error: Gagal membuat direktori course.");

    $zip_path = $course_path . basename($file["name"]);
    if (!move_uploaded_file($file["tmp_name"], $zip_path)) die("Error: Gagal memindahkan file zip.");

    // Ekstrak file
    $zip = new ZipArchive;
    if ($zip->open($zip_path) !== TRUE) die("Error: Gagal membuka file zip.");
    $zip->extractTo($course_path);
    $zip->close();

    // Mencari file launch di imsmanifest.xml
    $manifest_path = $course_path . "imsmanifest.xml";
    $launch_file = '';

    if (file_exists($manifest_path)) {
        libxml_use_internal_errors(true);
        $manifest = simplexml_load_file($manifest_path);

        if ($manifest === false) {
            die("Error: Gagal memuat file imsmanifest.xml. Pastikan format XML valid.");
        }

        foreach ($manifest->resources->resource as $resource) {
            $attrs = $resource->attributes('adlcp', true);
            if (isset($attrs->scormtype) && $attrs->scormtype == 'sco') {
                $launch_file = (string)$resource['href'];
                break;
            }
        }
    }

    if (empty($launch_file)) {
        function rrmdir($dir) {
            if (is_dir($dir)) {
                $objects = scandir($dir);
                foreach ($objects as $object) {
                    if ($object != "." && $object != "..") {
                        if (is_dir($dir. DIRECTORY_SEPARATOR .$object)) rrmdir($dir. DIRECTORY_SEPARATOR .$object);
                        else unlink($dir. DIRECTORY_SEPARATOR .$object);
                    }
                }
                rmdir($dir);
            }
        }
        rrmdir($course_path);
        die("Error: Gagal menemukan file 'launch' di dalam imsmanifest.xml. Pastikan file di-zip dengan benar dan manifest valid.");
    }

    // Simpan informasi ke database
    $title = $_POST['title'];
    $description = $_POST['description'];
    $original_filename = basename($file["name"]);
    $uploader_id = $_SESSION['user_id'];
    $full_launch_url = $course_path . $launch_file;

    $stmt = $conn->prepare("INSERT INTO courses (title, description, scorm_filename, launch_url, uploader_id) VALUES (?, ?, ?, ?, ?)");
    
    // ===== INI BARIS YANG DIPERBAIKI =====
    $stmt->bind_param("ssssi", $title, $description, $original_filename, $full_launch_url, $uploader_id);
    
    if ($stmt->execute()) {
        header("Location: admin_lms.php?status=success_extract");
        exit();
    } else {
        die("Error: Gagal menyimpan data ke database. " . $stmt->error);
    }

} else {
    die("Metode tidak valid.");
}
?>