<?php
/**
 * ============================================================
 * AJAX: Submit Review
 * ============================================================
 */

// Initialize
define('BASE_PATH', dirname(dirname(dirname(__DIR__))));
require_once BASE_PATH . '/app/config/config.php';

// Start session
if (session_status() === PHP_SESSION_NONE) {
    session_name(SESSION_NAME);
    session_start();
}

// Must be AJAX POST
if (!isAjax() || !isPost()) {
    Response::error('Invalid request', [], 400);
}

// Validate CSRF
if (!csrf_validate()) {
    Response::csrfError();
}

// Must be logged in
if (!isLoggedIn()) {
    Response::unauthorized('রিভিউ দিতে লগইন করুন');
}

// Load service
require_once APP_PATH . '/services/review_service.php';

// Get data
$productId = (int)post('product_id');
$rating = (int)post('rating');
$title = sanitize(post('review_title'));
$text = sanitize(post('review_text'));
$orderId = (int)post('order_id') ?: null;

// Validate
if ($productId < 1) {
    Response::error('অবৈধ পণ্য');
}

if ($rating < 1 || $rating > 5) {
    Response::error('রেটিং ১-৫ এর মধ্যে হতে হবে');
}

// Submit review
$result = ReviewService::submit(
    $productId,
    getUserId(),
    $rating,
    $title,
    $text,
    $orderId
);

if ($result['success']) {
    Response::success($result['message']);
} else {
    Response::error($result['message']);
}
