<?php
session_start();
include 'layouts/dbconn.php';

if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] !== 1) {
    http_response_code(403);
    echo json_encode(['success' => false, 'error' => 'Insufficient permissions']);
    exit;
}

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

try {
    $data = json_decode(file_get_contents('php://input'), true);
    $menu_id = $data['menu_id'] ?? null;

    if (!$menu_id) {
        throw new Exception('Menu ID is required');
    }

    // Start transaction
    $conn->begin_transaction();

    // Delete all child menu items first (recursive delete)
    function deleteChildren($conn, $parent_id) {
        $sql = "SELECT menu_id FROM menu_items WHERE parent_id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param('i', $parent_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        while ($row = $result->fetch_assoc()) {
            deleteChildren($conn, $row['menu_id']);
            
            // Delete child menu item
            $delete_sql = "DELETE FROM menu_items WHERE menu_id = ?";
            $delete_stmt = $conn->prepare($delete_sql);
            $delete_stmt->bind_param('i', $row['menu_id']);
            $delete_stmt->execute();
        }
    }

    // Delete children first
    deleteChildren($conn, $menu_id);

    // Delete the parent menu item
    $sql = "DELETE FROM menu_items WHERE menu_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('i', $menu_id);
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to delete menu item');
    }

    // Commit transaction
    $conn->commit();

    echo json_encode([
        'success' => true,
        'message' => 'Menu item and its children deleted successfully'
    ]);

} catch (Exception $e) {
    if ($conn->inTransaction()) {
        $conn->rollback();
    }
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}

$conn->close();
?>