<?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['extension_days']) && isset($_POST['reason'])) {
    $assignment_id = (int)$_POST['assignment_id'];
    $extension_days = (int)$_POST['extension_days'];
    $reason = htmlspecialchars(trim($_POST['reason']));

    // Validate inputs
    if ($extension_days <= 0 || $extension_days > 7) {
        echo json_encode(['success' => false, 'message' => 'Extension must be between 1 and 7 days']);
        exit();
    }

    if (strlen($reason) < 20) {
        echo json_encode(['success' => false, 'message' => 'Please provide a detailed reason (at least 20 characters)']);
        exit();
    }

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

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

    $student_id = $student->studentID;

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

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

    // Check if assignment allows late submission
    if (!$assignment->allow_late_submission) {
        echo json_encode(['success' => false, 'message' => 'This assignment does not allow extensions']);
        exit();
    }

    // Get or create submission record
    $sql = "SELECT id FROM assignment_submissions 
            WHERE assignment_id = :assignment_id AND student_id = :student_id";
    $conn->query($sql);
    $conn->bind(':assignment_id', $assignment_id);
    $conn->bind(':student_id', $student_id);
    $submission = $conn->fetchSingle();

    if (!$submission) {
        // Create a placeholder submission
        $sql = "INSERT INTO assignment_submissions (assignment_id, student_id, submission_status)
                VALUES (:assignment_id, :student_id, 'not_submitted')";
        $conn->query($sql);
        $conn->bind(':assignment_id', $assignment_id);
        $conn->bind(':student_id', $student_id);
        $conn->execute();
        $submission_id = $conn->lastInserted();
    } else {
        $submission_id = $submission->id;
    }

    // Check if already requested extension
    $sql = "SELECT id, status FROM assignment_extensions 
            WHERE submission_id = :submission_id AND student_id = :student_id 
            ORDER BY id DESC LIMIT 1";
    $conn->query($sql);
    $conn->bind(':submission_id', $submission_id);
    $conn->bind(':student_id', $student_id);
    $existing = $conn->fetchSingle();

    if ($existing && $existing->status == 'pending') {
        echo json_encode(['success' => false, 'message' => 'You already have a pending extension request']);
        exit();
    }

    if ($existing && $existing->status == 'approved') {
        echo json_encode(['success' => false, 'message' => 'You already have an approved extension for this assignment']);
        exit();
    }

    // Request extension
    $result = $assignment_mgr->requestExtension($submission_id, $student_id, $extension_days, $reason);

    echo json_encode($result);
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
}

