<?php
session_start();
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/config.php';

header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(false, 'Method not allowed', [], 405);
}

$itemId = (int) ($_GET['item_id'] ?? $_POST['item_id'] ?? 0);
$restaurantId = (int) ($_GET['restaurant_id'] ?? $_POST['restaurant_id'] ?? 0);

if ($itemId <= 0 || $restaurantId <= 0) {
    jsonResponse(false, 'Invalid parameters');
}

$db = Database::getInstance();

$item = $db->query(
    "SELECT * FROM menu_items WHERE id = ? AND restaurant_id = ? AND is_available = 1",
    [$itemId, $restaurantId]
)->fetch();

if (!$item) {
    jsonResponse(false, 'Item not found or unavailable');
}

$db->query(
    "UPDATE menu_items SET view_count = view_count + 1 WHERE id = ?",
    [$itemId]
);

$variations = $db->query(
    "SELECT * FROM item_variations WHERE restaurant_id = ? AND menu_item_id = ? AND status = 1 ORDER BY sort_order ASC",
    [$restaurantId, $itemId]
)->fetchAll();

$itemAddonGroups = $db->query(
    "SELECT iag.*, ag.name as group_name, ag.is_required, ag.min_select, ag.max_select
     FROM item_addon_groups iag
     JOIN addon_groups ag ON iag.addon_group_id = ag.id
     WHERE iag.menu_item_id = ? AND ag.restaurant_id = ? AND ag.status = 1
     ORDER BY ag.sort_order ASC",
    [$itemId, $restaurantId]
)->fetchAll();

$addonGroups = [];
foreach ($itemAddonGroups as $iag) {
    $addons = $db->query(
        "SELECT * FROM addons WHERE restaurant_id = ? AND addon_group_id = ? AND status = 1 ORDER BY sort_order ASC",
        [$restaurantId, $iag['addon_group_id']]
    )->fetchAll();
    $addonGroups[] = [
        'id'          => $iag['addon_group_id'],
        'name'        => $iag['group_name'],
        'is_required' => (bool) $iag['is_required'],
        'min_select'  => (int) $iag['min_select'],
        'max_select'  => (int) $iag['max_select'],
        'addons'      => $addons,
    ];
}

$offerPrice = null;
$regularPrice = (float) $item['regular_price'];
if (!empty($item['offer_price']) && (float) $item['offer_price'] > 0) {
    $offerPrice = (float) $item['offer_price'];
}

$response = [
    'id'            => $item['id'],
    'name'          => $item['name'],
    'short_desc'    => $item['short_description'] ?? '',
    'full_desc'     => $item['full_description'] ?? '',
    'regular_price' => $regularPrice,
    'offer_price'   => $offerPrice,
    'price'         => $offerPrice !== null ? $offerPrice : $regularPrice,
    'main_image'    => !empty($item['main_image']) ? $item['main_image'] : '',
    'gallery_images' => !empty($item['gallery_images']) ? json_decode($item['gallery_images'], true) : [],
    'is_new'        => (bool) $item['is_new'],
    'is_bestseller' => (bool) $item['is_bestseller'],
    'is_spicy'      => (bool) $item['is_spicy'],
    'is_vegetarian' => (bool) $item['is_vegetarian'],
    'is_vegan'      => (bool) $item['is_vegan'],
    'is_halal'      => (bool) $item['is_halal'],
    'is_gluten_free' => (bool) $item['is_gluten_free'],
    'is_chefs_choice' => (bool) $item['is_chefs_choice'],
    'variations'    => $variations,
    'addon_groups'  => $addonGroups,
];

jsonResponse(true, 'Item loaded', $response);
