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

//header('Content-Type: application/json');

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

if (!isset($_SESSION['student'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

if (isset($_POST['assignment_id']) && isset($_POST['student_id'])) {
    $assignment_id = (int)$_POST['assignment_id'];
    $student_id = (int)$_POST['student_id'];
    $submission_text = isset($_POST['submission_text']) ? htmlspecialchars(trim($_POST['submission_text'])) : '';

    // Verify student
    $sql = "SELECT studentID FROM student WHERE username = :username";
    $conn->query($sql);
    $conn->bind(':username', $_SESSION['student']);
    $student = $conn->fetchSingle();

    if (!$student || $student->studentID != $student_id) {
        echo json_encode(['success' => false, 'message' => 'Invalid student']);
        exit();
    }

    // Get assignment details
    $assignment = $assignment_mgr->getAssignmentById($assignment_id);

    if (!$assignment) {
        echo json_encode(['success' => false, 'message' => 'Assignment not found']);
        exit();
    }

    // Check if assignment is published
    if ($assignment->status != 'published') {
        echo json_encode(['success' => false, 'message' => 'Assignment is not available']);
        exit();
    }

    // Check due date
    $now = new DateTime();
    $due_date = new DateTime($assignment->due_date);
    $is_overdue = $now > $due_date;

    if ($is_overdue && !$assignment->allow_late_submission) {
        echo json_encode(['success' => false, 'message' => 'Assignment deadline has passed']);
        exit();
    }

    // Check late submission days
    if ($is_overdue && $assignment->allow_late_submission) {
        $late_deadline = clone $due_date;
        $late_deadline->modify('+' . $assignment->late_submission_days . ' days');

        if ($now > $late_deadline) {
            echo json_encode(['success' => false, 'message' => 'Late submission period has ended']);
            exit();
        }
    }

    // Validate submission content
    if (empty($submission_text) && (!isset($_FILES['submission_files']) || empty($_FILES['submission_files']['name'][0]))) {
        echo json_encode(['success' => false, 'message' => 'Please provide either text response or upload files']);
        exit();
    }

    $file_path = null;
    $submission_files = [];

    // Handle file uploads
    if (isset($_FILES['submission_files']) && !empty($_FILES['submission_files']['name'][0])) {
        $upload_dir = '../../uploads/submissions/';
        if (!file_exists($upload_dir)) {
            mkdir($upload_dir, 0755, true);
        }

        $total_files = count($_FILES['submission_files']['name']);

        for ($i = 0; $i < $total_files; $i++) {
            if ($_FILES['submission_files']['error'][$i] === UPLOAD_ERR_OK) {
                $file_name = $_FILES['submission_files']['name'][$i];
                $file_tmp = $_FILES['submission_files']['tmp_name'][$i];
                $file_size = $_FILES['submission_files']['size'][$i];
                $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', 'zip'];

                if (!in_array($file_ext, $allowed_extensions)) {
                    echo json_encode(['success' => false, 'message' => 'Invalid file type: ' . $file_name]);
                    exit();
                }

                // Validate file size (max 10MB per file)
                if ($file_size > 10 * 1024 * 1024) {
                    echo json_encode(['success' => false, 'message' => 'File too large: ' . $file_name . ' (max 10MB)']);
                    exit();
                }

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

                // Move uploaded file
                if (move_uploaded_file($file_tmp, $upload_path)) {
                    $submission_files[] = [
                        'path' => 'uploads/submissions/' . $new_filename,
                        'name' => $file_name,
                        'size' => round($file_size / 1024 / 1024, 2) . ' MB'
                    ];

                    // Set first file as main submission file for backward compatibility
                    if ($i == 0) {
                        $file_path = 'uploads/submissions/' . $new_filename;
                    }
                } else {
                    echo json_encode(['success' => false, 'message' => 'Failed to upload file: ' . $file_name]);
                    exit();
                }
            }
        }
    }

    // Prepare submission data
    $submission_data = [
        'text' => $submission_text,
        'file' => $file_path
    ];

    // Submit assignment
    $result = $assignment_mgr->submitAssignment($assignment_id, $student_id, $submission_data);

    if ($result['success']) {
        $submission_id = $result['submission_id'];

        // Add additional files if any
        if (!empty($submission_files) && count($submission_files) > 0) {
            foreach ($submission_files as $file) {
                $assignment_mgr->addSubmissionFile($submission_id, $file['path'], $file['name'], $file['size']);
            }
        }

        echo json_encode($result);
    } else {
        // Delete uploaded files if submission failed
        if (!empty($submission_files)) {
            foreach ($submission_files as $file) {
                if (file_exists('../../' . $file['path'])) {
                    unlink('../../' . $file['path']);
                }
            }
        }
        echo json_encode($result);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
}
