<?php
// ============================================================
//  ajax/save_authors.php
//  Saves all authors + contributions for a submission
//  Replaces entire author list (delete + re-insert)
// ============================================================
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);
$authorsJson  = $_POST['authors'] ?? '[]';
$authors      = json_decode($authorsJson, true);

if (!$submissionId) jsonResponse(false, 'Submission ID required');
if (!is_array($authors) || empty($authors)) jsonResponse(false, 'No author data');

// 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');

$db = db();
try {
    $db->beginTransaction();

    // Delete existing authors & contributions (cascade will handle contributions)
    $db->prepare("DELETE FROM author_contributions
                  WHERE author_id IN (
                      SELECT author_id FROM submission_authors WHERE submission_id = ?
                  )")->execute([$submissionId]);
    $db->prepare("DELETE FROM submission_authors WHERE submission_id = ?")
       ->execute([$submissionId]);

    $insertAuthor = $db->prepare(
        "INSERT INTO submission_authors
           (submission_id, user_id, email, title, first_name, middle_name, last_name,
            phone_country_code, phone_number, institutional_email,
            affiliation_id, is_corresponding, author_order, created_at)
         VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,NOW())"
    );

    $insertContrib = $db->prepare(
        "INSERT INTO author_contributions
           (author_id, writing_original_draft, writing_review_editing,
            conceptualization, data_curation, formal_analysis, funding_acquisition,
            investigation, methodology, project_administration, resources,
            software, supervision, validation, visualization)
         VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
    );

    $savedIds = [];
    foreach ($authors as $order => $a) {
        $affilId = (int)($a['affiliation_id'] ?? 0) ?: null;

        $insertAuthor->execute([
            $submissionId,
            $user_id,                         // always link to submitting user
            trim($a['email'] ?? ''),
            trim($a['title'] ?? '') ?: null,
            trim($a['first_name'] ?? ''),
            trim($a['middle_name'] ?? '') ?: null,
            trim($a['last_name'] ?? ''),
            trim($a['phone_country_code'] ?? '') ?: null,
            trim($a['phone_number'] ?? '') ?: null,
            trim($a['institutional_email'] ?? '') ?: null,
            $affilId,
            (int)($a['is_corresponding'] ?? 0),
            $order + 1,
        ]);

        $authorId = (int)$db->lastInsertId();
        $savedIds[] = $authorId;

        $c = $a['contributions'] ?? [];
        $insertContrib->execute([
            $authorId,
            (int)($c['writing_original_draft']   ?? 0),
            (int)($c['writing_review_editing']    ?? 0),
            (int)($c['conceptualization']         ?? 0),
            (int)($c['data_curation']             ?? 0),
            (int)($c['formal_analysis']           ?? 0),
            (int)($c['funding_acquisition']       ?? 0),
            (int)($c['investigation']             ?? 0),
            (int)($c['methodology']               ?? 0),
            (int)($c['project_administration']    ?? 0),
            (int)($c['resources']                 ?? 0),
            (int)($c['software']                  ?? 0),
            (int)($c['supervision']               ?? 0),
            (int)($c['validation']                ?? 0),
            (int)($c['visualization']             ?? 0),
        ]);
    }

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

    $db->commit();

    jsonResponse(true, 'Authors saved', [
        'author_count' => count($savedIds),
        'author_ids'   => $savedIds,
    ]);

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