<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Models\User;
use Illuminate\Http\Request;

class GlobalSearchController extends Controller
{
    public function search(Request $request)
    {
        $query = $request->get('query');
        
        if (strlen($query) < 2) {
            return response()->json([]);
        }

        $results = [];

        // 1. Search Orders
        $orders = Order::where('invoice_number', 'like', "%{$query}%")
            ->orWhere('customer_name', 'like', "%{$query}%")
            ->take(5)
            ->get()
            ->map(function ($order) {
                return [
                    'type' => 'Order',
                    'title' => $order->invoice_number,
                    'subtitle' => $order->customer_name . ' - ' . number_format($order->total_price, 0, ',', '.'),
                    'url' => Helper::getOrderUrl($order), // We need a helper for this or logic
                    'status' => $order->status,
                ];
            });

        // 2. Search Users
        $users = User::where('name', 'like', "%{$query}%")
            ->orWhere('email', 'like', "%{$query}%")
            ->take(5)
            ->get()
            ->map(function ($user) {
                return [
                    'type' => 'User',
                    'title' => $user->name,
                    'subtitle' => $user->email . ' (' . $user->getRoleLabel() . ')',
                    'url' => auth()->user()->isDeveloper() ? route('users.edit', $user) : '#',
                    'status' => $user->is_active ? 'Active' : 'Inactive',
                ];
            });

        // 3. Search Navigation (Static)
        $navItems = $this->searchNavigation($query);

        return response()->json([
            'orders' => $orders,
            'users' => $users,
            'pages' => $navItems,
        ]);
    }

    private function searchNavigation($query)
    {
        $query = strtolower($query);
        $pages = [
            ['title' => 'Dashboard', 'url' => route('dashboard'), 'keywords' => ['home', 'dashboard']],
            ['title' => 'Buat Order', 'url' => route('orders.create'), 'keywords' => ['create order', 'buat order', 'new']],
            ['title' => 'Daftar Order', 'url' => route('orders.index'), 'keywords' => ['orders', 'list', 'daftar']],
            ['title' => 'Laporan Keuangan', 'url' => route('reports.index'), 'keywords' => ['report', 'finance', 'keuangan']],
            ['title' => 'Manajemen User', 'url' => route('users.index'), 'keywords' => ['users', 'pengguna', 'admin']],
        ];

        return collect($pages)->filter(function ($page) use ($query) {
            return str_contains(strtolower($page['title']), $query) || 
                   collect($page['keywords'])->contains(fn($k) => str_contains($k, $query));
        })->values();
    }
}

class Helper {
    public static function getOrderUrl($order) {
        $user = auth()->user();
        if ($user->isKasir()) return route('kasir.show', $order);
        if ($user->isOperator()) return route('produksi.show', $order);
        if ($user->isDesigner() || $user->isDeveloper()) return route('orders.show', $order);
        return '#';
    }
}
