<?php
require_once '../includes/config.php';
require_once '../includes/db.php';
require_once '../includes/functions.php';

// Log all errors to a file
ini_set('log_errors', 1);
ini_set('error_log', 'debug.log');

// Log the request
error_log("=== Add Comment Request ===");
error_log("Request method: " . $_SERVER['REQUEST_METHOD']);
error_log("POST data: " . print_r($_POST, true));
error_log("Session data: " . print_r($_SESSION, true));

header('Content-Type: application/json');

// Check if user is logged in
if (!isLoggedIn()) {
    error_log("User not logged in");
    echo json_encode(['success' => false, 'message' => 'يجب تسجيل الدخول لإضافة تعليق.']);
    exit;
}

error_log("User is logged in, user_id: " . $_SESSION['user_id']);

// Check if request method is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    error_log("Invalid request method");
    echo json_encode(['success' => false, 'message' => 'طلب غير صالح.']);
    exit;
}

// Get POST data
$product_id = isset($_POST['product_id']) ? intval($_POST['product_id']) : 0;
$comment = isset($_POST['comment']) ? trim($_POST['comment']) : '';

error_log("Product ID: " . $product_id);
error_log("Comment: " . $comment);

// Validate input
if ($product_id <= 0) {
    error_log("Invalid product ID");
    echo json_encode(['success' => false, 'message' => 'معرف المنتج غير صالح.']);
    exit;
}

if (empty($comment)) {
    error_log("Empty comment");
    echo json_encode(['success' => false, 'message' => 'التعليق لا يمكن أن يكون فارغاً.']);
    exit;
}

if (strlen($comment) > 500) {
    error_log("Comment too long");
    echo json_encode(['success' => false, 'message' => 'التعليق طويل جداً. الحد الأقصى هو 500 حرف.']);
    exit;
}

error_log("Input validation passed");

// Add comment to database
try {
    error_log("Attempting to add comment to database");
    $result = addProductComment($pdo, $product_id, $_SESSION['user_id'], $comment);
    error_log("addProductComment result: " . ($result ? "true" : "false"));
    
    if ($result) {
        // Get the newly added comment with user info
        $stmt = $pdo->prepare("
            SELECT pc.*, u.username 
            FROM product_comments pc 
            JOIN users u ON pc.user_id = u.id 
            WHERE pc.product_id = ? AND pc.user_id = ? 
            ORDER BY pc.created_at DESC 
            LIMIT 1
        ");
        $stmt->execute([$product_id, $_SESSION['user_id']]);
        $new_comment = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($new_comment) {
            $new_comment['formatted_time'] = formatTimeAgo($new_comment['created_at']);
            error_log("Successfully added comment, returning with comment data");
            echo json_encode([
                'success' => true, 
                'message' => 'تم إضافة التعليق بنجاح.',
                'comment' => $new_comment
            ]);
        } else {
            error_log("Successfully added comment, but couldn't retrieve it");
            echo json_encode(['success' => true, 'message' => 'تم إضافة التعليق بنجاح.']);
        }
    } else {
        error_log("Failed to add comment to database");
        echo json_encode(['success' => false, 'message' => 'فشل في إضافة التعليق. يرجى المحاولة مرة أخرى.']);
    }
} catch (Exception $e) {
    error_log("Exception in addProductComment: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'حدث خطأ أثناء إضافة التعليق.']);
}
?>