<?php
declare(strict_types=1);
require __DIR__ . '/bootstrap.php';

$user = require_user();
$course = active_course();

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'GET') {
    $stmt = db()->prepare(
        'SELECT a.assignment_slug, s.status, s.marks, s.feedback, s.submitted_at
         FROM assignment_submissions s
         JOIN assignments a ON a.id = s.assignment_id
         WHERE s.user_id = :user_id AND a.course_id = :course_id'
    );
    $stmt->execute([
        'user_id' => $user['id'],
        'course_id' => $course['id'],
    ]);
    json_response(['submissions' => $stmt->fetchAll()]);
}

require_method('POST');
$assignmentSlug = trim((string) ($_POST['assignment_id'] ?? ''));
$submissionText = trim((string) ($_POST['submission_text'] ?? ''));

if ($assignmentSlug === '') {
    json_response(['error' => 'Assignment is required.'], 422);
}

$assignmentStmt = db()->prepare(
    'SELECT id
     FROM assignments
     WHERE course_id = :course_id AND assignment_slug = :assignment_slug
     LIMIT 1'
);
$assignmentStmt->execute([
    'course_id' => $course['id'],
    'assignment_slug' => $assignmentSlug,
]);
$assignment = $assignmentStmt->fetch();
if (!$assignment) {
    json_response(['error' => 'Assignment not found.'], 404);
}

$filePath = null;
if (!empty($_FILES['submission_file']) && $_FILES['submission_file']['error'] === UPLOAD_ERR_OK) {
    $allowed = ['pdf', 'doc', 'docx', 'ppt', 'pptx', 'txt'];
    $extension = strtolower(pathinfo($_FILES['submission_file']['name'], PATHINFO_EXTENSION));
    if (!in_array($extension, $allowed, true)) {
        json_response(['error' => 'Unsupported file type.'], 422);
    }

    $uploadDir = dirname(__DIR__) . '/uploads/assignments/' . (int) $user['id'];
    if (!is_dir($uploadDir) && !mkdir($uploadDir, 0755, true) && !is_dir($uploadDir)) {
        json_response(['error' => 'Could not create upload directory.'], 500);
    }

    $safeName = bin2hex(random_bytes(12)) . '.' . $extension;
    $target = $uploadDir . '/' . $safeName;
    if (!move_uploaded_file($_FILES['submission_file']['tmp_name'], $target)) {
        json_response(['error' => 'Could not save uploaded file.'], 500);
    }
    $filePath = 'uploads/assignments/' . (int) $user['id'] . '/' . $safeName;
}

if ($submissionText === '' && $filePath === null) {
    json_response(['error' => 'Upload a file or paste assignment text.'], 422);
}

$stmt = db()->prepare(
    'INSERT INTO assignment_submissions (user_id, assignment_id, submission_text, file_path)
     VALUES (:user_id, :assignment_id, :submission_text, :file_path)
     ON CONFLICT(user_id, assignment_id)
     DO UPDATE SET
       submission_text = excluded.submission_text,
       file_path = COALESCE(excluded.file_path, assignment_submissions.file_path),
       status = "submitted",
       submitted_at = CURRENT_TIMESTAMP'
);
$stmt->execute([
    'user_id' => $user['id'],
    'assignment_id' => $assignment['id'],
    'submission_text' => $submissionText !== '' ? $submissionText : null,
    'file_path' => $filePath,
]);

json_response([
    'ok' => true,
    'certificate_status' => certificate_status((int) $user['id'], (int) $course['id']),
]);
