<?php

class SearchController extends Controller
{
    public function index(): void
    {
        Auth::requireLogin();
        $query = trim((string) ($_GET['q'] ?? ''));
        $results = ['loads'=>[], 'carriers'=>[], 'invoices'=>[], 'drivers'=>[], 'equipment'=>[], 'fuel'=>[], 'hos'=>[], 'borders'=>[], 'documents'=>[]];

        if ($query !== '') {
            $db = Database::connection();
            $term = '%' . $query . '%';
            $role = current_role();
            $user = Auth::user() ?: [];

            if ($role === 'carrier') {
                $carrierId = (int) ($user['carrier_id'] ?? 0);
                if ($carrierId > 0) {
                    $stmt = $db->prepare("SELECT id,load_number,reference_number,pickup_location,delivery_location,status
                        FROM loads
                        WHERE carrier_id=? AND (load_number LIKE ? OR reference_number LIKE ? OR pickup_location LIKE ? OR delivery_location LIKE ?)
                        ORDER BY id DESC LIMIT 25");
                    $stmt->execute([$carrierId,$term,$term,$term,$term]);
                    $results['loads'] = $stmt->fetchAll();

                    $stmt = $db->prepare("SELECT DISTINCT documents.id,documents.document_type,documents.file_name,documents.related_type,documents.related_id
                        FROM documents
                        LEFT JOIN load_stops ON documents.related_type='stop' AND documents.related_id=load_stops.id
                        LEFT JOIN loads ON (documents.related_type='load' AND documents.related_id=loads.id)
                            OR (documents.related_type='stop' AND load_stops.load_id=loads.id)
                        LEFT JOIN border_crossings ON documents.related_type='border_crossing' AND documents.related_id=border_crossings.id
                        LEFT JOIN loads border_load ON border_load.id=border_crossings.load_id
                        WHERE ((documents.related_type='carrier' AND documents.related_id=?) OR loads.carrier_id=? OR border_load.carrier_id=?)
                          AND (documents.document_type LIKE ? OR documents.file_name LIKE ?)
                        ORDER BY documents.id DESC LIMIT 25");
                    $stmt->execute([$carrierId,$carrierId,$carrierId,$term,$term]);
                    $results['documents'] = $stmt->fetchAll();
                }
            } else {
                if (can('loads.view') || can('dispatch.view') || is_admin_role()) {
                    $stmt=$db->prepare("SELECT id,load_number,reference_number,pickup_location,delivery_location,status FROM loads WHERE load_number LIKE ? OR reference_number LIKE ? OR pickup_location LIKE ? OR delivery_location LIKE ? ORDER BY id DESC LIMIT 25");
                    $stmt->execute([$term,$term,$term,$term]);
                    $results['loads']=$stmt->fetchAll();
                }
                if (can('carriers.manage') || can('dispatch.view') || is_admin_role()) {
                    $stmt=$db->prepare("SELECT id,company_name,mc_number,dot_number,onboarding_status,status FROM carriers WHERE company_name LIKE ? OR dba_name LIKE ? OR mc_number LIKE ? OR dot_number LIKE ? OR contact_name LIKE ? ORDER BY company_name LIMIT 25");
                    $stmt->execute([$term,$term,$term,$term,$term]);
                    $results['carriers']=$stmt->fetchAll();
                }
                if (can('accounting.view') || can('invoices.manage') || $role === 'dispatcher') {
                    $stmt=$db->prepare("SELECT invoices.id,invoices.invoice_number,invoices.status,invoices.total,brokers.company_name FROM invoices LEFT JOIN brokers ON brokers.id=invoices.broker_id WHERE invoices.invoice_number LIKE ? OR brokers.company_name LIKE ? ORDER BY invoices.id DESC LIMIT 25");
                    $stmt->execute([$term,$term]);
                    $results['invoices']=$stmt->fetchAll();
                }
                if (can('drivers.view') || is_admin_role()) {
                    $stmt=$db->prepare("SELECT id,name,email,phone,status FROM drivers WHERE name LIKE ? OR email LIKE ? OR phone LIKE ? OR license_number LIKE ? ORDER BY name LIMIT 25");
                    $stmt->execute([$term,$term,$term,$term]);
                    $results['drivers']=$stmt->fetchAll();
                }
                if (can('equipment.view') || is_admin_role()) {
                    $stmt=$db->prepare("SELECT id,unit_number identifier,'Truck' kind,status FROM trucks WHERE unit_number LIKE ? OR vin LIKE ? OR plate_number LIKE ? UNION ALL SELECT id,trailer_number identifier,'Trailer' kind,status FROM trailers WHERE trailer_number LIKE ? OR plate_number LIKE ? LIMIT 30");
                    $stmt->execute([$term,$term,$term,$term,$term]);
                    $results['equipment']=$stmt->fetchAll();
                }
                if (can('fuel.view') || can('driver.fuel')) {
                    if ($role === 'driver') {
                        $stmt=$db->prepare("SELECT fuel_allocations.id,fuel_allocations.allocation_number,fuel_allocations.status,fuel_allocations.remaining_amount,loads.load_number FROM fuel_allocations LEFT JOIN loads ON loads.id=fuel_allocations.load_id WHERE fuel_allocations.driver_id=? AND (fuel_allocations.allocation_number LIKE ? OR loads.load_number LIKE ?) ORDER BY fuel_allocations.id DESC LIMIT 25");
                        $stmt->execute([(int)($user['driver_id']??0),$term,$term]);
                    } else {
                        $stmt=$db->prepare("SELECT fuel_allocations.id,fuel_allocations.allocation_number,fuel_allocations.status,fuel_allocations.remaining_amount,loads.load_number FROM fuel_allocations LEFT JOIN loads ON loads.id=fuel_allocations.load_id LEFT JOIN drivers ON drivers.id=fuel_allocations.driver_id WHERE fuel_allocations.allocation_number LIKE ? OR loads.load_number LIKE ? OR drivers.name LIKE ? ORDER BY fuel_allocations.id DESC LIMIT 25");
                        $stmt->execute([$term,$term,$term]);
                    }
                    $results['fuel']=$stmt->fetchAll();
                }
                if (can('hos.view') || can('hos.driver')) {
                    if ($role === 'driver') {
                        $stmt=$db->prepare("SELECT hos_daily_logs.id,hos_daily_logs.driver_id,hos_daily_logs.log_date,hos_daily_logs.status,drivers.name AS driver_name FROM hos_daily_logs JOIN drivers ON drivers.id=hos_daily_logs.driver_id WHERE hos_daily_logs.driver_id=? AND (drivers.name LIKE ? OR hos_daily_logs.log_date LIKE ? OR hos_daily_logs.status LIKE ?) ORDER BY hos_daily_logs.log_date DESC LIMIT 25");
                        $stmt->execute([(int)($user['driver_id']??0),$term,$term,$term]);
                    } else {
                        $stmt=$db->prepare("SELECT hos_daily_logs.id,hos_daily_logs.driver_id,hos_daily_logs.log_date,hos_daily_logs.status,drivers.name AS driver_name FROM hos_daily_logs JOIN drivers ON drivers.id=hos_daily_logs.driver_id WHERE drivers.name LIKE ? OR hos_daily_logs.log_date LIKE ? OR hos_daily_logs.status LIKE ? ORDER BY hos_daily_logs.log_date DESC LIMIT 25");
                        $stmt->execute([$term,$term,$term]);
                    }
                    $results['hos']=$stmt->fetchAll();
                }
                if (can('border.manage') || can('driver.border')) {
                    if ($role === 'driver') {
                        $stmt=$db->prepare("SELECT border_crossings.id,border_crossings.crossing_number,border_crossings.crossing_name,border_crossings.status FROM border_crossings JOIN loads ON loads.id=border_crossings.load_id WHERE loads.driver_id=? AND (border_crossings.crossing_number LIKE ? OR border_crossings.crossing_name LIKE ? OR border_crossings.reference_number LIKE ?) ORDER BY border_crossings.id DESC LIMIT 25");
                        $stmt->execute([(int)($user['driver_id']??0),$term,$term,$term]);
                    } else {
                        $stmt=$db->prepare("SELECT id,crossing_number,crossing_name,status FROM border_crossings WHERE crossing_number LIKE ? OR crossing_name LIKE ? OR reference_number LIKE ? ORDER BY id DESC LIMIT 25");
                        $stmt->execute([$term,$term,$term]);
                    }
                    $results['borders']=$stmt->fetchAll();
                }
                if (can('documents.view') || can('documents.manage')) {
                    $stmt=$db->prepare("SELECT id,document_type,file_name,related_type,related_id FROM documents WHERE document_type LIKE ? OR file_name LIKE ? ORDER BY id DESC LIMIT 25");
                    $stmt->execute([$term,$term]);
                    $results['documents']=$stmt->fetchAll();
                }
            }
        }

        $this->view('search/index', compact('query','results'));
    }
}
