<?php
// ajax/save_statements.php — v2
require_once __DIR__ . '/../config/db.php';
header('Content-Type: application/json');
startSession();

$user    = getCurrentUser();
$user_id = $user['user_id'];

$submissionId = (int)($_POST['submission_id'] ?? 0);
$data         = json_decode($_POST['data'] ?? '{}', true);

if (!$submissionId)   jsonResponse(false, 'Submission ID required');
if (!is_array($data)) jsonResponse(false, 'Invalid data');

$chk = db()->prepare("SELECT submission_id FROM submissions WHERE submission_id=? AND user_id=?");
$chk->execute([$submissionId, $user_id]);
if (!$chk->fetch()) jsonResponse(false, 'Access denied');

$db = db();

// DDL outside transaction — create table then add any missing columns
try {
    $db->exec("CREATE TABLE IF NOT EXISTS submission_statements (
        statement_id               INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        submission_id              INT UNSIGNED NOT NULL UNIQUE,
        conflict_of_interest       VARCHAR(10)  DEFAULT NULL,
        conflict_details           TEXT,
        manuscript_submission_type VARCHAR(20)  DEFAULT 'no_previous',
        manuscript_details         TEXT,
        funding_status             VARCHAR(30)  DEFAULT 'no_funding',
        funding_details            TEXT,
        funder_data                TEXT,
        generative_ai_used         TINYINT(1)   DEFAULT NULL,
        generative_ai_details      TEXT,
        ethics_compliant           TINYINT(1)   DEFAULT 0,
        studies_animals            TEXT,
        studies_humans             TEXT,
        includes_identifiable_data TEXT,
        data_availability_statement TEXT,
        animals_answers            TEXT COMMENT 'JSON: sidebar Y/N answers for animals survey',
        humans_answers             TEXT COMMENT 'JSON: sidebar Y/N answers for humans survey',
        identifiable_answers       TEXT COMMENT 'JSON: sidebar Y/N answers for identifiable survey',
        data_answers               TEXT COMMENT 'JSON: sidebar Y/N answers for data survey',
        updated_at                 DATETIME DEFAULT NOW() ON UPDATE NOW()
    )");
} catch (PDOException $e) {}

// Add any missing columns silently
$addCols = [
    'conflict_details TEXT',
    'manuscript_details TEXT',
    'funder_data TEXT',
    'animals_answers TEXT',
    'humans_answers TEXT',
    'identifiable_answers TEXT',
    'data_answers TEXT',
];
foreach ($addCols as $col) {
    try { $db->exec("ALTER TABLE submission_statements ADD COLUMN $col"); } catch(PDOException $e){}
}
// Fix ENUM columns → VARCHAR (if old schema had wrong type)
foreach ([
    "MODIFY COLUMN conflict_of_interest VARCHAR(10) DEFAULT NULL",
    "MODIFY COLUMN manuscript_submission_type VARCHAR(20) DEFAULT 'no_previous'",
    "MODIFY COLUMN funding_status VARCHAR(30) DEFAULT 'no_funding'",
] as $mod) {
    try { $db->exec("ALTER TABLE submission_statements $mod"); } catch(PDOException $e){}
}

// ── Sanitize ──────────────────────────────────────────────────
$coi       = in_array($data['conflict_of_interest'] ?? '', ['none','exists'])
             ? $data['conflict_of_interest'] : null;

$mst       = ($data['manuscript_submission_type'] ?? '') === 'previous'
             ? 'previous' : 'no_previous';

$fund      = ($data['funding_status'] ?? '') === 'funding_received'
             ? 'funding_received' : 'no_funding';

$aiRaw     = $data['generative_ai_used'] ?? '';
$aiUsed    = ($aiRaw === '' || $aiRaw === null) ? null : (int)$aiRaw;

$coiDet    = trim($data['conflict_details']       ?? '') ?: null;
$mstDet    = trim($data['manuscript_details']     ?? '') ?: null;
$fundDet   = trim($data['funding_details']        ?? '') ?: null;
$funderDat = !empty($data['funder_data'])          ? $data['funder_data'] : null;
$aiDet     = trim($data['generative_ai_details']  ?? '') ?: null;
$ethics    = (int)($data['ethics_compliant']      ?? 0);
$animals   = trim($data['studies_animals']        ?? '') ?: null;
$humans    = trim($data['studies_humans']         ?? '') ?: null;
$identif   = trim($data['includes_identifiable_data']   ?? '') ?: null;
$dataStmt  = trim($data['data_availability_statement']  ?? '') ?: null;

// Survey answers (JSON strings)
$animalsAns = !empty($data['animals_answers'])      ? $data['animals_answers']      : null;
$humansAns  = !empty($data['humans_answers'])       ? $data['humans_answers']       : null;
$identAns   = !empty($data['identifiable_answers']) ? $data['identifiable_answers'] : null;
$dataAns    = !empty($data['data_answers'])         ? $data['data_answers']         : null;

// ── UPSERT ─────────────────────────────────────────────────────
try {
    $db->beginTransaction();

    $exists = $db->prepare("SELECT statement_id FROM submission_statements WHERE submission_id=?");
    $exists->execute([$submissionId]);

    if ($exists->fetchColumn()) {
        $db->prepare(
            "UPDATE submission_statements SET
               conflict_of_interest=?,        conflict_details=?,
               manuscript_submission_type=?,   manuscript_details=?,
               funding_status=?,               funding_details=?,
               funder_data=?,
               generative_ai_used=?,           generative_ai_details=?,
               ethics_compliant=?,
               studies_animals=?,              animals_answers=?,
               studies_humans=?,               humans_answers=?,
               includes_identifiable_data=?,   identifiable_answers=?,
               data_availability_statement=?,  data_answers=?,
               updated_at=NOW()
             WHERE submission_id=?"
        )->execute([
            $coi, $coiDet,
            $mst, $mstDet,
            $fund, $fundDet,
            $funderDat,
            $aiUsed, $aiDet,
            $ethics,
            $animals, $animalsAns,
            $humans, $humansAns,
            $identif, $identAns,
            $dataStmt, $dataAns,
            $submissionId,
        ]);
    } else {
        $db->prepare(
            "INSERT INTO submission_statements
               (submission_id,
                conflict_of_interest,        conflict_details,
                manuscript_submission_type,  manuscript_details,
                funding_status,              funding_details,
                funder_data,
                generative_ai_used,          generative_ai_details,
                ethics_compliant,
                studies_animals,             animals_answers,
                studies_humans,              humans_answers,
                includes_identifiable_data,  identifiable_answers,
                data_availability_statement, data_answers)
             VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
        )->execute([
            $submissionId,
            $coi, $coiDet,
            $mst, $mstDet,
            $fund, $fundDet,
            $funderDat,
            $aiUsed, $aiDet,
            $ethics,
            $animals, $animalsAns,
            $humans, $humansAns,
            $identif, $identAns,
            $dataStmt, $dataAns,
        ]);
    }

    $db->prepare("UPDATE submissions SET updated_at=NOW() WHERE submission_id=?")->execute([$submissionId]);
    $db->commit();
    jsonResponse(true, 'Saved');

} catch (PDOException $e) {
    if ($db->inTransaction()) $db->rollBack();
    jsonResponse(false, 'DB error: ' . $e->getMessage());
}

