<?php
session_start();
//require_once 'includes/config.php';
require_once 'includes/database.php';
require_once 'Classes/Elearning.php';

$conn = new Database();
$elearning = new ELearning();

if (!isset($_SESSION['username'])) {
    echo '<div class="alert alert-danger">Unauthorized access</div>';
    exit();
}

// Check if form is submitted either via POST or via AJAX with add_material parameter
if (isset($_POST['add_material']) || (isset($_POST) && !empty($_POST) && isset($_POST['title']))) {
    // Sanitize inputs
    $title = htmlspecialchars(trim($_POST['title']));
    $description = htmlspecialchars(trim($_POST['description']));
    $material_type = $_POST['material_type'];
    $class_id = (int)$_POST['class'];
    $section_id = (int)$_POST['section'];
    $subject_id = (int)$_POST['subject'];
    $term_id = (int)$_POST['term'];
    $status = $_POST['status'];
    $duration = isset($_POST['duration']) ? trim($_POST['duration']) : null;
    $external_link = isset($_POST['external_link']) ? trim($_POST['external_link']) : null;

    $uploaded_by = $_SESSION['username'];
    $uploader_type = $elearning->checkUserType($uploaded_by) ?? 'admin';

    $file_path = null;
    $file_size = null;
    $new_file_path = null;

    // Validate required fields
    if (empty($title) || empty($class_id) || empty($section_id) || empty($subject_id) || empty($term_id)) {
        echo '<div class="alert alert-danger">
                <i class="fas fa-exclamation-triangle"></i> Please fill all required fields
              </div>';
        exit();
    }

    // Handle file upload for non-link types
    if ($material_type !== 'link') {
        if (!isset($_FILES['material_file']) || $_FILES['material_file']['error'] !== UPLOAD_ERR_OK) {
            echo '<div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle"></i> Please upload a file
                  </div>';
            exit();
        }

        $file = $_FILES['material_file'];
        $file_name = $file['name'];
        $file_tmp = $file['tmp_name'];
        $file_size_bytes = $file['size'];
        $file_size = round($file_size_bytes / 1024 / 1024, 2) . ' MB';
        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

        // Validate file type
        $allowed_extensions = [
            'pdf' => ['pdf'],
            'video' => ['mp4', 'avi', 'mov', 'webm'],
            'document' => ['doc', 'docx', 'txt', 'ppt', 'pptx'],
            'audio' => ['mp3', 'wav', 'ogg']
        ];

        if (!isset($allowed_extensions[$material_type]) || !in_array($file_ext, $allowed_extensions[$material_type])) {
            echo '<div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle"></i> Invalid file type for selected material type
                  </div>';
            exit();
        }

        // Validate file size
        $max_sizes = [
            'pdf' => 50 * 1024 * 1024, // 50MB
            'video' => 200 * 1024 * 1024, // 200MB
            'document' => 50 * 1024 * 1024,
            'audio' => 50 * 1024 * 1024
        ];

        if ($file_size_bytes > $max_sizes[$material_type]) {
            $max_mb = $max_sizes[$material_type] / 1024 / 1024;
            echo '<div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle"></i> File size exceeds maximum allowed size of ' . $max_mb . 'MB
                  </div>';
            exit();
        }

        // Create upload directory if it doesn't exist
        $upload_dir = '../uploads/learning_materials/';
        if (!file_exists($upload_dir)) {
            mkdir($upload_dir, 0755, true);
        }

        // Generate unique filename
        $new_filename = time() . '_' . uniqid() . '.' . $file_ext;
        $upload_path = $upload_dir . $new_filename;

        // Move uploaded file
        if (move_uploaded_file($file_tmp, $upload_path)) {
            $file_path = '../uploads/learning_materials/' . $new_filename;
            $new_file_path = 'uploads/learning_materials/' . $new_filename;
        } else {
            echo '<div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle"></i> Failed to upload file. Please try again.
                  </div>';
            exit();
        }
    } else {
        // Validate external link
        if (empty($external_link)) {
            echo '<div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle"></i> Please provide an external link
                  </div>';
            exit();
        }

        if (!filter_var($external_link, FILTER_VALIDATE_URL)) {
            echo '<div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle"></i> Please provide a valid URL
                  </div>';
            exit();
        }
    }

    // Prepare data for insertion
    $data = [
        'title' => $title,
        'description' => $description,
        'material_type' => $material_type,
        'file_path' => $new_file_path,
        'external_link' => $external_link,
        'class_id' => $class_id,
        'section_id' => $section_id,
        'subject_id' => $subject_id,
        'term_id' => $term_id,
        'uploaded_by' => $uploaded_by,
        'uploader_type' => $uploader_type,
        'file_size' => $file_size,
        'duration' => $duration,
        'status' => $status
    ];

    // Insert material
    $result = $elearning->addMaterial($data);

    if ($result['success']) {
        echo '<div class="alert alert-success">
                <i class="fas fa-check-circle"></i> ' . $result['message'] . '
              </div>';
    } else {
        // Delete uploaded file if database insertion failed
        if ($file_path && file_exists('../' . $new_file_path)) {
            unlink('../' . $new_file_path);
        }
        echo '<div class="alert alert-danger">
                <i class="fas fa-exclamation-triangle"></i> ' . $result['message'] . '
              </div>';
    }
} else {
    echo '<div class="alert alert-danger">Invalid request</div>';
}