<?php
// ============================================================
//  ajax/save_draft.php  —  Save / Create Submission Draft
//  Fixed: always returns submission_id, handles all cases
// ============================================================
require_once __DIR__ . '/../config/db.php';
startSession();

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(false, 'Invalid request method');
}

$userId  = getCurrentUserId();
$action  = trim($_POST['action'] ?? 'save');

// ── Create brand new blank submission ─────────────────────────
if ($action === 'new') {
    try {
        $stmt = db()->prepare(
            "INSERT INTO submissions
               (user_id, status, is_draft, completion_score, created_at, updated_at)
             VALUES (?, 'draft', 1, 0, NOW(), NOW())"
        );
        $stmt->execute([$userId]);
        $newId = (int)db()->lastInsertId();
        jsonResponse(true, 'New draft created', ['submission_id' => $newId]);
    } catch (PDOException $e) {
        jsonResponse(false, 'DB error: ' . $e->getMessage());
    }
}

// ── Save fields ───────────────────────────────────────────────
$submissionId    = (int)($_POST['submission_id']    ?? 0);
$journalId       = (int)($_POST['journal_id']        ?? 0) ?: null;
$specialtyId     = (int)($_POST['specialty_id']      ?? 0) ?: null;
$articleTypeId   = (int)($_POST['article_type_id']   ?? 0) ?: null;
$researchTopicId = (int)($_POST['research_topic_id'] ?? 0) ?: null;
$scopeStatement  = mb_substr(trim($_POST['scope_statement'] ?? ''), 0, 400);

// ── Get fee from article type ─────────────────────────────────
$feeChf = null;
if ($articleTypeId) {
    try {
        $stmt = db()->prepare(
            "SELECT preliminary_fee_chf FROM article_types WHERE article_type_id = ?"
        );
        $stmt->execute([$articleTypeId]);
        $feeChf = $stmt->fetchColumn() ?: null;
    } catch (PDOException $e) { /* ignore */ }
}

// ── Calculate completion score ────────────────────────────────
function calcScore(array $data): int {
    $required = ['journal_id','specialty_id','article_type_id','scope_statement'];
    $filled   = 0;
    foreach ($required as $f) {
        if (!empty($data[$f])) $filled++;
    }
    if (!empty($data['has_manuscript'])) $filled++;
    return (int)(($filled / (count($required) + 1)) * 100);
}

// Check manuscript file
$hasManuscript = false;
if ($submissionId) {
    try {
        $stmt = db()->prepare(
            "SELECT COUNT(*) FROM submission_files
             WHERE submission_id = ? AND file_type IN ('manuscript','manuscript_pdf')"
        );
        $stmt->execute([$submissionId]);
        $hasManuscript = $stmt->fetchColumn() > 0;
    } catch (PDOException $e) { /* ignore */ }
}

$scoreData = [
    'journal_id'      => $journalId,
    'specialty_id'    => $specialtyId,
    'article_type_id' => $articleTypeId,
    'scope_statement' => $scopeStatement,
    'has_manuscript'  => $hasManuscript,
];
$completionScore = calcScore($scoreData);

// ── INSERT or UPDATE ──────────────────────────────────────────
try {
    if ($submissionId) {
        // Verify ownership
        $stmt = db()->prepare(
            "SELECT user_id FROM submissions WHERE submission_id = ?"
        );
        $stmt->execute([$submissionId]);
        $owner = $stmt->fetchColumn();

        if (!$owner) {
            // ID doesnt exist — create new
            $submissionId = 0;
        } elseif ((int)$owner !== $userId) {
            jsonResponse(false, 'Access denied — this draft belongs to another user');
        }
    }

    if ($submissionId) {
        // UPDATE existing draft
        $stmt = db()->prepare(
            "UPDATE submissions SET
               journal_id          = ?,
               specialty_id        = ?,
               article_type_id     = ?,
               research_topic_id   = ?,
               scope_statement     = ?,
               preliminary_fee_chf = ?,
               completion_score    = ?,
               updated_at          = NOW()
             WHERE submission_id = ? AND user_id = ?"
        );
        $stmt->execute([
            $journalId, $specialtyId, $articleTypeId,
            $researchTopicId, $scopeStatement,
            $feeChf, $completionScore,
            $submissionId, $userId
        ]);
    } else {
        // INSERT new draft
        $stmt = db()->prepare(
            "INSERT INTO submissions
               (user_id, journal_id, specialty_id, article_type_id,
                research_topic_id, scope_statement, preliminary_fee_chf,
                completion_score, status, is_draft, created_at, updated_at)
             VALUES (?,?,?,?,?,?,?,?,'draft',1,NOW(),NOW())"
        );
        $stmt->execute([
            $userId, $journalId, $specialtyId, $articleTypeId,
            $researchTopicId, $scopeStatement,
            $feeChf, $completionScore
        ]);
        $submissionId = (int)db()->lastInsertId();
    }

    jsonResponse(true, 'Saved successfully', [
        'submission_id'    => $submissionId,
        'completion_score' => $completionScore,
        'preliminary_fee'  => $feeChf,
    ]);

} catch (PDOException $e) {
    jsonResponse(false, 'Database error: ' . $e->getMessage());
}