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

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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Authentication required']);
    exit();
}

// Check if request method is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit();
}

try {
    $user_id = $_SESSION['user_id'];
    $user_role = $_SESSION['user_role'];
    
    // Only students can submit assignments
    if ($user_role !== 'student') {
        echo json_encode(['success' => false, 'message' => 'Only students can submit assignments']);
        exit();
    }
    
    // Get JSON input
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input || !isset($input['assignment_id']) || !isset($input['file_upload_id'])) {
        echo json_encode(['success' => false, 'message' => 'Missing required fields']);
        exit();
    }
    
    $assignment_id = (int)$input['assignment_id'];
    $file_upload_id = (int)$input['file_upload_id'];
    $comments = $input['comments'] ?? '';
    
    // Verify the assignment exists and is still open
    $stmt = $pdo->prepare("
        SELECT id, due_date, status 
        FROM assignments 
        WHERE id = ? AND status = 'published'
    ");
    $stmt->execute([$assignment_id]);
    $assignment = $stmt->fetch();
    
    if (!$assignment) {
        echo json_encode(['success' => false, 'message' => 'Assignment not found or not available']);
        exit();
    }
    
    // Check if due date has passed
    $current_date = new DateTime();
    $due_date = new DateTime($assignment['due_date']);
    
    if ($current_date > $due_date) {
        echo json_encode(['success' => false, 'message' => 'Assignment submission deadline has passed']);
        exit();
    }
    
    // Get student ID
    $stmt = $pdo->prepare("SELECT id FROM students WHERE user_id = ?");
    $stmt->execute([$user_id]);
    $student = $stmt->fetch();
    
    if (!$student) {
        echo json_encode(['success' => false, 'message' => 'Student record not found']);
        exit();
    }
    
    $student_id = $student['id'];
    
    // Check if student has already submitted this assignment
    $stmt = $pdo->prepare("
        SELECT id 
        FROM assignment_submissions 
        WHERE assignment_id = ? AND student_id = ?
    ");
    $stmt->execute([$assignment_id, $student_id]);
    $existing_submission = $stmt->fetch();
    
    if ($existing_submission) {
        // Update existing submission
        if ($file_upload_id > 0) {
            // If file is uploaded, update with file_upload_id
            $stmt = $pdo->prepare("
                UPDATE assignment_submissions 
                SET file_upload_id = ?, feedback = ?, submission_date = NOW(), status = 'submitted'
                WHERE id = ?
            ");
            $result = $stmt->execute([$file_upload_id, $comments, $existing_submission['id']]);
        } else {
            // If no file is uploaded, update without changing file_upload_id
            $stmt = $pdo->prepare("
                UPDATE assignment_submissions 
                SET feedback = ?, submission_date = NOW(), status = 'submitted'
                WHERE id = ?
            ");
            $result = $stmt->execute([$comments, $existing_submission['id']]);
        }
    } else {
        // Create new submission
        if ($file_upload_id > 0) {
            // If file is uploaded, insert with file_upload_id
            $stmt = $pdo->prepare("
                INSERT INTO assignment_submissions (assignment_id, student_id, file_upload_id, feedback, status)
                VALUES (?, ?, ?, ?, 'submitted')
            ");
            $result = $stmt->execute([$assignment_id, $student_id, $file_upload_id, $comments]);
        } else {
            // If no file is uploaded, insert with NULL file_upload_id
            $stmt = $pdo->prepare("
                INSERT INTO assignment_submissions (assignment_id, student_id, feedback, status)
                VALUES (?, ?, ?, 'submitted')
            ");
            $result = $stmt->execute([$assignment_id, $student_id, $comments]);
        }
    }
    
    if ($result) {
        echo json_encode(['success' => true, 'message' => 'Assignment submitted successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to submit assignment']);
    }
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error submitting assignment: ' . $e->getMessage()]);
}
?>