<?php
/**
 * article_siq_submit.php
 * Place at: /journals/article_siq_submit.php
 *
 * Saves SIQ rating to DB.
 * Sets $_SESSION['siq_rated_{sid}'] = true so article.php
 * unlocks the comment form on reload.
 */

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

include_once __DIR__ . '/../config/db_new.php';

function out(array $d): void {
    echo json_encode($d, JSON_UNESCAPED_UNICODE);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    out(['status' => 'error', 'message' => 'Invalid request method.']);
}

/* ── Read inputs ────────────────────────────────────────── */
$sid = (int)trim($_POST['submission_id'] ?? 0);
if ($sid < 1) out(['status' => 'error', 'message' => 'Invalid article ID.']);

$keyMap = [
    'clarity'       => 'clarity',
    'clinical'      => 'clinical',
    'study'         => 'study',
    'data_analysis' => 'data',
    'novelty'       => 'novelty',
    'presentation'  => 'presentation',
];
$scores = []; $sum = 0;
foreach ($keyMap as $col => $postKey) {
    $v = isset($_POST[$postKey]) ? max(1, min(10, (int)$_POST[$postKey])) : 1;
    $scores[$col] = $v; $sum += $v;
}
$avgScore  = round($sum / count($scores), 2);
$conflict  = in_array(trim($_POST['conflict'] ?? 'no'), ['no','yes']) ? trim($_POST['conflict']) : 'no';
$coiDetail = mb_substr(trim($_POST['conflict_detail'] ?? ''), 0, 1000);
$ip        = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
$ua        = mb_substr($_SERVER['HTTP_USER_AGENT'] ?? '', 0, 512);

if (!$pdo) out(['status' => 'error', 'message' => 'Database connection failed.']);

/* ── Auto-create table ──────────────────────────────────── */
try {
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS `article_siq_ratings` (
            `rating_id`       INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            `submission_id`   INT UNSIGNED NOT NULL,
            `clarity`         TINYINT UNSIGNED NOT NULL DEFAULT 1,
            `clinical`        TINYINT UNSIGNED NOT NULL DEFAULT 1,
            `study`           TINYINT UNSIGNED NOT NULL DEFAULT 1,
            `data_analysis`   TINYINT UNSIGNED NOT NULL DEFAULT 1,
            `novelty`         TINYINT UNSIGNED NOT NULL DEFAULT 1,
            `presentation`    TINYINT UNSIGNED NOT NULL DEFAULT 1,
            `siq_score`       DECIMAL(4,2) NOT NULL DEFAULT 0.00,
            `conflict`        ENUM('no','yes') NOT NULL DEFAULT 'no',
            `conflict_detail` TEXT DEFAULT NULL,
            `ip_address`      VARCHAR(45) NOT NULL DEFAULT '',
            `user_agent`      VARCHAR(512) DEFAULT NULL,
            `status`          TINYINT UNSIGNED NOT NULL DEFAULT 1,
            `admin_note`      TEXT DEFAULT NULL,
            `created_at`      DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            INDEX `idx_sub`  (`submission_id`),
            INDEX `idx_ip`   (`ip_address`),
            INDEX `idx_date` (`created_at`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    ");
} catch (PDOException $e) {}

/* ── ALWAYS set session flag first ─────────────────────────
   This ensures even if rate-limit fires, the user who already
   rated can still see/use the comment form.
─────────────────────────────────────────────────────────── */
$_SESSION['siq_rated_' . $sid] = true;

/* ── Rate-limit: 1 per IP per article per 24 h ──────────── */
try {
    $rl = $pdo->prepare("
        SELECT COUNT(*) FROM article_siq_ratings
        WHERE submission_id = ? AND ip_address = ?
          AND created_at > DATE_SUB(NOW(), INTERVAL 24 HOUR)
    ");
    $rl->execute([$sid, $ip]);
    if ((int)$rl->fetchColumn() > 0) {
        /* Already rated — return success so page reloads
           and comment form unlocks (session was set above) */
        out([
            'status'  => 'success',
            'message' => 'You have already rated this article today. You can still leave a comment!',
            'already_rated' => true,
            'siq_score' => null,
        ]);
    }
} catch (PDOException $e) {}

/* ── Insert rating ──────────────────────────────────────── */
$newRatingId = 0;
try {
    $ins = $pdo->prepare("
        INSERT INTO article_siq_ratings
            (submission_id, clarity, clinical, study, data_analysis,
             novelty, presentation, siq_score,
             conflict, conflict_detail, ip_address, user_agent, status)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
    ");
    $ins->execute([
        $sid,
        $scores['clarity'], $scores['clinical'], $scores['study'],
        $scores['data_analysis'], $scores['novelty'], $scores['presentation'],
        $avgScore, $conflict, $coiDetail ?: null, $ip, $ua ?: null,
    ]);
    $newRatingId = (int)$pdo->lastInsertId();
} catch (PDOException $e) {
    /* DB insert failed — but session is already set, so still
       return success so the page reloads and comment form shows */
    out([
        'status'    => 'success',
        'message'   => 'Thank you for rating this article!',
        'db_error'  => true,
        'siq_score' => null,
        'rating_id' => 0,
    ]);
}

/* ── Aggregate SIQ ──────────────────────────────────────── */
try {
    $agg = $pdo->prepare("
        SELECT COUNT(*) AS cnt, AVG(siq_score) AS mean
        FROM article_siq_ratings
        WHERE submission_id = ? AND status = 1
    ");
    $agg->execute([$sid]);
    $row          = $agg->fetch(PDO::FETCH_ASSOC);
    $totalRatings = (int)$row['cnt'];
    $meanScore    = $totalRatings > 0 ? round((float)$row['mean'], 1) : null;
    $isFirst      = ($totalRatings === 1);
    $revealed     = ($totalRatings >= 2);
    $pubScore     = $revealed ? number_format($meanScore, 1) : null;

    $msg = $isFirst
        ? "You're the first to rate this article! The SIQ will be revealed after one more rating."
        : "Thank you! The SIQ for this article is now {$pubScore}.";

    out([
        'status'        => 'success',
        'message'       => $msg,
        'is_first'      => $isFirst,
        'revealed'      => $revealed,
        'siq_score'     => $pubScore,
        'your_score'    => number_format($avgScore, 1),
        'total'         => $totalRatings,
        'rating_id'     => $newRatingId,
        'already_rated' => false,
    ]);

} catch (PDOException $e) {
    out([
        'status'    => 'success',
        'message'   => 'Thank you for rating this article!',
        'siq_score' => null,
        'rating_id' => $newRatingId,
    ]);
}