<?php
require_once __DIR__ . '/../includes/config.php';

// Check if logged in
if (!isLoggedIn()) {
    handleError('Trebuie să fii logat', 401);
}

// Get data
$order_id = $_POST['order_id'] ?? null;
$comment = $_POST['comment'] ?? '';
$user_id = $_SESSION['user_id'];

// Validation
if (!$order_id || !is_numeric($order_id)) {
    handleError('ID comenză invalid');
}

if (empty(trim($comment))) {
    handleError('Comentariul nu poate fi gol');
}

if (strlen($comment) > 5000) {
    handleError('Comentariul e prea lung');
}

// Check if order exists
$result = $db->query("SELECT id FROM orders WHERE id = $order_id LIMIT 1");
if (!$result || $result->num_rows === 0) {
    handleError('Comanda nu există');
}

// Insert comment
$escaped_comment = escape($comment);
$insert_query = "INSERT INTO order_comments (order_id, user_id, comment) VALUES ($order_id, $user_id, '$escaped_comment')";

if ($db->query($insert_query)) {
    handleSuccess(['comment_id' => $db->insert_id], 'Comentariu adăugat');
} else {
    handleError('Eroare la adăugarea comentariului');
}
?>
