<?php

namespace Mtc\Modules\QuickOrder\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Mtc\Shop\Item;

class QuickOrderController extends Controller
{
    public function index()
    {
        return template('shop/quick_order.twig', [
            'page_title' => 'Quick Order',
        ]);
    }

    public function search(Request $request): JsonResponse
    {
        $rateLimit = \Mtc\Core\RateLimit::log('quick_order_search', null, 30);
        if ($rateLimit && $rateLimit['limited']) {
            return response()->json([
                'status' => 'error',
                'message' => $rateLimit['message'],
            ], 429);
        }

        $term = trim($request->input('term', ''));

        if (mb_strlen($term) < 2) {
            return response()->json([
                'status' => 'error',
                'message' => 'Search term must be at least 2 characters',
            ], 400);
        }

        $escapedTerm = str_replace(['%', '_'], ['\\%', '\\_'], $term);

        $products = Item::query()
            ->where('hidden', 0)
            ->where('deleted', 0)
            ->where(function ($query) use ($escapedTerm) {
                $query->where('name', 'like', "%{$escapedTerm}%")
                    ->orWhere('epos_code', 'like', "%{$escapedTerm}%")
                    ->orWhereHas('sizes', function ($sq) use ($escapedTerm) {
                        $sq->where('hide', 0)
                            ->where(function ($inner) use ($escapedTerm) {
                                $inner->where('PLU', 'like', "%{$escapedTerm}%")
                                    ->orWhere('ean', 'like', "%{$escapedTerm}%");
                            });
                    });
            })
            ->with([
                'images',
                'sizes' => function ($q) {
                    $q->where('hide', 0)->orderBy('order');
                },
                'categories',
            ])
            ->orderBy('num_sold', 'desc')
            ->take(24)
            ->get();

        global $image_folders;
        $smallthumbPath = isset($image_folders['product_folders']['smallthumbs']['path'])
            ? $image_folders['product_folders']['smallthumbs']['path']
            : 'uploads/images/products/smallthumbs';

        $results = $products->map(function (Item $item) use ($smallthumbPath) {
            $defaultImage = $item->images->where('default', 1)->first();
            $image = defined('THEME_URL') ? THEME_URL . '/images/placeholders/no-image.jpg' : '/sites/default/images/placeholders/no-image.jpg';

            if ($defaultImage) {
                $imagePath = '/' . $smallthumbPath . '/' . $defaultImage->name;
                if (defined('SITE_PATH') && file_exists(SITE_PATH . $imagePath)) {
                    $image = $imagePath;
                }
            }

            $form = $item->findAssessmentForm();
            $requiresAssessment = $form !== null;
            $assessmentUrl = null;

            if ($requiresAssessment) {
                $cardData = $item->getProductCardData();
                $assessmentUrl = $cardData['url'] ?? null;
            }

            $sizes = $item->sizes->map(function ($size) {
                return [
                    'id' => $size->id,
                    'size' => $size->size,
                    'pack_size' => $size->pack_size ?? '',
                    'price' => number_format($size->price, 2, '.', ''),
                    'sale_price' => number_format($size->sale_price, 2, '.', ''),
                    'stock' => $size->stock,
                    'hide' => $size->hide,
                ];
            })->values();

            return [
                'id' => $item->id,
                'name' => $item->name,
                'image' => $image,
                'from_price' => $item->from_price,
                'product_type' => $item->product_type ?: 'general',
                'in_stock' => $item->in_stock,
                'url' => $item->url,
                'sizes' => $sizes,
                'requires_assessment' => $requiresAssessment,
                'assessment_url' => $assessmentUrl,
            ];
        });

        return response()->json([
            'status' => 'ok',
            'products' => $results->values(),
        ]);
    }
}
