<?php
/**
 * article_track.php
 * Place at: /journals/social-science/article_track.php
 *
 * Called via JS fetch on:
 *   - every page load  → event=view        (always increments)
 *   - PDF click        → event=pdf_download (always increments)
 *   - XML click        → event=xml_download (always increments)
 *
 * NO session dedup — every call increments the counter.
 * Returns JSON: {"status":"ok","views":N,"downloads":N,...}
 */

if (session_status() === PHP_SESSION_NONE) session_start();
ini_set('display_errors', 0);
error_reporting(0);
header('Content-Type: application/json; charset=UTF-8');
header('Cache-Control: no-store');

// ── Resolve db_new.php path regardless of where this file sits ──
$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; }
}

// ── Read params (POST preferred, GET fallback) ──
$sid   = (int)(($_POST['id']    ?? $_GET['id']    ?? 0));
$event = trim(  $_POST['event'] ?? $_GET['event'] ?? 'view');

$allowed = ['view', 'pdf_download', 'xml_download'];
if (!$sid || !in_array($event, $allowed, true)) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid params', 'sid' => $sid, 'event' => $event]);
    exit;
}

if (empty($pdo)) {
    echo json_encode(['status' => 'error', 'message' => 'DB connection unavailable']);
    exit;
}

/* ── Ensure article_stats table exists (auto-create if missing) ── */
try {
    $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
    ");
} catch (PDOException $e) { /* table already exists - ignore */ }

/* ── Always increment the matching column ── */
try {
    if ($event === 'view') {
        $pdo->prepare("
            INSERT INTO article_stats (submission_id, total_views, last_viewed_at)
            VALUES (?, 1, NOW())
            ON DUPLICATE KEY UPDATE
              total_views    = total_views + 1,
              last_viewed_at = NOW()
        ")->execute([$sid]);

    } elseif ($event === 'pdf_download') {
        $pdo->prepare("
            INSERT INTO article_stats (submission_id, total_pdf_downloads, last_downloaded_at)
            VALUES (?, 1, NOW())
            ON DUPLICATE KEY UPDATE
              total_pdf_downloads = total_pdf_downloads + 1,
              last_downloaded_at  = NOW()
        ")->execute([$sid]);

    } elseif ($event === 'xml_download') {
        $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) {
    echo json_encode(['status' => 'db_error', 'message' => $e->getMessage()]);
    exit;
}

/* ── Fetch and return current counts ── */
try {
    $row = $pdo->prepare("
        SELECT total_views, total_pdf_downloads, total_xml_downloads
        FROM article_stats
        WHERE submission_id = ?
        LIMIT 1
    ");
    $row->execute([$sid]);
    $stats = $row->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $stats = null;
}

$views  = (int)($stats['total_views']         ?? 0);
$pdfDl  = (int)($stats['total_pdf_downloads'] ?? 0);
$xmlDl  = (int)($stats['total_xml_downloads'] ?? 0);

echo json_encode([
    'status'        => 'ok',
    'event'         => $event,
    'views'         => $views,
    'downloads'     => $pdfDl + $xmlDl,
    'pdf_downloads' => $pdfDl,
    'xml_downloads' => $xmlDl,
]);