<?php
/**
 * article_comment_submit.php
 * Place at: /journals/article_comment_submit.php
 *
 * Fields: submission_id, name, comment
 * No rating required. status=0 until admin approves.
 */

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.']);

$sid     = (int)trim($_POST['submission_id'] ?? 0);
$name    = trim($_POST['name']    ?? '');
$comment = trim($_POST['comment'] ?? '');
$ip      = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';

if (!$sid)                              out(['status'=>'error','message'=>'Invalid article.']);
if (mb_strlen($name) < 2 || mb_strlen($name) > 120)
                                        out(['status'=>'error','message'=>'Name must be 2–120 characters.']);
if (mb_strlen($comment) < 10)          out(['status'=>'error','message'=>'Comment must be at least 10 characters.']);
if (mb_strlen($comment) > 3000)        out(['status'=>'error','message'=>'Comment is too long (max 3000 characters).']);

/* Also verify session — extra server-side guard */
if (empty($_SESSION['siq_rated_'.$sid])) {
    out(['status'=>'error','message'=>'Please rate the article before commenting.']);
}

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

/* Auto-create table */
try {
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS `article_comments` (
            `comment_id`    INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            `submission_id` INT UNSIGNED NOT NULL,
            `name`          VARCHAR(120) NOT NULL,
            `email`         VARCHAR(180) DEFAULT NULL,
            `rating`        TINYINT UNSIGNED NOT NULL DEFAULT 0,
            `comment`       TEXT NOT NULL,
            `ip_address`    VARCHAR(45) NOT NULL DEFAULT '',
            `status`        TINYINT UNSIGNED NOT NULL DEFAULT 0
                            COMMENT '0=pending,1=approved,2=rejected',
            `admin_note`    TEXT DEFAULT NULL,
            `created_at`    DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            INDEX `idx_sub`    (`submission_id`),
            INDEX `idx_status` (`status`),
            INDEX `idx_date`   (`created_at`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    ");
} catch (PDOException $e) {}

/* Rate-limit: max 3 per IP per 10 min */
try {
    $rl = $pdo->prepare("SELECT COUNT(*) FROM article_comments WHERE ip_address=? AND created_at > DATE_SUB(NOW(), INTERVAL 10 MINUTE)");
    $rl->execute([$ip]);
    if ((int)$rl->fetchColumn() >= 3) out(['status'=>'error','message'=>'Too many comments. Please wait a few minutes.']);
} catch (PDOException $e) {}

/* Insert status=0 */
try {
    $ins = $pdo->prepare("INSERT INTO article_comments (submission_id,name,rating,comment,ip_address,status) VALUES (?,?,0,?,?,0)");
    $ins->execute([$sid, $name, $comment, $ip]);
    out(['status'=>'success','message'=>'Thank you! Your comment has been submitted and is pending review.']);
} catch (PDOException $e) {
    out(['status'=>'error','message'=>'Database error. Please try again.']);
}