<?php
/**
 * rate_item.php — AJAX endpoint for submitting/updating ratings
 * Version: 1.0.0
 *
 * POST params: item_type (submission|content), item_id (int), rating (1-5)
 * Returns JSON: { success: bool, avg_rating: float, total_ratings: int, message: string }
 */
require_once __DIR__ . '/config.php';

// Ensure session is active
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

header('Content-Type: application/json; charset=utf-8');

// ----- Auth check -----
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'You must be logged in to rate.']);
    exit;
}

// ----- Method check -----
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed.']);
    exit;
}

// ----- Input validation -----
$user_id = intval($_SESSION['user_id']);

$item_type = isset($_POST['item_type']) ? sanitize_text_field(strval($_POST['item_type'])) : '';
$item_id = isset($_POST['item_id']) ? intval($_POST['item_id']) : 0;
$rating = isset($_POST['rating']) ? intval($_POST['rating']) : 0;

if (!in_array($item_type, ['submission', 'content'], true)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid item type.']);
    exit;
}

if ($item_id <= 0) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid item ID.']);
    exit;
}

if ($rating < 1 || $rating > 5) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Rating must be between 1 and 5.']);
    exit;
}

// ----- Database connection -----
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($conn->connect_error) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database connection failed.']);
    exit;
}
$conn->set_charset('utf8mb4');

// ----- Verify item exists -----
if ($item_type === 'submission') {
    $check = $conn->prepare("SELECT id FROM submissions WHERE id = ? AND is_verified = 1");
} else {
    $check = $conn->prepare("SELECT id FROM content WHERE id = ? AND status = 'approved'");
}
$check->bind_param("i", $item_id);
$check->execute();
if ($check->get_result()->num_rows === 0) {
    $check->close();
    $conn->close();
    http_response_code(404);
    echo json_encode(['success' => false, 'message' => 'Item not found.']);
    exit;
}
$check->close();

// ----- Upsert rating -----
$stmt = $conn->prepare(
    "INSERT INTO ratings (user_id, item_type, item_id, rating)
     VALUES (?, ?, ?, ?)
     ON DUPLICATE KEY UPDATE rating = VALUES(rating), updated_at = CURRENT_TIMESTAMP"
);
$stmt->bind_param("isii", $user_id, $item_type, $item_id, $rating);

if (!$stmt->execute()) {
    $stmt->close();
    $conn->close();
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Failed to save rating.']);
    exit;
}
$stmt->close();

// ----- Fetch updated averages -----
$avg_stmt = $conn->prepare("SELECT AVG(rating) AS avg_rating, COUNT(*) AS total FROM ratings WHERE item_type = ? AND item_id = ?");
$avg_stmt->bind_param("si", $item_type, $item_id);
$avg_stmt->execute();
$avg_result = $avg_stmt->get_result()->fetch_assoc();
$avg_stmt->close();
$conn->close();

echo json_encode([
    'success' => true,
    'avg_rating' => round((float) ($avg_result['avg_rating'] ?? 0), 1),
    'total_ratings' => (int) ($avg_result['total'] ?? 0),
    'user_rating' => $rating,
    'message' => 'Rating saved successfully.',
]);
