<?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();
$baseUrl = getBaseUrl();

$action = $_GET['action'] ?? $_POST['action'] ?? '';

if ($action === 'toggle_status' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    if (empty($_POST['csrf_token']) || !$csrf->verify($_POST['csrf_token'])) {
        jsonResponse(false, 'Invalid CSRF token');
    }
    $id = (int)($_POST['id'] ?? 0);
    $item = $db->query("SELECT id, is_available FROM menu_items WHERE id = ? AND restaurant_id = ?", [$id, $restaurantId])->fetch();
    if (!$item) {
        jsonResponse(false, 'Item not found');
    }
    $newStatus = $item['is_available'] ? 0 : 1;
    $db->update('menu_items', ['is_available' => $newStatus], 'id = ?', [$id]);
    jsonResponse(true, 'Item ' . ($newStatus ? 'activated' : 'deactivated'));
}

if ($action === 'delete' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    if (empty($_POST['csrf_token']) || !$csrf->verify($_POST['csrf_token'])) {
        jsonResponse(false, 'Invalid CSRF token');
    }
    $id = (int)($_POST['id'] ?? 0);
    $item = $db->query("SELECT id, name FROM menu_items WHERE id = ? AND restaurant_id = ?", [$id, $restaurantId])->fetch();
    if (!$item) {
        jsonResponse(false, 'Item not found');
    }
    $db->delete('menu_items', 'id = ? AND restaurant_id = ?', [$id, $restaurantId]);
    $activityLog = new ActivityLog();
    $activityLog->log($userId, $restaurantId, 'menu', 'item_delete', 'Item "' . $item['name'] . '" deleted');
    jsonResponse(true, 'Item deleted successfully');
}

if ($action === 'duplicate' && $_SERVER['REQUEST_METHOD'] === 'GET') {
    $id = (int)($_GET['id'] ?? 0);
    $item = $db->query("SELECT * FROM menu_items WHERE id = ? AND restaurant_id = ?", [$id, $restaurantId])->fetch();
    if (!$item) {
        jsonResponse(false, 'Item not found');
    }
    unset($item['id']);
    $item['name'] = $item['name'] . ' (Copy)';
    $item['slug'] = $item['slug'] . '-copy-' . time();
    $item['view_count'] = 0;
    $item['order_count'] = 0;
    $item['created_at'] = date('Y-m-d H:i:s');
    $item['updated_at'] = date('Y-m-d H:i:s');
    $newId = $db->insert('menu_items', $item);

    $linkedGroups = $db->query("SELECT addon_group_id FROM item_addon_groups WHERE menu_item_id = ?", [$id])->fetchAll();
    foreach ($linkedGroups as $lg) {
        $db->insert('item_addon_groups', ['menu_item_id' => $newId, 'addon_group_id' => $lg['addon_group_id']]);
    }

    $activityLog = new ActivityLog();
    $activityLog->log($userId, $restaurantId, 'menu', 'item_duplicate', 'Item duplicated');
    redirect($baseUrl . '/restaurant-admin/item_form.php?id=' . $newId);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && in_array($action, ['add', 'edit'])) {
    if (empty($_POST['csrf_token']) || !$csrf->verify($_POST['csrf_token'])) {
        jsonResponse(false, 'Invalid CSRF token');
    }

    $id = (int)($_POST['item_id'] ?? 0);
    $categoryId = (int)($_POST['category_id'] ?? 0);
    $name = trim($_POST['name'] ?? '');
    $slug = trim($_POST['slug'] ?? slugify($name));
    $shortDescription = trim($_POST['short_description'] ?? '');
    $fullDescription = trim($_POST['full_description'] ?? '');
    $regularPrice = (float)($_POST['regular_price'] ?? 0);
    $offerPrice = !empty($_POST['offer_price']) ? (float)$_POST['offer_price'] : null;
    $costPrice = !empty($_POST['cost_price']) ? (float)$_POST['cost_price'] : null;
    $taxSetting = $_POST['tax_setting'] ?? 'default';
    $prepTime = !empty($_POST['prep_time']) ? (int)$_POST['prep_time'] : null;
    $calories = !empty($_POST['calories']) ? (int)$_POST['calories'] : null;
    $ingredients = trim($_POST['ingredients'] ?? '');
    $allergens = trim($_POST['allergens'] ?? '');
    $stockStatus = $_POST['stock_status'] ?? 'in_stock';
    $stockQuantity = !empty($_POST['stock_quantity']) ? (int)$_POST['stock_quantity'] : null;
    $sortOrder = (int)($_POST['sort_order'] ?? 0);
    $addonGroups = $_POST['addon_groups'] ?? [];

    if (empty($name)) {
        jsonResponse(false, 'Item name is required');
    }
    if ($categoryId <= 0) {
        jsonResponse(false, 'Please select a category');
    }
    if ($regularPrice <= 0) {
        jsonResponse(false, 'Regular price must be greater than 0');
    }

    $upload = new Upload();
    $mainImage = null;
    $galleryImages = [];

    if (!empty($_FILES['main_image']['name'])) {
        $result = $upload->uploadFile($_FILES['main_image'], 'menu-items/' . $restaurantId);
        if ($result['success']) {
            $mainImage = $result['path'];
        } else {
            jsonResponse(false, 'Main image upload failed: ' . implode(', ', $result['errors']));
        }
    }

    if (!empty($_FILES['gallery_images']['name'][0])) {
        foreach ($_FILES['gallery_images']['name'] as $key => $gname) {
            if ($_FILES['gallery_images']['error'][$key] === UPLOAD_ERR_OK) {
                $gFile = [
                    'name' => $gname,
                    'type' => $_FILES['gallery_images']['type'][$key],
                    'tmp_name' => $_FILES['gallery_images']['tmp_name'][$key],
                    'error' => $_FILES['gallery_images']['error'][$key],
                    'size' => $_FILES['gallery_images']['size'][$key],
                ];
                $result = $upload->uploadFile($gFile, 'menu-items/' . $restaurantId);
                if ($result['success']) {
                    $galleryImages[] = $result['path'];
                } else {
                    jsonResponse(false, 'Gallery image upload failed: ' . implode(', ', $result['errors']));
                }
            }
        }
    }

    $booleanFields = [
        'is_available', 'is_featured', 'is_new', 'is_bestseller', 'is_chefs_choice',
        'is_spicy', 'is_vegetarian', 'is_vegan', 'is_halal', 'is_gluten_free'
    ];
    $boolValues = [];
    foreach ($booleanFields as $bf) {
        $boolValues[$bf] = isset($_POST[$bf]) ? 1 : 0;
    }

    $itemData = [
        'restaurant_id' => $restaurantId,
        'category_id' => $categoryId,
        'name' => $name,
        'slug' => $slug,
        'short_description' => $shortDescription,
        'full_description' => $fullDescription,
        'regular_price' => $regularPrice,
        'offer_price' => $offerPrice,
        'cost_price' => $costPrice,
        'tax_setting' => $taxSetting,
        'prep_time' => $prepTime,
        'calories' => $calories,
        'ingredients' => $ingredients,
        'allergens' => $allergens,
        'stock_status' => $stockStatus,
        'stock_quantity' => $stockQuantity,
        'sort_order' => $sortOrder,
    ];
    $itemData = array_merge($itemData, $boolValues);

    if ($mainImage) {
        $itemData['main_image'] = $mainImage;
    }
    if (!empty($galleryImages)) {
        $existingGallery = ($action === 'edit' && isset($item)) ? json_decode($item['gallery_images'] ?? '[]', true) ?: [] : [];
        $allGallery = array_merge($existingGallery, $galleryImages);
        $itemData['gallery_images'] = json_encode($allGallery);
    }

    if ($action === 'add') {
        $newId = $db->insert('menu_items', $itemData);
        $itemId = $newId;
        $logAction = 'item_create';
    } else {
        $existing = $db->query("SELECT id FROM menu_items WHERE id = ? AND restaurant_id = ?", [$id, $restaurantId])->fetch();
        if (!$existing) {
            jsonResponse(false, 'Item not found');
        }
        $db->update('menu_items', $itemData, 'id = ?', [$id]);
        $itemId = $id;
        $logAction = 'item_update';
    }

    $db->delete('item_addon_groups', 'menu_item_id = ?', [$itemId]);
    if (!empty($addonGroups)) {
        foreach ($addonGroups as $agId) {
            $agId = (int)$agId;
            if ($agId > 0) {
                $db->insert('item_addon_groups', ['menu_item_id' => $itemId, 'addon_group_id' => $agId]);
            }
        }
    }

    $activityLog = new ActivityLog();
    $activityLog->log($userId, $restaurantId, 'menu', $logAction, 'Item "' . $name . '" ' . ($action === 'add' ? 'created' : 'updated'));

    jsonResponse(true, 'Item ' . ($action === 'add' ? 'created' : 'updated') . ' successfully', ['redirect' => $baseUrl . '/restaurant-admin/items.php']);
}

jsonResponse(false, 'Invalid request');
