<?php
declare(strict_types=1);

define('APP_ROOT', dirname(__DIR__));

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once APP_ROOT . '/includes/lecturer_auth.php';
require_once APP_ROOT . '/includes/db.php';

header('Content-Type: application/json; charset=utf-8');

$mysqli = $mysqli ?? ($conn ?? null);

if (!$mysqli instanceof mysqli) {
    echo json_encode(['ok' => false, 'message' => 'DB connection failed']);
    exit;
}

$submission_id = (int)($_POST['submission_id'] ?? 0);
$score         = trim((string)($_POST['score'] ?? ''));
$status        = trim((string)($_POST['workflow_status'] ?? 'graded_provisional'));
$feedback      = trim((string)($_POST['feedback'] ?? ''));

if ($submission_id <= 0 || empty($_FILES['pdf']['tmp_name'])) {
    echo json_encode(['ok' => false, 'message' => 'Invalid request']);
    exit;
}

$allowedStatuses = [
    'submitted',
    'under_review',
    'needs_correction',
    'graded_provisional',
    'marked'
];

if (!in_array($status, $allowedStatuses, true)) {
    $status = 'graded_provisional';
}

$dir = APP_ROOT . '/uploads/corrected_submissions';

if (!is_dir($dir)) {
    @mkdir($dir, 0775, true);
}

if (!is_writable($dir)) {
    echo json_encode(['ok' => false, 'message' => 'Upload folder is not writable']);
    exit;
}

$name = date('Ymd_His') . '_LECT_MARKED_SUB' . $submission_id . '_' . bin2hex(random_bytes(4)) . '.pdf';
$dest = $dir . '/' . $name;

if (!move_uploaded_file($_FILES['pdf']['tmp_name'], $dest)) {
    echo json_encode(['ok' => false, 'message' => 'Upload failed']);
    exit;
}

$path = 'uploads/corrected_submissions/' . $name;
$scoreVal = ($score === '') ? null : (float)$score;
$lecturerId = (int)($_SESSION['lecturer_id'] ?? $_SESSION['user_id'] ?? $_SESSION['id'] ?? 0);

$stmt = $mysqli->prepare("
    UPDATE lms_submissions
    SET final_score = ?,
        feedback = ?,
        workflow_status = ?,
        corrected_file_path = ?,
        corrected_original_name = ?,
        marked_at = NOW(),
        marked_by = ?
    WHERE id = ?
");

if (!$stmt) {
    echo json_encode(['ok' => false, 'message' => 'SQL prepare failed: ' . $mysqli->error]);
    exit;
}

$stmt->bind_param(
    'dssssii',
    $scoreVal,
    $feedback,
    $status,
    $path,
    $name,
    $lecturerId,
    $submission_id
);

$stmt->execute();

if ($stmt->errno) {
    echo json_encode(['ok' => false, 'message' => 'SQL execute failed: ' . $stmt->error]);
    $stmt->close();
    exit;
}

$stmt->close();

echo json_encode([
    'ok' => true,
    'path' => $path
]);

exit;