<?php
// Clean JSON API: return latest submission for current QP Setter session
// Ensures no HTML/errors leak into output

declare(strict_types=1);

ob_start();
header('Content-Type: application/json');
header('X-Content-Type-Options: nosniff');

try {
    require_once __DIR__ . '/../../config/config.php';
    if (session_status() !== PHP_SESSION_ACTIVE) { session_start(); }

    $staffId = $_SESSION['qps_staff_id'] ?? 0;
    $assignmentId = $_SESSION['qps_assignment_id'] ?? 0;
    if (!$staffId || !$assignmentId) {
        http_response_code(401);
        echo json_encode([ 'status' => 'error', 'message' => 'Unauthorized' ]);
        exit;
    }

    // First, check if form_data column exists
    $columnExists = false;
    try {
        $checkColumn = $pdo->query("SHOW COLUMNS FROM qp_setter_submissions LIKE 'form_data'");
        $columnExists = $checkColumn->rowCount() > 0;
    } catch (Exception $e) {
        // Column doesn't exist, we'll handle it gracefully
        $columnExists = false;
    }
    
    if ($columnExists) {
        $st = $pdo->prepare('SELECT id, assignment_id, staff_id, status, template_json, notes, form_data, created_at, updated_at
                              FROM qp_setter_submissions
                              WHERE assignment_id = ? AND staff_id = ?
                              ORDER BY id DESC LIMIT 1');
    } else {
        $st = $pdo->prepare('SELECT id, assignment_id, staff_id, status, template_json, notes, created_at, updated_at
                              FROM qp_setter_submissions
                              WHERE assignment_id = ? AND staff_id = ?
                              ORDER BY id DESC LIMIT 1');
    }
    $st->execute([$assignmentId, $staffId]);
    $row = $st->fetch(PDO::FETCH_ASSOC);

    if (!$row) {
        echo json_encode([ 'status' => 'success', 'data' => null ]);
        exit;
    }

    $tplRaw = (string)($row['template_json'] ?? '');
    $tplDecoded = html_entity_decode($tplRaw, ENT_QUOTES | ENT_HTML5, 'UTF-8');
    $notesRaw = (string)($row['notes'] ?? '');
    $notesDecoded = html_entity_decode($notesRaw, ENT_QUOTES | ENT_HTML5, 'UTF-8');
    
    // Handle form_data column if it exists
    $formDataRaw = '';
    $formDataDecoded = '';
    if ($columnExists && isset($row['form_data'])) {
        $formDataRaw = (string)($row['form_data'] ?? '');
        $formDataDecoded = html_entity_decode($formDataRaw, ENT_QUOTES | ENT_HTML5, 'UTF-8');
    }

    $parsed = isset($_GET['parsed']) || isset($_GET['format']);
    $templateArray = null;
    if ($parsed) {
        $tmp = json_decode($tplDecoded, true);
        if (json_last_error() === JSON_ERROR_NONE && is_array($tmp)) {
            $templateArray = $tmp;
        }
    }

    echo json_encode([
        'status' => 'success',
        'data' => [
            'id' => (int)$row['id'],
            'assignment_id' => (int)$row['assignment_id'],
            'staff_id' => (int)$row['staff_id'],
            'status_text' => (string)$row['status'],
            'template_json' => $tplRaw,
            'template_json_decoded' => $tplDecoded,
            'template' => $templateArray, // only if parsed flag provided and valid
            'notes' => $notesDecoded,
            'form_data' => $formDataRaw,
            'form_data_decoded' => $formDataDecoded,
            'created_at' => (string)($row['created_at'] ?? ''),
            'updated_at' => (string)($row['updated_at'] ?? ''),
        ]
    ]);
} catch (Throwable $e) {
    http_response_code(500);
    // Log the error for debugging
    error_log('get_submission.php error: ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine());
    echo json_encode([ 'status' => 'error', 'message' => 'Server error: ' . $e->getMessage() ]);
} finally {
    // Discard any buffered output that might corrupt JSON
    ob_end_flush();
}
