<?php
// ============================================================
//  ajax/save_manuscript.php
//  Saves/updates manuscript_info (title, running title, abstract)
// ============================================================
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);
$manuscriptId = (int)($_POST['manuscript_id'] ?? 0);
$articleTitle = trim($_POST['article_title'] ?? '');
$runningTitle = trim($_POST['running_title'] ?? '');
$abstract     = trim($_POST['abstract']      ?? '');
$action       = $_POST['action'] ?? 'save';

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

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

// Char counts
$titleCharCount    = mb_strlen($articleTitle);
$abstractCharCount = mb_strlen($abstract);

$db = db();

try {
    if ($manuscriptId) {
        // UPDATE existing
        $stmt = $db->prepare(
            "UPDATE manuscript_info
             SET article_title       = ?,
                 running_title       = ?,
                 abstract            = ?,
                 title_char_count    = ?,
                 abstract_char_count = ?,
                 updated_at          = NOW()
             WHERE manuscript_id = ? AND submission_id = ?"
        );
        $stmt->execute([
            $articleTitle ?: null,
            $runningTitle ?: null,
            $abstract     ?: null,
            $titleCharCount,
            $abstractCharCount,
            $manuscriptId,
            $submissionId
        ]);
    } else {
        // INSERT new
        $stmt = $db->prepare(
            "INSERT INTO manuscript_info
               (submission_id, article_title, running_title, abstract,
                title_char_count, abstract_char_count, created_at, updated_at)
             VALUES (?, ?, ?, ?, ?, ?, NOW(), NOW())"
        );
        $stmt->execute([
            $submissionId,
            $articleTitle ?: null,
            $runningTitle ?: null,
            $abstract     ?: null,
            $titleCharCount,
            $abstractCharCount
        ]);
        $manuscriptId = (int)$db->lastInsertId();
    }

    // Update submission completion score
    $score = 0;
    if ($articleTitle)            $score += 25;
    if ($abstract)                $score += 25;

    // Check keywords count
    $kwStmt = $db->prepare("SELECT COUNT(*) FROM submission_keywords WHERE submission_id = ?");
    $kwStmt->execute([$submissionId]);
    $kwCount = (int)$kwStmt->fetchColumn();
    if ($kwCount >= 5)            $score += 25;

    // Check submission step 1 fields
    $subStmt = $db->prepare("SELECT journal_id, specialty_id, article_type_id FROM submissions WHERE submission_id = ?");
    $subStmt->execute([$submissionId]);
    $sub = $subStmt->fetch();
    if ($sub && $sub['journal_id'] && $sub['specialty_id'] && $sub['article_type_id']) $score += 25;

    $db->prepare("UPDATE submissions SET updated_at = NOW() WHERE submission_id = ?")
       ->execute([$submissionId]);

    jsonResponse(true, 'Saved successfully', [
        'manuscript_id' => $manuscriptId,
        'score'         => $score,
    ]);

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