<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/config.php';

$auth = new Auth();
$auth->requireRole(['restaurant_admin', 'restaurant_manager', 'cashier', 'kitchen_staff', 'waiter']);

$csrf = new CSRF();
$restaurantId = $auth->restaurantId();
$userId = $auth->userId();
$db = Database::getInstance();

$action = $_GET['action'] ?? $_POST['action'] ?? '';
$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET' && strpos($action, 'get_') === 0) {
    $id = (int)($_GET['id'] ?? 0);

    if ($action === 'get_variation') {
        $var = $db->query("SELECT * FROM item_variations WHERE id = ? AND restaurant_id = ?", [$id, $restaurantId])->fetch();
        if ($var) jsonResponse(true, 'ok', ['variation' => $var]);
        jsonResponse(false, 'Not found');
    }
    if ($action === 'get_addon_group') {
        $group = $db->query("SELECT * FROM addon_groups WHERE id = ? AND restaurant_id = ?", [$id, $restaurantId])->fetch();
        if ($group) jsonResponse(true, 'ok', ['group' => $group]);
        jsonResponse(false, 'Not found');
    }
    if ($action === 'get_addon') {
        $addon = $db->query("SELECT * FROM addons WHERE id = ? AND restaurant_id = ?", [$id, $restaurantId])->fetch();
        if ($addon) jsonResponse(true, 'ok', ['addon' => $addon]);
        jsonResponse(false, 'Not found');
    }
}

if ($method === 'POST') {
    if (empty($_POST['csrf_token']) || !$csrf->verify($_POST['csrf_token'])) {
        jsonResponse(false, 'Invalid CSRF token');
    }

    if ($action === 'add_variation' || $action === 'edit_variation') {
        $id = (int)($_POST['variation_id'] ?? 0);
        $menuItemId = (int)($_POST['menu_item_id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $price = (float)($_POST['price'] ?? 0);
        $sortOrder = (int)($_POST['sort_order'] ?? 0);
        $status = (int)($_POST['status'] ?? 1);

        if (empty($name)) jsonResponse(false, 'Name is required');
        if ($menuItemId <= 0) jsonResponse(false, 'Please select a menu item');

        $checkItem = $db->query("SELECT id FROM menu_items WHERE id = ? AND restaurant_id = ?", [$menuItemId, $restaurantId])->fetch();
        if (!$checkItem) jsonResponse(false, 'Menu item not found');

        if ($action === 'add_variation') {
            $db->insert('item_variations', [
                'restaurant_id' => $restaurantId,
                'menu_item_id' => $menuItemId,
                'name' => $name,
                'price' => $price,
                'status' => $status,
                'sort_order' => $sortOrder,
            ]);
            jsonResponse(true, 'Variation added successfully');
        } else {
            $db->update('item_variations', [
                'menu_item_id' => $menuItemId,
                'name' => $name,
                'price' => $price,
                'status' => $status,
                'sort_order' => $sortOrder,
            ], 'id = ? AND restaurant_id = ?', [$id, $restaurantId]);
            jsonResponse(true, 'Variation updated successfully');
        }
    }

    if ($action === 'delete_variation') {
        $id = (int)($_POST['id'] ?? 0);
        $db->delete('item_variations', 'id = ? AND restaurant_id = ?', [$id, $restaurantId]);
        jsonResponse(true, 'Variation deleted');
    }

    if ($action === 'add_addon_group' || $action === 'edit_addon_group') {
        $id = (int)($_POST['addon_group_id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $isRequired = isset($_POST['is_required']) ? 1 : 0;
        $minSelect = (int)($_POST['min_select'] ?? 0);
        $maxSelect = (int)($_POST['max_select'] ?? 10);
        $sortOrder = (int)($_POST['sort_order'] ?? 0);
        $status = (int)($_POST['status'] ?? 1);

        if (empty($name)) jsonResponse(false, 'Group name is required');

        if ($action === 'add_addon_group') {
            $db->insert('addon_groups', [
                'restaurant_id' => $restaurantId,
                'name' => $name,
                'is_required' => $isRequired,
                'min_select' => $minSelect,
                'max_select' => $maxSelect,
                'sort_order' => $sortOrder,
                'status' => $status,
            ]);
            jsonResponse(true, 'Add-on group created');
        } else {
            $db->update('addon_groups', [
                'name' => $name,
                'is_required' => $isRequired,
                'min_select' => $minSelect,
                'max_select' => $maxSelect,
                'sort_order' => $sortOrder,
                'status' => $status,
            ], 'id = ? AND restaurant_id = ?', [$id, $restaurantId]);
            jsonResponse(true, 'Add-on group updated');
        }
    }

    if ($action === 'delete_addon_group') {
        $id = (int)($_POST['id'] ?? 0);
        $db->delete('addon_groups', 'id = ? AND restaurant_id = ?', [$id, $restaurantId]);
        jsonResponse(true, 'Add-on group deleted');
    }

    if ($action === 'add_addon' || $action === 'edit_addon') {
        $id = (int)($_POST['addon_id'] ?? 0);
        $groupId = (int)($_POST['addon_group_id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $price = (float)($_POST['price'] ?? 0);
        $sortOrder = (int)($_POST['sort_order'] ?? 0);
        $status = (int)($_POST['status'] ?? 1);

        if (empty($name)) jsonResponse(false, 'Addon name is required');
        if ($groupId <= 0) jsonResponse(false, 'Addon group not found');

        if ($action === 'add_addon') {
            $db->insert('addons', [
                'restaurant_id' => $restaurantId,
                'addon_group_id' => $groupId,
                'name' => $name,
                'price' => $price,
                'sort_order' => $sortOrder,
                'status' => $status,
            ]);
            jsonResponse(true, 'Addon added');
        } else {
            $db->update('addons', [
                'name' => $name,
                'price' => $price,
                'sort_order' => $sortOrder,
                'status' => $status,
            ], 'id = ? AND restaurant_id = ?', [$id, $restaurantId]);
            jsonResponse(true, 'Addon updated');
        }
    }

    if ($action === 'delete_addon') {
        $id = (int)($_POST['id'] ?? 0);
        $db->delete('addons', 'id = ? AND restaurant_id = ?', [$id, $restaurantId]);
        jsonResponse(true, 'Addon deleted');
    }
}

jsonResponse(false, 'Invalid request');
