<?php
/**
 * article_jats_xml.php
 * Place at: /journals/social-science/article_jats_xml.php
 *
 * Generates JATS 1.3 XML from DB. Works for ALL articles —
 * whether published (has publication_date) or not.
 *
 * Usage: article_jats_xml.php?id=38
 */

if (session_status() === PHP_SESSION_NONE) session_start();
ini_set('display_errors', 0);
error_reporting(0);

/* ── Find db_new.php ── */
$dbPaths = [
    __DIR__ . '/../../config/db_new.php',
    __DIR__ . '/../config/db_new.php',
    __DIR__ . '/config/db_new.php',
    dirname(__DIR__, 2) . '/config/db_new.php',
];
foreach ($dbPaths as $p) {
    if (file_exists($p)) { include_once $p; break; }
}

$sid = (int)($_GET['id'] ?? 0);
if (!$sid || empty($pdo)) {
    http_response_code(404);
    exit('Article not found.');
}

/* ─── Fetch data ─────────────────────────────────────────── */
try {
    /* Step 1: submission + manuscript_info + journal (always available) */
    $stmt = $pdo->prepare("
        SELECT s.submission_id, s.tracking_code, s.journal_id,
               mi.article_title, mi.running_title, mi.abstract
        FROM submissions s
        LEFT JOIN manuscript_info mi ON mi.submission_id = s.submission_id
        WHERE s.submission_id = ?
        LIMIT 1
    ");
    $stmt->execute([$sid]);
    $base = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$base) {
        http_response_code(404);
        exit('Article not found.');
    }

    /* Step 2: best published file (may be NULL — use ANY file as fallback) */
    $pfStmt = $pdo->prepare("
        SELECT pf.doi, pf.page_no, pf.reference, pf.publication_date,
               pf.published_pdf_path, pf.volume_id
        FROM submission_files pf
        WHERE pf.submission_id = ?
          AND pf.file_type IN ('payment_receipt','final_manuscript_revised','declaration_form')
        ORDER BY
            (pf.publication_date IS NOT NULL) DESC,
            pf.uploaded_at DESC
        LIMIT 1
    ");
    $pfStmt->execute([$sid]);
    $pf = $pfStmt->fetch(PDO::FETCH_ASSOC);

    /* Step 3: volume + journal */
    $volume  = null;
    $journal = null;
    if (!empty($pf['volume_id'])) {
        $vStmt = $pdo->prepare("SELECT * FROM journal_volumes WHERE id=? LIMIT 1");
        $vStmt->execute([$pf['volume_id']]);
        $volume = $vStmt->fetch(PDO::FETCH_ASSOC);
    }
    if (!empty($base['journal_id'])) {
        $jStmt = $pdo->prepare("SELECT * FROM journals WHERE journal_id=? LIMIT 1");
        $jStmt->execute([$base['journal_id']]);
        $journal = $jStmt->fetch(PDO::FETCH_ASSOC);
    }

    /* Merge into one article array */
    $article = array_merge($base, $pf ?: [], [
        'journal_name' => $journal['name'] ?? 'Communeglobal International Journal of Social Sciences',
        'journal_slug' => $journal['slug'] ?? 'social-science',
        'vol_num'      => $volume['volume'] ?? '',
        'vol_iss'      => $volume['issue']  ?? '',
        'vol_year'     => $volume['year']   ?? '',
        'vol_title'    => $volume['title']  ?? '',
    ]);

    /* Step 4: Authors + affiliations */
    $aStmt = $pdo->prepare("
        SELECT sa.author_id, sa.first_name, sa.middle_name, sa.last_name,
               sa.title AS author_title, sa.email,
               sa.is_corresponding, sa.author_order, sa.affiliation_id,
               af.name AS aff_name, af.department, af.city, af.country
        FROM submission_authors sa
        LEFT JOIN affiliations af ON af.affiliation_id = sa.affiliation_id
        WHERE sa.submission_id = ?
        ORDER BY sa.author_order
    ");
    $aStmt->execute([$sid]);
    $authors = $aStmt->fetchAll(PDO::FETCH_ASSOC);

    /* Step 5: Keywords */
    $kStmt = $pdo->prepare("
        SELECT k.keyword FROM submission_keywords sk
        JOIN keywords k ON k.keyword_id = sk.keyword_id
        WHERE sk.submission_id = ?
        ORDER BY sk.display_order
    ");
    $kStmt->execute([$sid]);
    $keywords = array_column($kStmt->fetchAll(PDO::FETCH_ASSOC), 'keyword');

    /* Step 6: References */
    $refText  = $article['reference'] ?? '';
    $refLines = [];
    if ($refText) {
        $refLines = array_values(array_filter(
            array_map('trim', explode("\n", $refText)),
            fn($l) => $l !== ''
        ));
    }

    /* Step 7: Submitted / accepted dates */
    $subStmt = $pdo->prepare("SELECT submitted_at, created_at FROM submissions WHERE submission_id=? LIMIT 1");
    $subStmt->execute([$sid]);
    $subRow = $subStmt->fetch(PDO::FETCH_ASSOC);
    $submittedDate = $subRow ? ($subRow['submitted_at'] ?: $subRow['created_at']) : null;

    $edStmt = $pdo->prepare("SELECT MIN(created_at) AS first_decision FROM editorial_decisions WHERE submission_id=?");
    $edStmt->execute([$sid]);
    $edRow = $edStmt->fetch(PDO::FETCH_ASSOC);
    $acceptedDate = $edRow['first_decision'] ?? null;

} catch (PDOException $e) {
    http_response_code(500);
    exit('Database error: ' . $e->getMessage());
}

/* ─── Record xml_download stat ───────────────────────────── */
$sessKey = "tracked_xml_download_{$sid}";
if (empty($_SESSION[$sessKey])) {
    $_SESSION[$sessKey] = true;
    try {
        $ipHash = hash('sha256', $_SERVER['REMOTE_ADDR'] ?? '');
        $uaHash = hash('sha256', $_SERVER['HTTP_USER_AGENT'] ?? '');
        $sessionKey = session_id() . '_' . $sid . '_xml_download';

        /* Auto-create table if needed */
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS `article_stats` (
              `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
              `submission_id` int(10) UNSIGNED NOT NULL,
              `total_views` int(10) UNSIGNED NOT NULL DEFAULT 0,
              `total_pdf_downloads` int(10) UNSIGNED NOT NULL DEFAULT 0,
              `total_xml_downloads` int(10) UNSIGNED NOT NULL DEFAULT 0,
              `last_viewed_at` datetime DEFAULT NULL,
              `last_downloaded_at` datetime DEFAULT NULL,
              `created_at` datetime NOT NULL DEFAULT current_timestamp(),
              `updated_at` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
              PRIMARY KEY (`id`),
              UNIQUE KEY `uq_submission` (`submission_id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");

        $pdo->prepare("
            INSERT INTO article_stats (submission_id, total_xml_downloads, last_downloaded_at)
            VALUES (?, 1, NOW())
            ON DUPLICATE KEY UPDATE total_xml_downloads = total_xml_downloads + 1, last_downloaded_at = NOW()
        ")->execute([$sid]);
    } catch (PDOException $e) { /* silent */ }
}

/* ─── Helpers ────────────────────────────────────────────── */
function xe(string $s): string {
    return htmlspecialchars(trim($s), ENT_XML1, 'UTF-8');
}

/* ─── Derived metadata ────────────────────────────────────── */
$doi         = $article['doi']              ?? '';
$pubDate     = $article['publication_date'] ?? '';
$pubYear     = $pubDate ? date('Y', strtotime($pubDate)) : date('Y');
$pubMonth    = $pubDate ? date('m', strtotime($pubDate)) : '';
$pubDay      = $pubDate ? date('d', strtotime($pubDate)) : '';
$volNum      = $article['vol_num']          ?? '';
$volIss      = $article['vol_iss']          ?? '';
$pageNo      = $article['page_no']          ?? '';
$fPage = $lPage = '';
if ($pageNo && strpos($pageNo, '-') !== false) {
    [$fPage, $lPage] = array_map('trim', explode('-', $pageNo, 2));
} elseif ($pageNo) {
    $fPage = trim($pageNo);
}
$journalName = $article['journal_name'];
$jSlugVal    = $article['journal_slug'];
$title       = $article['article_title']   ?? 'Untitled';
$abstract    = $article['abstract']        ?? '';
$trackCode   = $article['tracking_code']   ?? ('ART-' . $sid);
$siteUrl     = (isset($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? 'communeglobal.com');
$articleUrl  = $siteUrl . '/journals/' . $jSlugVal . '/article.php?id=' . $sid;

/* ─── Build unique affiliations list ────────────────────── */
$affMap  = [];
$affList = [];
foreach ($authors as $a) {
    $affId = $a['affiliation_id'] ?? null;
    if ($affId && !isset($affMap[$affId])) {
        $affMap[$affId] = count($affMap) + 1;
        $affList[] = $a;
    }
}

/* ═══════════════════════════════════════════════════════════
   BUILD JATS 1.3 XML
═══════════════════════════════════════════════════════════ */
$xml  = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
$xml .= '<!DOCTYPE article PUBLIC "-//NLM//DTD JATS (Z39.96) Journal Archiving and Interchange DTD v1.3 20210610//EN"' . "\n";
$xml .= '  "https://jats.nlm.nih.gov/archiving/1.3/JATS-archivearticle1-3.dtd">' . "\n";
$xml .= '<article xmlns:xlink="http://www.w3.org/1999/xlink"' . "\n";
$xml .= '         xmlns:mml="http://www.w3.org/1998/Math/MathML"' . "\n";
$xml .= '         article-type="research-article" xml:lang="en">' . "\n\n";

/* ── FRONT ── */
$xml .= "  <front>\n";
$xml .= "    <journal-meta>\n";
$xml .= "      <journal-id journal-id-type=\"publisher-id\">" . xe(strtoupper($jSlugVal)) . "</journal-id>\n";
$xml .= "      <journal-title-group>\n";
$xml .= "        <journal-title>" . xe($journalName) . "</journal-title>\n";
$xml .= "      </journal-title-group>\n";
$xml .= "      <publisher>\n";
$xml .= "        <publisher-name>Commune Global</publisher-name>\n";
$xml .= "        <publisher-loc>Gurugram, India</publisher-loc>\n";
$xml .= "      </publisher>\n";
$xml .= "    </journal-meta>\n\n";

$xml .= "    <article-meta>\n";
$xml .= "      <article-id pub-id-type=\"publisher-id\">" . xe($trackCode) . "</article-id>\n";
if ($doi) {
    $xml .= "      <article-id pub-id-type=\"doi\">" . xe($doi) . "</article-id>\n";
}

/* Title */
$xml .= "      <title-group>\n";
$xml .= "        <article-title>" . xe($title) . "</article-title>\n";
if (!empty($article['running_title'])) {
    $xml .= "        <alt-title alt-title-type=\"running-head\">" . xe($article['running_title']) . "</alt-title>\n";
}
$xml .= "      </title-group>\n\n";

/* Authors */
$xml .= "      <contrib-group>\n";
foreach ($authors as $a) {
    $fn   = xe($a['first_name'] ?? '');
    $mn   = xe($a['middle_name'] ?? '');
    $ln   = xe($a['last_name'] ?? '');
    $corrAttr = $a['is_corresponding'] ? ' corresp="yes"' : '';
    $xml .= "        <contrib contrib-type=\"author\"{$corrAttr}>\n";
    $xml .= "          <name>\n";
    $xml .= "            <surname>{$ln}</surname>\n";
    $xml .= "            <given-names>{$fn}" . ($mn ? " {$mn}" : '') . "</given-names>\n";
    $xml .= "          </name>\n";
    $affId = $a['affiliation_id'] ?? null;
    if ($affId && isset($affMap[$affId])) {
        $xml .= "          <xref ref-type=\"aff\" rid=\"aff{$affMap[$affId]}\"/>\n";
    }
    if ($a['is_corresponding']) {
        $xml .= "          <xref ref-type=\"corresp\" rid=\"cor1\"/>\n";
    }
    $xml .= "        </contrib>\n";
}
$xml .= "      </contrib-group>\n\n";

/* Affiliations */
foreach ($affList as $a) {
    $affId  = $a['affiliation_id'];
    $affIdx = $affMap[$affId];
    $xml .= "      <aff id=\"aff{$affIdx}\">";
    if (!empty($a['aff_name']))   $xml .= "<institution>" . xe($a['aff_name']) . "</institution>";
    if (!empty($a['department'])) $xml .= ", <institution content-type=\"dept\">" . xe($a['department']) . "</institution>";
    if (!empty($a['city']))       $xml .= ", <addr-line>" . xe($a['city']) . "</addr-line>";
    if (!empty($a['country']))    $xml .= ", <country>" . xe($a['country']) . "</country>";
    $xml .= "\n      </aff>\n";
}

/* Corresponding author note — email hidden */
$corrAuthor = null;
foreach ($authors as $a) { if ($a['is_corresponding']) { $corrAuthor = $a; break; } }
if ($corrAuthor) {
    $xml .= "      <author-notes>\n";
    $xml .= "        <corresp id=\"cor1\">Corresponding author details available upon request.</corresp>\n";
    $xml .= "      </author-notes>\n\n";
}

/* Pub date */
if ($pubDate) {
    $xml .= "      <pub-date pub-type=\"epub\" date-type=\"pub\" iso-8601-date=\"" . xe($pubDate) . "\">\n";
    $xml .= "        <day>{$pubDay}</day>\n";
    $xml .= "        <month>{$pubMonth}</month>\n";
    $xml .= "        <year>{$pubYear}</year>\n";
    $xml .= "      </pub-date>\n";
} else {
    $xml .= "      <pub-date pub-type=\"epub\">\n";
    $xml .= "        <year>" . date('Y') . "</year>\n";
    $xml .= "      </pub-date>\n";
}

/* History */
if ($submittedDate || $acceptedDate) {
    $xml .= "      <history>\n";
    if ($submittedDate) {
        $xml .= "        <date date-type=\"received\" iso-8601-date=\"" . xe(date('Y-m-d', strtotime($submittedDate))) . "\">\n";
        $xml .= "          <day>"   . date('d', strtotime($submittedDate)) . "</day>\n";
        $xml .= "          <month>" . date('m', strtotime($submittedDate)) . "</month>\n";
        $xml .= "          <year>"  . date('Y', strtotime($submittedDate)) . "</year>\n";
        $xml .= "        </date>\n";
    }
    if ($acceptedDate) {
        $xml .= "        <date date-type=\"accepted\" iso-8601-date=\"" . xe(date('Y-m-d', strtotime($acceptedDate))) . "\">\n";
        $xml .= "          <day>"   . date('d', strtotime($acceptedDate)) . "</day>\n";
        $xml .= "          <month>" . date('m', strtotime($acceptedDate)) . "</month>\n";
        $xml .= "          <year>"  . date('Y', strtotime($acceptedDate)) . "</year>\n";
        $xml .= "        </date>\n";
    }
    $xml .= "      </history>\n";
}

/* Volume/issue/pages */
if ($volNum) $xml .= "      <volume>{$volNum}</volume>\n";
if ($volIss) $xml .= "      <issue>{$volIss}</issue>\n";
if ($fPage)  $xml .= "      <fpage>" . xe($fPage) . "</fpage>\n";
if ($lPage)  $xml .= "      <lpage>" . xe($lPage) . "</lpage>\n";

/* Permissions */
$xml .= "      <permissions>\n";
$xml .= "        <copyright-statement>© {$pubYear} The Authors</copyright-statement>\n";
$xml .= "        <copyright-year>{$pubYear}</copyright-year>\n";
$xml .= "        <license license-type=\"open-access\" xlink:href=\"https://creativecommons.org/licenses/by/4.0/\">\n";
$xml .= "          <license-p>Open access under CC BY 4.0. Authors retain copyright.</license-p>\n";
$xml .= "        </license>\n";
$xml .= "      </permissions>\n\n";

/* Self URI */
$xml .= "      <self-uri xlink:href=\"" . xe($articleUrl) . "\"/>\n";
if ($doi) {
    $xml .= "      <self-uri content-type=\"doi\" xlink:href=\"https://doi.org/" . xe($doi) . "\"/>\n";
}

/* Abstract */
if ($abstract) {
    $xml .= "      <abstract>\n";
    foreach (array_filter(array_map('trim', preg_split('/\n{2,}/', $abstract))) as $para) {
        $xml .= "        <p>" . xe($para) . "</p>\n";
    }
    $xml .= "      </abstract>\n";
}

/* Keywords */
if (!empty($keywords)) {
    $xml .= "      <kwd-group kwd-group-type=\"author-keywords\">\n";
    $xml .= "        <title>Keywords</title>\n";
    foreach ($keywords as $kw) {
        $xml .= "        <kwd>" . xe($kw) . "</kwd>\n";
    }
    $xml .= "      </kwd-group>\n";
}

$xml .= "    </article-meta>\n";
$xml .= "  </front>\n\n";

/* ── BODY ── */
$xml .= "  <body>\n";
$xml .= "    <sec sec-type=\"article-body\">\n";
$xml .= "      <title>Article</title>\n";
$xml .= "      <p>Full text available at: <ext-link ext-link-type=\"uri\" xlink:href=\"" . xe($articleUrl) . "\">" . xe($articleUrl) . "</ext-link></p>\n";
$xml .= "    </sec>\n";
$xml .= "  </body>\n\n";

/* ── BACK: References ── */
if (!empty($refLines)) {
    $xml .= "  <back>\n";
    $xml .= "    <ref-list>\n";
    $xml .= "      <title>References</title>\n";
    foreach ($refLines as $i => $ref) {
        $clean   = preg_replace('/^\d+\.\s*/', '', $ref);
        $doiMatch = [];
        preg_match('/10\.\d{4,9}\/[\w\d\.\-\/]+/i', $ref, $doiMatch);
        $refDoi  = $doiMatch[0] ?? '';
        $refId   = 'ref' . ($i + 1);
        $xml .= "      <ref id=\"{$refId}\">\n";
        $xml .= "        <label>" . ($i + 1) . "</label>\n";
        $xml .= "        <mixed-citation>" . xe($clean);
        if ($refDoi) $xml .= " <pub-id pub-id-type=\"doi\">" . xe($refDoi) . "</pub-id>";
        $xml .= "</mixed-citation>\n";
        $xml .= "      </ref>\n";
    }
    $xml .= "    </ref-list>\n";
    $xml .= "  </back>\n";
}

$xml .= "</article>\n";

/* ─── Send as download ────────────────────────────────────── */
$safeDoi = $doi ? '-' . preg_replace('/[^a-zA-Z0-9_-]/', '_', $doi) : '';
$filename = 'article-' . $sid . $safeDoi . '.xml';

header('Content-Type: application/xml; charset=UTF-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Length: ' . strlen($xml));
header('Cache-Control: no-cache, no-store');
echo $xml;