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

$conn = new Database();
$assignment = new Assignment();

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

if (isset($_POST['add_assignment'])) {
    // Sanitize inputs
    $title = htmlspecialchars(trim($_POST['title']));
    $description = htmlspecialchars(trim($_POST['description']));
    $instructions = htmlspecialchars(trim($_POST['instructions']));
    $class_id = (int)$_POST['class'];
    $section_id = (int)$_POST['section'];
    $subject_id = (int)$_POST['subject'];
    $due_date = $_POST['due_date'];
    $total_marks = (int)$_POST['total_marks'];
    $assignment_type = $_POST['assignment_type'];
    $status = $_POST['status'];
    $allow_late = isset($_POST['allow_late']) ? 1 : 0;
    $late_days = isset($_POST['late_days']) ? (int)$_POST['late_days'] : 0;

    $created_by = $_SESSION['teacher'];
    $creator_type = 'teacher';


    $attachment_url = null;

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

    // Validate total marks
    if ($total_marks <= 0) {
        echo '<div class="alert alert-danger">
                <i class="fas fa-exclamation-triangle"></i> Total marks must be greater than 0
              </div>';
        exit();
    }

    // Validate due date
    $due_datetime = DateTime::createFromFormat('Y-m-d H:i', $due_date);
    if (!$due_datetime) {
        echo '<div class="alert alert-danger">
                <i class="fas fa-exclamation-triangle"></i> Invalid date format
              </div>';
        exit();
    }

    $now = new DateTime();
    if ($due_datetime <= $now) {
        echo '<div class="alert alert-danger">
                <i class="fas fa-exclamation-triangle"></i> Due date must be in the future
              </div>';
        exit();
    }

    // Handle file upload
    if (isset($_FILES['attachment']) && $_FILES['attachment']['error'] === UPLOAD_ERR_OK) {
        $file = $_FILES['attachment'];
        $file_name = $file['name'];
        $file_tmp = $file['tmp_name'];
        $file_size = $file['size'];
        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

        // Validate file type
        $allowed_extensions = ['pdf', 'doc', 'docx', 'txt', 'xls', 'xlsx', 'ppt', 'pptx', 'jpg', 'jpeg', 'png', 'gif'];

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

        // Validate file size (max 25MB)
        if ($file_size > 25 * 1024 * 1024) {
            echo '<div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle"></i> File size exceeds maximum limit of 25MB
                  </div>';
            exit();
        }

        // Create upload directory
        $upload_dir = '../uploads/assignments/';
        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)) {
            $attachment_url = 'uploads/assignments/' . $new_filename;
        } else {
            echo '<div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle"></i> Failed to upload file
                  </div>';
            exit();
        }
    }

    // Prepare data for insertion
    $data = [
        'title' => $title,
        'description' => $description,
        'instructions' => $instructions,
        'class_id' => $class_id,
        'section_id' => $section_id,
        'subject_id' => $subject_id,
        'created_by' => $created_by,
        'creator_type' => $creator_type,
        'due_date' => $due_date,
        'total_marks' => $total_marks,
        'assignment_type' => $assignment_type,
        'status' => $status,
        'allow_late_submission' => $allow_late,
        'late_submission_days' => $late_days,
        'attachment_url' => $attachment_url
    ];


    // Create assignment
    $result = $assignment->createAssignment($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 ($attachment_url && file_exists('../' . $attachment_url)) {
            unlink('../' . $attachment_url);
        }
        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>';
}