<?php
/**
 * Menu Management API
 * Handles CRUD operations for menu filters, subcategories, and menu items
 */

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

header('Content-Type: application/json');
require_once 'config.php';

// Get the action
$action = isset($_GET['action']) ? $_GET['action'] : (isset($_POST['action']) ? $_POST['action'] : '');

try {
    switch ($action) {
        // ===== MENU FILTERS =====
        case 'create_filter':
            echo json_encode(createFilter($conn));
            break;
        case 'get_filters':
            echo json_encode(getFilters($conn));
            break;
        case 'get_filter':
            echo json_encode(getFilter($conn, $_GET['id'] ?? 0));
            break;
        case 'update_filter':
            echo json_encode(updateFilter($conn));
            break;
        case 'delete_filter':
            echo json_encode(deleteFilter($conn, $_POST['id'] ?? 0));
            break;

        // ===== MENU SUBCATEGORIES =====
        case 'create_subcategory':
            echo json_encode(createSubcategory($conn));
            break;
        case 'get_subcategories':
            echo json_encode(getSubcategories($conn, $_GET['filter_id'] ?? 0));
            break;
        case 'update_subcategory':
            echo json_encode(updateSubcategory($conn));
            break;
        case 'delete_subcategory':
            echo json_encode(deleteSubcategory($conn, $_POST['id'] ?? 0));
            break;

        // ===== MENU ITEMS =====
        case 'create_item':
            echo json_encode(createMenuItem($conn));
            break;
        case 'get_items':
            echo json_encode(getMenuItems($conn, $_GET['subcategory_id'] ?? 0));
            break;
        case 'get_item':
            echo json_encode(getMenuItem($conn, $_GET['id'] ?? 0));
            break;
        case 'update_item':
            echo json_encode(updateMenuItem($conn));
            break;
        case 'delete_item':
            echo json_encode(deleteMenuItem($conn, $_POST['id'] ?? 0));
            break;

        // ===== PUBLIC API =====
        case 'get_menu':
            echo json_encode(getPublicMenu($conn));
            break;

        default:
            echo json_encode([
                'success' => false,
                'message' => 'Invalid action: ' . $action
            ]);
    }
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'API Error: ' . $e->getMessage()
    ]);
}

// ===== FILTER FUNCTIONS =====
function createFilter($conn) {
    $filter_name = isset($_POST['filter_name']) ? trim($_POST['filter_name']) : '';
    $description = isset($_POST['description']) ? trim($_POST['description']) : '';
    $display_order = isset($_POST['display_order']) ? (int)$_POST['display_order'] : 0;

    if (empty($filter_name)) {
        return ['success' => false, 'message' => 'Filter name is required'];
    }

    $stmt = $conn->prepare("INSERT INTO menu_filters (filter_name, description, display_order) VALUES (?, ?, ?)");
    $stmt->bind_param("ssi", $filter_name, $description, $display_order);

    if ($stmt->execute()) {
        return ['success' => true, 'message' => 'Filter created', 'id' => $conn->insert_id];
    }
    return ['success' => false, 'message' => 'Failed to create filter'];
}

function getFilters($conn) {
    $result = $conn->query("SELECT * FROM menu_filters ORDER BY display_order ASC");
    $filters = [];
    
    while ($row = $result->fetch_assoc()) {
        $filters[] = $row;
    }
    
    return ['success' => true, 'data' => $filters];
}

function getFilter($conn, $id) {
    $stmt = $conn->prepare("SELECT * FROM menu_filters WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($row = $result->fetch_assoc()) {
        return ['success' => true, 'data' => $row];
    }
    return ['success' => false, 'message' => 'Filter not found'];
}

function updateFilter($conn) {
    $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
    $filter_name = isset($_POST['filter_name']) ? trim($_POST['filter_name']) : '';
    $description = isset($_POST['description']) ? trim($_POST['description']) : '';
    $display_order = isset($_POST['display_order']) ? (int)$_POST['display_order'] : 0;

    if (!$id || empty($filter_name)) {
        return ['success' => false, 'message' => 'Invalid data'];
    }

    $stmt = $conn->prepare("UPDATE menu_filters SET filter_name = ?, description = ?, display_order = ? WHERE id = ?");
    $stmt->bind_param("ssii", $filter_name, $description, $display_order, $id);

    if ($stmt->execute()) {
        return ['success' => true, 'message' => 'Filter updated'];
    }
    return ['success' => false, 'message' => 'Failed to update filter'];
}

function deleteFilter($conn, $id) {
    try {
        // Start transaction
        $conn->begin_transaction();

        // Step 1: Get all subcategories in this filter
        $get_subcategories_stmt = $conn->prepare("SELECT id FROM menu_subcategories WHERE filter_id = ?");
        $get_subcategories_stmt->bind_param("i", $id);
        $get_subcategories_stmt->execute();
        $subcategories_result = $get_subcategories_stmt->get_result();
        
        $subcategory_ids = [];
        while ($row = $subcategories_result->fetch_assoc()) {
            $subcategory_ids[] = $row['id'];
        }
        $get_subcategories_stmt->close();

        // Step 2: For each subcategory, get all menu items
        if (!empty($subcategory_ids)) {
            $subcategory_placeholders = implode(',', array_fill(0, count($subcategory_ids), '?'));
            $get_items_stmt = $conn->prepare("SELECT id FROM menu_items WHERE subcategory_id IN ($subcategory_placeholders)");
            
            $types = str_repeat('i', count($subcategory_ids));
            $get_items_stmt->bind_param($types, ...$subcategory_ids);
            $get_items_stmt->execute();
            $items_result = $get_items_stmt->get_result();
            
            $item_ids = [];
            while ($row = $items_result->fetch_assoc()) {
                $item_ids[] = $row['id'];
            }
            $get_items_stmt->close();

            // Step 3: Delete dine_in_order_items that reference these menu items
            if (!empty($item_ids)) {
                $item_placeholders = implode(',', array_fill(0, count($item_ids), '?'));
                $delete_order_items_sql = "DELETE FROM dine_in_order_items WHERE item_id IN ($item_placeholders)";
                $delete_order_items_stmt = $conn->prepare($delete_order_items_sql);
                
                $item_types = str_repeat('i', count($item_ids));
                $delete_order_items_stmt->bind_param($item_types, ...$item_ids);
                $delete_order_items_stmt->execute();
                $delete_order_items_stmt->close();

                // Step 4: Delete cart items that reference these menu items
                $delete_cart_items_sql = "DELETE FROM cart WHERE item_id IN ($item_placeholders)";
                $delete_cart_items_stmt = $conn->prepare($delete_cart_items_sql);
                $delete_cart_items_stmt->bind_param($item_types, ...$item_ids);
                $delete_cart_items_stmt->execute();
                $delete_cart_items_stmt->close();
            }

            // Step 5: Delete all menu items in these subcategories
            $delete_items_sql = "DELETE FROM menu_items WHERE subcategory_id IN ($subcategory_placeholders)";
            $delete_items_stmt = $conn->prepare($delete_items_sql);
            $delete_items_stmt->bind_param($types, ...$subcategory_ids);
            $delete_items_stmt->execute();
            $delete_items_stmt->close();

            // Step 6: Delete all subcategories in this filter
            $delete_subcategories_sql = "DELETE FROM menu_subcategories WHERE filter_id = ?";
            $delete_subcategories_stmt = $conn->prepare($delete_subcategories_sql);
            $delete_subcategories_stmt->bind_param("i", $id);
            $delete_subcategories_stmt->execute();
            $delete_subcategories_stmt->close();
        }

        // Step 7: Delete the filter
        $delete_filter_stmt = $conn->prepare("DELETE FROM menu_filters WHERE id = ?");
        $delete_filter_stmt->bind_param("i", $id);
        
        if ($delete_filter_stmt->execute()) {
            $delete_filter_stmt->close();
            $conn->commit();
            return ['success' => true, 'message' => 'Filter and all related items deleted successfully'];
        } else {
            throw new Exception('Failed to delete filter: ' . $delete_filter_stmt->error);
        }
        
    } catch (Exception $e) {
        $conn->rollback();
        return ['success' => false, 'message' => 'Failed to delete filter: ' . $e->getMessage()];
    }
}

// ===== SUBCATEGORY FUNCTIONS =====
function createSubcategory($conn) {
    $filter_id = isset($_POST['filter_id']) ? (int)$_POST['filter_id'] : 0;
    $subcategory_name = isset($_POST['subcategory_name']) ? trim($_POST['subcategory_name']) : '';
    $display_order = isset($_POST['display_order']) ? (int)$_POST['display_order'] : 0;

    if (!$filter_id || empty($subcategory_name)) {
        return ['success' => false, 'message' => 'Filter ID and subcategory name required'];
    }

    $stmt = $conn->prepare("INSERT INTO menu_subcategories (filter_id, subcategory_name, display_order) VALUES (?, ?, ?)");
    $stmt->bind_param("isi", $filter_id, $subcategory_name, $display_order);

    if ($stmt->execute()) {
        return ['success' => true, 'message' => 'Subcategory created', 'id' => $conn->insert_id];
    }
    return ['success' => false, 'message' => 'Failed to create subcategory'];
}

function getSubcategories($conn, $filter_id) {
    $stmt = $conn->prepare("SELECT * FROM menu_subcategories WHERE filter_id = ? ORDER BY display_order ASC");
    $stmt->bind_param("i", $filter_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $subcategories = [];
    
    while ($row = $result->fetch_assoc()) {
        $subcategories[] = $row;
    }
    
    return ['success' => true, 'data' => $subcategories];
}

function updateSubcategory($conn) {
    $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
    $subcategory_name = isset($_POST['subcategory_name']) ? trim($_POST['subcategory_name']) : '';
    $display_order = isset($_POST['display_order']) ? (int)$_POST['display_order'] : 0;

    if (!$id || empty($subcategory_name)) {
        return ['success' => false, 'message' => 'Invalid data'];
    }

    $stmt = $conn->prepare("UPDATE menu_subcategories SET subcategory_name = ?, display_order = ? WHERE id = ?");
    $stmt->bind_param("sii", $subcategory_name, $display_order, $id);

    if ($stmt->execute()) {
        return ['success' => true, 'message' => 'Subcategory updated'];
    }
    return ['success' => false, 'message' => 'Failed to update subcategory'];
}

function deleteSubcategory($conn, $id) {
    try {
        // Start transaction for data integrity
        $conn->begin_transaction();

        // Step 1: Get all menu items in this subcategory
        $get_items_stmt = $conn->prepare("SELECT id FROM menu_items WHERE subcategory_id = ?");
        $get_items_stmt->bind_param("i", $id);
        $get_items_stmt->execute();
        $items_result = $get_items_stmt->get_result();
        
        $item_ids = [];
        while ($row = $items_result->fetch_assoc()) {
            $item_ids[] = $row['id'];
        }
        $get_items_stmt->close();

        // Step 2: Delete dine_in_order_items that reference these menu items
        if (!empty($item_ids)) {
            $placeholders = implode(',', array_fill(0, count($item_ids), '?'));
            $delete_order_items_sql = "DELETE FROM dine_in_order_items WHERE item_id IN ($placeholders)";
            $delete_order_items_stmt = $conn->prepare($delete_order_items_sql);
            
            // Build bind parameters dynamically
            $types = str_repeat('i', count($item_ids));
            $delete_order_items_stmt->bind_param($types, ...$item_ids);
            $delete_order_items_stmt->execute();
            $delete_order_items_stmt->close();

            // Step 3: Delete cart items that reference these menu items
            $delete_cart_items_sql = "DELETE FROM cart WHERE item_id IN ($placeholders)";
            $delete_cart_items_stmt = $conn->prepare($delete_cart_items_sql);
            $delete_cart_items_stmt->bind_param($types, ...$item_ids);
            $delete_cart_items_stmt->execute();
            $delete_cart_items_stmt->close();

            // Step 4: Delete the menu items themselves
            $delete_items_sql = "DELETE FROM menu_items WHERE subcategory_id = ?";
            $delete_items_stmt = $conn->prepare($delete_items_sql);
            $delete_items_stmt->bind_param("i", $id);
            $delete_items_stmt->execute();
            $delete_items_stmt->close();
        }

        // Step 5: Delete the subcategory
        $delete_subcategory_stmt = $conn->prepare("DELETE FROM menu_subcategories WHERE id = ?");
        $delete_subcategory_stmt->bind_param("i", $id);
        
        if ($delete_subcategory_stmt->execute()) {
            $delete_subcategory_stmt->close();
            $conn->commit();
            return ['success' => true, 'message' => 'Subcategory and related items deleted successfully'];
        } else {
            throw new Exception('Failed to delete subcategory: ' . $delete_subcategory_stmt->error);
        }
        
    } catch (Exception $e) {
        $conn->rollback();
        return ['success' => false, 'message' => 'Failed to delete subcategory: ' . $e->getMessage()];
    }
}

// ===== MENU ITEM FUNCTIONS =====
function createMenuItem($conn) {
    $subcategory_id = isset($_POST['subcategory_id']) ? (int)$_POST['subcategory_id'] : 0;
    $item_name = isset($_POST['item_name']) ? trim($_POST['item_name']) : '';
    $description = isset($_POST['description']) ? trim($_POST['description']) : '';
    $price = isset($_POST['price']) ? (float)$_POST['price'] : 0;
    $display_order = isset($_POST['display_order']) ? (int)$_POST['display_order'] : 0;
    $is_available = isset($_POST['is_available']) ? (int)$_POST['is_available'] : 1;
    $image_path = '';

    if (!$subcategory_id || empty($item_name) || $price <= 0) {
        return ['success' => false, 'message' => 'Invalid menu item data'];
    }

    // Handle image upload
    if (!empty($_FILES['image']['name'])) {
        $upload_result = handleImageUpload($_FILES['image']);
        if (!$upload_result['success']) {
            return $upload_result;
        }
        $image_path = $upload_result['path'];
    }

    $stmt = $conn->prepare("INSERT INTO menu_items (subcategory_id, item_name, description, price, image_path, display_order, is_available) VALUES (?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("issdsii", $subcategory_id, $item_name, $description, $price, $image_path, $display_order, $is_available);

    if ($stmt->execute()) {
        return ['success' => true, 'message' => 'Menu item created', 'id' => $conn->insert_id];
    }
    return ['success' => false, 'message' => 'Failed to create menu item'];
}

function getMenuItems($conn, $subcategory_id) {
    $stmt = $conn->prepare("SELECT * FROM menu_items WHERE subcategory_id = ? ORDER BY display_order ASC");
    $stmt->bind_param("i", $subcategory_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $items = [];
    
    while ($row = $result->fetch_assoc()) {
        $items[] = $row;
    }
    
    return ['success' => true, 'data' => $items];
}

function getMenuItem($conn, $id) {
    $stmt = $conn->prepare("SELECT * FROM menu_items WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($row = $result->fetch_assoc()) {
        return ['success' => true, 'data' => $row];
    }
    return ['success' => false, 'message' => 'Menu item not found'];
}

function updateMenuItem($conn) {
    $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
    $item_name = isset($_POST['item_name']) ? trim($_POST['item_name']) : '';
    $description = isset($_POST['description']) ? trim($_POST['description']) : '';
    $price = isset($_POST['price']) ? (float)$_POST['price'] : 0;
    $display_order = isset($_POST['display_order']) ? (int)$_POST['display_order'] : 0;
    $is_available = isset($_POST['is_available']) ? (int)$_POST['is_available'] : 1;

    if (!$id || empty($item_name) || $price <= 0) {
        return ['success' => false, 'message' => 'Invalid data'];
    }

    $image_path = null;

    // Handle image upload if provided
    if (!empty($_FILES['image']['name'])) {
        $upload_result = handleImageUpload($_FILES['image']);
        if (!$upload_result['success']) {
            return $upload_result;
        }
        $image_path = $upload_result['path'];

        // Delete old image
        $stmt = $conn->prepare("SELECT image_path FROM menu_items WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($row = $result->fetch_assoc()) {
            if (!empty($row['image_path'])) {
                $old_image_abs_path = __DIR__ . '/../' . ltrim($row['image_path'], '/\\');
                if (file_exists($old_image_abs_path)) {
                    unlink($old_image_abs_path);
                }
            }
        }

        $stmt = $conn->prepare("UPDATE menu_items SET item_name = ?, description = ?, price = ?, display_order = ?, is_available = ?, image_path = ? WHERE id = ?");
        $stmt->bind_param("ssdiisi", $item_name, $description, $price, $display_order, $is_available, $image_path, $id);
    } else {
        $stmt = $conn->prepare("UPDATE menu_items SET item_name = ?, description = ?, price = ?, display_order = ?, is_available = ? WHERE id = ?");
        $stmt->bind_param("ssdiii", $item_name, $description, $price, $display_order, $is_available, $id);
    }

    if ($stmt->execute()) {
        return ['success' => true, 'message' => 'Menu item updated'];
    }
    return ['success' => false, 'message' => 'Failed to update menu item'];
}

function deleteMenuItem($conn, $id) {
    try {
        // Start transaction
        $conn->begin_transaction();

        // Get image path before deleting
        $stmt = $conn->prepare("SELECT image_path FROM menu_items WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($row = $result->fetch_assoc()) {
            if (!empty($row['image_path']) && file_exists($row['image_path'])) {
                unlink($row['image_path']);
            }
        }
        $stmt->close();

        // Delete dine_in_order_items that reference this menu item
        $delete_order_items_stmt = $conn->prepare("DELETE FROM dine_in_order_items WHERE item_id = ?");
        $delete_order_items_stmt->bind_param("i", $id);
        $delete_order_items_stmt->execute();
        $delete_order_items_stmt->close();

        // Delete cart items that reference this menu item
        $delete_cart_stmt = $conn->prepare("DELETE FROM cart WHERE item_id = ?");
        $delete_cart_stmt->bind_param("i", $id);
        $delete_cart_stmt->execute();
        $delete_cart_stmt->close();

        // Delete the menu item
        $stmt = $conn->prepare("DELETE FROM menu_items WHERE id = ?");
        $stmt->bind_param("i", $id);

        if ($stmt->execute()) {
            $stmt->close();
            $conn->commit();
            return ['success' => true, 'message' => 'Menu item and related orders deleted successfully'];
        } else {
            throw new Exception('Failed to delete menu item: ' . $stmt->error);
        }
        
    } catch (Exception $e) {
        $conn->rollback();
        return ['success' => false, 'message' => 'Failed to delete menu item: ' . $e->getMessage()];
    }
}

// ===== PUBLIC API =====
function getPublicMenu($conn) {
    $sql = "SELECT 
                f.id as filter_id,
                f.filter_name,
                f.display_order as filter_order,
                sc.id as subcategory_id,
                sc.subcategory_name,
                sc.display_order as subcategory_order,
                mi.id as item_id,
                mi.item_name,
                mi.description,
                mi.price,
                mi.image_path,
                mi.display_order as item_order,
                mi.is_available
            FROM menu_filters f
            LEFT JOIN menu_subcategories sc ON f.id = sc.filter_id
            LEFT JOIN menu_items mi ON sc.id = mi.subcategory_id
            WHERE mi.is_available = 1
            ORDER BY f.display_order ASC, sc.display_order ASC, mi.display_order ASC";

    $result = $conn->query($sql);
    $menu = [];

    while ($row = $result->fetch_assoc()) {
        // Initialize filter if not exists
        if (!isset($menu[$row['filter_id']])) {
            $menu[$row['filter_id']] = [
                'filter_id' => $row['filter_id'],
                'filter_name' => $row['filter_name'],
                'subcategories' => []
            ];
        }

        // Initialize subcategory if not exists
        if ($row['subcategory_id'] && !isset($menu[$row['filter_id']]['subcategories'][$row['subcategory_id']])) {
            $menu[$row['filter_id']]['subcategories'][$row['subcategory_id']] = [
                'subcategory_id' => $row['subcategory_id'],
                'subcategory_name' => $row['subcategory_name'],
                'items' => []
            ];
        }

        // Add item if exists
        if ($row['item_id']) {
            $menu[$row['filter_id']]['subcategories'][$row['subcategory_id']]['items'][] = [
                'item_id' => $row['item_id'],
                'item_name' => $row['item_name'],
                'description' => $row['description'],
                'price' => $row['price'],
                'image_path' => $row['image_path']
            ];
        }
    }

    // Reindex arrays
    $menu = array_values($menu);
    foreach ($menu as &$filter) {
        $filter['subcategories'] = array_values($filter['subcategories']);
    }

    return ['success' => true, 'data' => $menu];
}

// ===== HELPER FUNCTIONS =====
function handleImageUpload($file) {
    $upload_dir = __DIR__ . '/../assets/uploads/menu/';
    $web_path = 'assets/uploads/menu/';
    
    // Create directory if it doesn't exist
    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0755, true);
    }

    // Validate image
    $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
    $file_ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));

    if (!in_array($file_ext, $allowed)) {
        return ['success' => false, 'message' => 'Invalid image format'];
    }

    if ($file['size'] > 5 * 1024 * 1024) { // 5MB
        return ['success' => false, 'message' => 'Image too large (max 5MB)'];
    }

    $filename = 'menu_' . time() . '_' . bin2hex(random_bytes(4)) . '.' . $file_ext;
    $filepath = $upload_dir . $filename;
    $web_path_file = $web_path . $filename;

    if (move_uploaded_file($file['tmp_name'], $filepath)) {
        return ['success' => true, 'path' => $web_path_file];
    }

    return ['success' => false, 'message' => 'Failed to upload image'];
}

$conn->close();
?>
