<?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("=== Delete 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
$comment_id = isset($_POST['comment_id']) ? intval($_POST['comment_id']) : 0;

error_log("Comment ID: " . $comment_id);

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

// Get the comment to verify ownership
try {
    error_log("Attempting to get comment by ID: " . $comment_id);
    $existing_comment = getCommentById($pdo, $comment_id);
    error_log("getCommentById result: " . print_r($existing_comment, true));
    
    if (!$existing_comment) {
        error_log("Comment not found");
        echo json_encode(['success' => false, 'message' => 'التعليق غير موجود.']);
        exit;
    }
    
    // Check if the comment belongs to the current user
    if ($existing_comment['user_id'] != $_SESSION['user_id']) {
        error_log("User ID mismatch. Comment user_id: " . $existing_comment['user_id'] . ", Session user_id: " . $_SESSION['user_id']);
        echo json_encode(['success' => false, 'message' => 'ليس لديك صلاحية لحذف هذا التعليق.']);
        exit;
    }
    
    error_log("Ownership verified");
    
    // Delete comment from database
    error_log("Attempting to delete comment");
    $result = deleteProductComment($pdo, $comment_id, $_SESSION['user_id']);
    error_log("deleteProductComment result: " . ($result ? "true" : "false"));
    
    if ($result) {
        error_log("Successfully deleted comment");
        echo json_encode([
            'success' => true, 
            'message' => 'تم حذف التعليق بنجاح.'
        ]);
    } else {
        error_log("Failed to delete comment from database");
        echo json_encode(['success' => false, 'message' => 'فشل في حذف التعليق. يرجى المحاولة مرة أخرى.']);
    }
} catch (Exception $e) {
    error_log("Exception in delete comment: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'حدث خطأ أثناء حذف التعليق.']);
}
?>