<?php
// submit_comment.php
session_start();

// 1. DB connection
require_once __DIR__ . '/includes/config.php';

// 2. Accept only POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: index.php');
    exit;
}

// 3. Collect inputs
$book_id  = intval($_POST['book_id'] ?? 0);
$username = trim((string)($_POST['username'] ?? ''));
$email    = trim((string)($_POST['email'] ?? ''));
$comment  = trim((string)($_POST['comment'] ?? ''));

// Basic validation
if ($book_id <= 0 || $username === '' || $comment === '') {
    $_SESSION['comment_error'] = 'Please fill all required fields.';
    header("Location: book_details.php?id={$book_id}#comments");
    exit;
}

// 4. Simple rate-limit (per IP, 30 seconds)
$ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
$rateFile = sys_get_temp_dir() . "/last_comment_" . md5($ip);
if (file_exists($rateFile) && (time() - (int)file_get_contents($rateFile)) < 30) {
    $_SESSION['comment_error'] = 'You are commenting too quickly. Please wait a moment.';
    header("Location: book_details.php?id={$book_id}#comments");
    exit;
}
file_put_contents($rateFile, (string)time());

// Logged-in user id (optional)
$user_id = isset($_SESSION['user_id']) ? intval($_SESSION['user_id']) : null;

// ----------------------------------------------------
// 5. ML API CALL (FastAPI)
// ----------------------------------------------------
$detector_score = 0.0;
$detector_label = "api_error";

$api_url = "http://127.0.0.1:8000/predict";
$payload = json_encode(["text" => $comment]);

$ch = curl_init($api_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 2); // small timeout so page doesn’t hang

$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_err  = curl_error($ch);
curl_close($ch);

if ($response !== false && $http_code === 200) {
    $result = json_decode($response, true);
    if (is_array($result) && isset($result["score"], $result["label"])) {
        $detector_score = floatval($result["score"]);
        $detector_label = (string)$result["label"];
    }
} else {
    // API FAILED → fallback (score 0, label api_error)
    // $detector_score and $detector_label already have safe defaults
}

// ----------------------------------------------------
// 6. Decide comment status from ML score
// ----------------------------------------------------
if ($detector_score >= 0.80) {        // auto reject
    $status = "rejected";
} elseif ($detector_score >= 0.50) {  // send to admin review
    $status = "flagged";
} else {                              // low risk = approved
    $status = "approved";
}

// ----------------------------------------------------
// 7. Insert comment into DB
// ----------------------------------------------------
$sql = "INSERT INTO comments 
        (book_id, user_id, username, email, comment, status, detector_score, detector_label, created_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())";

$stmt = $conn->prepare($sql);
if ($stmt === false) {
    error_log('Prepare failed in submit_comment.php: ' . $conn->error);
    $_SESSION['comment_error'] = 'Server error. Please try again.';
    header("Location: book_details.php?id={$book_id}#comments");
    exit;
}

/*
 Types: 
   book_id        -> i
   user_id        -> i  (can be null)
   username       -> s
   email          -> s
   comment        -> s
   status         -> s
   detector_score -> d
   detector_label -> s
 => "iissssds"
*/
$stmt->bind_param(
    "iissssds",
    $book_id,
    $user_id,
    $username,
    $email,
    $comment,
    $status,
    $detector_score,
    $detector_label
);

$ok = $stmt->execute();
if (!$ok) {
    error_log('Insert comment failed: ' . $stmt->error);
    $_SESSION['comment_error'] = 'Unable to save your comment.';
} else {
    if ($status === 'approved') {
        $_SESSION['comment_msg'] = 'Comment posted successfully.';
    } elseif ($status === 'flagged') {
        $_SESSION['comment_msg'] = 'Your comment was flagged and is waiting for admin review.';
    } else { // rejected
        $_SESSION['comment_msg'] = 'Your comment was rejected by automatic moderation.';
    }
}

$stmt->close();

// 8. Redirect back to book page
header("Location: book_details.php?id={$book_id}#comments");
exit;
