<?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) {
    $stmt = $conn->prepare("DELETE FROM menu_filters WHERE id = ?");
    $stmt->bind_param("i", $id);

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

// ===== 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) {
    $stmt = $conn->prepare("DELETE FROM menu_subcategories WHERE id = ?");
    $stmt->bind_param("i", $id);

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

// ===== 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']) && file_exists($row['image_path'])) {
                unlink($row['image_path']);
            }
        }

        $stmt = $conn->prepare("UPDATE menu_items SET item_name = ?, description = ?, price = ?, display_order = ?, is_available = ?, image_path = ? WHERE id = ?");
        $stmt->bind_param("ssdisii", $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) {
    // 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 = $conn->prepare("DELETE FROM menu_items WHERE id = ?");
    $stmt->bind_param("i", $id);

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

// ===== 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();
?>
