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

if (!isLoggedIn()) {
    jsonResponse(['success' => false, 'error' => 'Unauthorized'], 401);
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(['success' => false, 'error' => 'Invalid request'], 400);
}

$product_id = (int)($_POST['product_id'] ?? 0);
$comment = escape($_POST['comment'] ?? '');

if ($product_id <= 0) {
    jsonResponse(['success' => false, 'error' => 'Invalid product'], 400);
}

if (empty($comment)) {
    jsonResponse(['success' => false, 'error' => 'Comment cannot be empty'], 400);
}

$user_id = $_SESSION['user_id'];

// Insert comment
$query = "INSERT INTO product_comments (product_id, user_id, comment) 
          VALUES ($product_id, $user_id, '$comment')";

if ($db->query($query)) {
    // Get comment info for display
    $get_result = $db->query("SELECT pc.*, u.name FROM product_comments pc 
                              JOIN users u ON pc.user_id = u.id 
                              WHERE pc.id = " . $db->insert_id);
    $new_comment = $get_result->fetch_assoc();
    
    // Audit log
    $product_result = $db->query("SELECT name FROM products WHERE id = $product_id");
    $product_name = $product_result->fetch_assoc()['name'];
    auditLog('comment', 'products', $product_id, $product_name, [], ['comment' => substr($comment, 0, 100)]);
    
    jsonResponse([
        'success' => true,
        'message' => 'Notă adăugată',
        'comment' => $new_comment
    ], 200);
} else {
    jsonResponse(['success' => false, 'error' => 'Database error'], 500);
}
?>
