<?php
/**
 * Agentic Square - Multi-Vendor Engine Review Injection Processor Endpoint
 * Path: client/review-endpoint.php
 */

session_start();
require_once __DIR__ . '/../config/config.php';

// Modified Access Guard: Fallback checking approach matches the automatic rule update pattern
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_SESSION['user_id']) || $_SESSION['user_role'] === 'seller' || $_SESSION['user_role'] === 'admin') {
    header('HTTP/1.1 403 Forbidden');
    echo json_encode(['success' => false, 'message' => 'Restricted transaction authorization framework access violation.']);
    exit;
}

// Intercept Payload Input Parameters
$order_id    = filter_input(INPUT_POST, 'order_id', FILTER_VALIDATE_INT);
$item_id     = filter_input(INPUT_POST, 'item_id', FILTER_VALIDATE_INT);
$seller_id   = filter_input(INPUT_POST, 'seller_id', FILTER_VALIDATE_INT);
$rating      = filter_input(INPUT_POST, 'rating', FILTER_VALIDATE_INT);
$review_text = filter_input(INPUT_POST, 'review_text', FILTER_DEFAULT);

$user_id     = (int)$_SESSION['user_id'];
$client_name = $_SESSION['user_name'] ?? 'Verified Buyer';

if (!$order_id || !$item_id || !$seller_id || !$rating || $rating < 1 || $rating > 5) {
    echo json_encode(['success' => false, 'message' => 'Structural parameter validation constraints missing.']);
    exit;
}

try {
    // Structural integrity gate check
    $checkStmt = $pdo->prepare("
        SELECT o.item_name, s.seller_name, r.id AS review_id
        FROM orders o
        LEFT JOIN sellers s ON o.seller_id = s.user_id
        LEFT JOIN reviews r ON o.id = r.order_id
        WHERE o.id = ? AND o.user_id = ? AND o.payment_status = 'Paid'
        LIMIT 1
    ");
    $checkStmt->execute([$order_id, $user_id]);
    $orderContext = $checkStmt->fetch();

    if (!$orderContext) {
        echo json_encode(['success' => false, 'message' => 'Order item processing frame reference error.']);
        exit;
    }

    if ($orderContext['review_id']) {
        echo json_encode(['success' => false, 'message' => 'Duplication Constraint: This purchase line is already reviewed.']);
        exit;
    }

    $item_name   = $orderContext['item_name'];
    $seller_name = $orderContext['seller_name'] ?? 'System Core Platform';

    // Insert Evaluation Entry Record
    $insertStmt = $pdo->prepare("
        INSERT INTO reviews (order_id, user_id, client_name, item_id, item_name, seller_id, seller_name, rating, review_text)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");
    
    $insertStmt->execute([
        $order_id,
        $user_id,
        $client_name,
        $item_id,
        $item_name,
        $seller_id,
        $seller_name,
        $rating,
        trim($review_text)
    ]);

    echo json_encode(['success' => true, 'message' => 'Your code review and assessment rating has been logged successfully.']);
    exit;

} catch (\PDOException $e) {
    header('HTTP/1.1 500 Internal Server Error');
    echo json_encode(['success' => false, 'message' => 'Infrastructure Processing Exception: ' . $e->getMessage()]);
    exit;
}