<?php

namespace App\Http\Controllers\Warehouse;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Warehouse\Item;
use App\Models\Warehouse\Project;
use App\Models\Warehouse\ProjectDivision;
use App\Models\Warehouse\Supplier;
use App\Models\Warehouse\IncomingOperation;
use App\Models\Warehouse\OutgoingTransaction;
use Illuminate\Support\Facades\Log;

class UniversalSearchController extends Controller
{
    /**
     * Navigation pages configuration for search
     */
    private function getNavigationPages()
    {
        return [
            // Dashboard
            [
                'name' => 'Dashboard',
                'url' => route('warehouse.dashboard'),
                'icon' => 'dashboard',
                'keywords' => ['dashboard', 'home', 'overview', 'stats', 'statistics'],
                'section' => 'Dashboard'
            ],

            // MASTERS Section
            [
                'name' => 'Suppliers',
                'url' => route('warehouse.suppliers.index'),
                'icon' => 'business',
                'keywords' => ['suppliers', 'vendor', 'supplier list', 'manage suppliers'],
                'section' => 'Masters'
            ],
            [
                'name' => 'Projects',
                'url' => route('warehouse.projects.index'),
                'icon' => 'work',
                'keywords' => ['projects', 'project list', 'manage projects', 'sites'],
                'section' => 'Masters'
            ],
            [
                'name' => 'Project Divisions',
                'url' => route('warehouse.project-divisions.index'),
                'icon' => 'work',
                'keywords' => ['divisions', 'project divisions', 'site divisions'],
                'section' => 'Masters'
            ],
            [
                'name' => 'Item Categories',
                'url' => route('warehouse.item-categories.index'),
                'icon' => 'category',
                'keywords' => ['item categories', 'categories', 'item groups'],
                'section' => 'Masters'
            ],
            [
                'name' => 'Item Types',
                'url' => route('warehouse.item-types.index'),
                'icon' => 'label',
                'keywords' => ['item types', 'types', 'item classification'],
                'section' => 'Masters'
            ],
            [
                'name' => 'Items',
                'url' => route('warehouse.items.index'),
                'icon' => 'inventory_2',
                'keywords' => ['items', 'materials', 'products', 'manage items', 'item list'],
                'section' => 'Masters'
            ],

            // TRANSACTIONS Section
            [
                'name' => 'Material Request',
                'url' => route('warehouse.inventory.material-requests'),
                'icon' => 'assignment',
                'keywords' => ['material request', 'mr', 'request materials', 'material requisition'],
                'section' => 'Transactions'
            ],
            [
                'name' => 'Incoming Operations Dashboard',
                'url' => route('warehouse.incoming-operations.index'),
                'icon' => 'input',
                'keywords' => ['incoming', 'incoming operations', 'receipts', 'goods received'],
                'section' => 'Transactions'
            ],
            [
                'name' => 'Supplier Deliveries',
                'url' => route('warehouse.supplier-delivery.index'),
                'icon' => 'local_shipping',
                'keywords' => ['supplier delivery', 'deliveries', 'vendor delivery', 'goods receipt'],
                'section' => 'Transactions'
            ],
            [
                'name' => 'Site Returns',
                'url' => route('warehouse.site-return.index'),
                'icon' => 'undo',
                'keywords' => ['site return', 'returns', 'material return', 'return to warehouse'],
                'section' => 'Transactions'
            ],
            [
                'name' => 'Outgoing Transactions',
                'url' => route('warehouse.outgoing.index'),
                'icon' => 'output',
                'keywords' => ['outgoing', 'outgoing transactions', 'issues', 'material issue'],
                'section' => 'Transactions'
            ],
            [
                'name' => 'Material Issue',
                'url' => route('warehouse.inventory.material-issued'),
                'icon' => 'send',
                'keywords' => ['material issue', 'issue materials', 'dispatch', 'mi'],
                'section' => 'Transactions'
            ],
            [
                'name' => 'Material Site Transfer',
                'url' => route('warehouse.site-transfers.index'),
                'icon' => 'swap_horiz',
                'keywords' => ['site transfer', 'transfer', 'material transfer', 'project transfer'],
                'section' => 'Transactions'
            ],

            // INVENTORY MANAGEMENT Section
            [
                'name' => 'Inventory Dashboard',
                'url' => route('warehouse.inventory.index'),
                'icon' => 'inventory',
                'keywords' => ['inventory', 'stock', 'stock levels', 'inventory dashboard'],
                'section' => 'Inventory'
            ],
            [
                'name' => 'Low Stock Alerts',
                'url' => route('warehouse.inventory.low-stock'),
                'icon' => 'warning',
                'keywords' => ['low stock', 'stock alerts', 'reorder', 'low inventory'],
                'section' => 'Inventory'
            ],
            [
                'name' => 'Stock Adjustments',
                'url' => route('warehouse.inventory.adjustments'),
                'icon' => 'tune',
                'keywords' => ['adjustments', 'stock adjustment', 'inventory adjustment'],
                'section' => 'Inventory'
            ],
            [
                'name' => 'Cycle Counting',
                'url' => route('warehouse.inventory.physical-count'),
                'icon' => 'fact_check',
                'keywords' => ['cycle count', 'physical count', 'stock count', 'inventory count'],
                'section' => 'Inventory'
            ],
            [
                'name' => 'Inventory Valuation',
                'url' => route('warehouse.inventory.valuation'),
                'icon' => 'attach_money',
                'keywords' => ['valuation', 'inventory value', 'stock value'],
                'section' => 'Inventory'
            ],
            [
                'name' => 'Aging Report',
                'url' => route('warehouse.inventory.aging-report'),
                'icon' => 'schedule',
                'keywords' => ['aging', 'aging report', 'stock aging', 'old stock'],
                'section' => 'Inventory'
            ],
            [
                'name' => 'FOC Conversion',
                'url' => route('warehouse.inventory.condition-conversion'),
                'icon' => 'transform',
                'keywords' => ['foc', 'foc conversion', 'condition conversion', 'damaged goods'],
                'section' => 'Inventory'
            ],

            // REPORTS Section
            [
                'name' => 'Inventory Report',
                'url' => route('warehouse.reports.inventory'),
                'icon' => 'assessment',
                'keywords' => ['inventory report', 'stock report'],
                'section' => 'Reports'
            ],
            [
                'name' => 'Materials Report',
                'url' => route('warehouse.reports.materials'),
                'icon' => 'list_alt',
                'keywords' => ['materials report', 'material list'],
                'section' => 'Reports'
            ],
            [
                'name' => 'Supplier Delivery Report',
                'url' => route('warehouse.reports.incoming'),
                'icon' => 'description',
                'keywords' => ['supplier delivery report', 'delivery report', 'goods received report'],
                'section' => 'Reports'
            ],
            [
                'name' => 'Division Deliveries Report',
                'url' => route('warehouse.reports.division-deliveries'),
                'icon' => 'account_tree',
                'keywords' => ['division deliveries', 'division report'],
                'section' => 'Reports'
            ],
            [
                'name' => 'Site Return Report',
                'url' => route('warehouse.reports.returns'),
                'icon' => 'assignment_return',
                'keywords' => ['site return report', 'return report'],
                'section' => 'Reports'
            ],
            [
                'name' => 'Material Request Report',
                'url' => route('warehouse.reports.outgoing'),
                'icon' => 'assignment_turned_in',
                'keywords' => ['material request report', 'mr report'],
                'section' => 'Reports'
            ],
            [
                'name' => 'Material Issue Report',
                'url' => route('warehouse.reports.transactions'),
                'icon' => 'receipt_long',
                'keywords' => ['material issue report', 'issue report', 'mi report'],
                'section' => 'Reports'
            ],
            [
                'name' => 'Stock on Project',
                'url' => route('warehouse.reports.stock-on-project'),
                'icon' => 'location_on',
                'keywords' => ['stock on project', 'project stock', 'site stock'],
                'section' => 'Reports'
            ],
            [
                'name' => 'FOC Report',
                'url' => route('warehouse.reports.damaged-items'),
                'icon' => 'broken_image',
                'keywords' => ['foc report', 'damaged items', 'damaged goods'],
                'section' => 'Reports'
            ],

            // SETTINGS Section
            [
                'name' => 'Warehouse Settings',
                'url' => route('warehouse.settings.index'),
                'icon' => 'tune',
                'keywords' => ['warehouse settings', 'settings', 'configuration'],
                'section' => 'Settings'
            ],
            [
                'name' => 'Site Settings',
                'url' => route('admin.site-settings.index'),
                'icon' => 'settings',
                'keywords' => ['site settings', 'general settings'],
                'section' => 'Settings'
            ],
        ];
    }

    /**
     * Perform universal search across multiple entities
     */
    public function search(Request $request)
    {
        $query = trim($request->get('q', ''));

        if (strlen($query) < 2) {
            return response()->json([
                'results' => [],
                'total' => 0
            ]);
        }

        $results = [];
        $limit = 5; // Limit results per category

        // Search Navigation Pages (highest priority)
        $navigationResults = $this->searchNavigationPages($query, 3);
        $results = array_merge($results, $navigationResults);

        // Search Items
        try {
            $items = Item::where(function($q) use ($query) {
                $q->where('item_code', 'LIKE', "%{$query}%")
                  ->orWhere('item_description', 'LIKE', "%{$query}%");
            })
            ->with('category')
            ->limit($limit)
            ->get();

            foreach ($items as $item) {
                $results[] = [
                    'type' => 'item',
                    'icon' => 'inventory_2',
                    'label' => $item->item_code . ' - ' . ($item->item_description ?? 'No Description'),
                    'subtitle' => $item->category ? $item->category->category_name : 'No Category',
                    'url' => route('warehouse.items.show', $item->id),
                    'color' => '#4CAF50'
                ];
            }
        } catch (\Exception $e) {
            Log::warning('Universal search - Items search failed: ' . $e->getMessage());
        }

        // Search Projects
        try {
            $projects = Project::where(function($q) use ($query) {
                $q->where('project_name', 'LIKE', "%{$query}%")
                  ->orWhere('project_number', 'LIKE', "%{$query}%");
            })
            ->with('projectDivision')
            ->limit($limit)
            ->get();

            foreach ($projects as $project) {
                $results[] = [
                    'type' => 'project',
                    'icon' => 'work',
                    'label' => ($project->project_number ?? 'PRJ') . ' - ' . $project->project_name,
                    'subtitle' => $project->projectDivision ? $project->projectDivision->division_name : 'No Division',
                    'url' => route('warehouse.projects.show', $project->id),
                    'color' => '#2196F3'
                ];
            }
        } catch (\Exception $e) {
            Log::warning('Universal search - Projects search failed: ' . $e->getMessage());
        }

        // Search Project Divisions
        try {
            $divisions = ProjectDivision::where(function($q) use ($query) {
                $q->where('division_name', 'LIKE', "%{$query}%")
                  ->orWhere('division_code', 'LIKE', "%{$query}%");
            })
            ->limit($limit)
            ->get();

            foreach ($divisions as $division) {
                $results[] = [
                    'type' => 'division',
                    'icon' => 'business',
                    'label' => ($division->division_code ?? 'DIV') . ' - ' . $division->division_name,
                    'subtitle' => 'Division',
                    'url' => route('warehouse.project-divisions.show', $division->id),
                    'color' => '#9C27B0'
                ];
            }
        } catch (\Exception $e) {
            Log::warning('Universal search - Divisions search failed: ' . $e->getMessage());
        }

        // Search Suppliers
        try {
            $suppliers = Supplier::where(function($q) use ($query) {
                $q->where('name', 'LIKE', "%{$query}%")
                  ->orWhere('supplier_code', 'LIKE', "%{$query}%")
                  ->orWhere('contact_person', 'LIKE', "%{$query}%");
            })
            ->limit($limit)
            ->get();

            foreach ($suppliers as $supplier) {
                $results[] = [
                    'type' => 'supplier',
                    'icon' => 'local_shipping',
                    'label' => ($supplier->supplier_code ?? 'SUP') . ' - ' . $supplier->name,
                    'subtitle' => $supplier->contact_person ?? 'Supplier',
                    'url' => route('warehouse.suppliers.show', $supplier->id),
                    'color' => '#FF9800'
                ];
            }
        } catch (\Exception $e) {
            Log::warning('Universal search - Suppliers search failed: ' . $e->getMessage());
        }

        // Search Incoming Operations (Supplier Deliveries, Site Returns)
        try {
            $incomingOps = IncomingOperation::where(function($q) use ($query) {
                $q->where('reference_number', 'LIKE', "%{$query}%")
                  ->orWhere('lpo_number', 'LIKE', "%{$query}%")
                  ->orWhere('delivery_note_number', 'LIKE', "%{$query}%");
            })
            ->limit($limit)
            ->get();

            foreach ($incomingOps as $op) {
                $typeLabel = $op->operation_type === 'supplier_delivery' ? 'Supplier Delivery' : 'Site Return';
                $results[] = [
                    'type' => 'incoming',
                    'icon' => 'input',
                    'label' => $op->reference_number,
                    'subtitle' => $typeLabel . ' - ' . ($op->lpo_number ?? 'No LPO'),
                    'url' => route('warehouse.incoming-operations.show', $op->id),
                    'color' => '#00BCD4'
                ];
            }
        } catch (\Exception $e) {
            Log::warning('Universal search - Incoming operations search failed: ' . $e->getMessage());
        }

        // Search Material Requests (Outgoing Transactions)
        try {
            $outgoingTxns = OutgoingTransaction::where(function($q) use ($query) {
                $q->where('reference_number', 'LIKE', "%{$query}%");
            })
            ->limit($limit)
            ->get();

            foreach ($outgoingTxns as $txn) {
                $results[] = [
                    'type' => 'material_request',
                    'icon' => 'assignment',
                    'label' => $txn->reference_number,
                    'subtitle' => 'Material Request - ' . ucfirst($txn->status ?? 'pending'),
                    'url' => route('warehouse.outgoing.show', $txn->id),
                    'color' => '#E91E63'
                ];
            }
        } catch (\Exception $e) {
            Log::warning('Universal search - Outgoing transactions search failed: ' . $e->getMessage());
        }

        // Sort results by relevance (exact matches first, then navigation, then entities)
        usort($results, function($a, $b) use ($query) {
            // Priority: navigation > entities
            $aPriority = $a['type'] === 'navigation' ? 0 : 1;
            $bPriority = $b['type'] === 'navigation' ? 0 : 1;

            if ($aPriority !== $bPriority) {
                return $aPriority - $bPriority;
            }

            // Within same priority, exact matches first
            $aExact = stripos($a['label'], $query) === 0 ? 0 : 1;
            $bExact = stripos($b['label'], $query) === 0 ? 0 : 1;
            return $aExact - $bExact;
        });

        // Limit total results
        $results = array_slice($results, 0, 20);

        return response()->json([
            'results' => $results,
            'total' => count($results),
            'query' => $query
        ]);
    }

    /**
     * Search navigation pages
     */
    private function searchNavigationPages($query, $limit = 3)
    {
        $results = [];
        $pages = $this->getNavigationPages();
        $query = strtolower($query);

        foreach ($pages as $page) {
            // Search in name and keywords
            $nameMatch = stripos($page['name'], $query) !== false;
            $keywordMatch = false;

            foreach ($page['keywords'] as $keyword) {
                if (stripos($keyword, $query) !== false) {
                    $keywordMatch = true;
                    break;
                }
            }

            if ($nameMatch || $keywordMatch) {
                $results[] = [
                    'type' => 'navigation',
                    'icon' => $page['icon'],
                    'label' => $page['name'],
                    'subtitle' => $page['section'],
                    'url' => $page['url'],
                    'color' => '#607D8B',
                    'exactMatch' => stripos($page['name'], $query) === 0
                ];
            }

            if (count($results) >= $limit) {
                break;
            }
        }

        // Sort by exact match
        usort($results, function($a, $b) {
            return ($b['exactMatch'] ?? false) <=> ($a['exactMatch'] ?? false);
        });

        return array_slice($results, 0, $limit);
    }
}
