<?php

namespace App\Http\Controllers;

use App\Models\Employee;
use App\Models\AccessCatalog;
use Illuminate\Http\Request;

class SearchController extends Controller
{
    public function index(Request $request)
    {
        $query = $request->get('q');
        
        if (empty($query)) {
            return redirect()->back();
        }

        $employees = Employee::with('department')
            ->where('name', 'like', "%{$query}%")
            ->orWhere('nip', 'like', "%{$query}%")
            ->orWhere('email', 'like', "%{$query}%")
            ->latest()
            ->take(10)
            ->get();

        $catalogs = AccessCatalog::with('ownerDepartment')
            ->where('name', 'like', "%{$query}%")
            ->orWhere('code', 'like', "%{$query}%")
            ->latest()
            ->take(10)
            ->get();

        // Potential report matches (basic logic)
        $reports = [];
        $reportTypes = [
            'pensiun' => ['name' => 'Laporan Pensiun', 'route' => 'reports.retirement'],
            'perpanjangan' => ['name' => 'Laporan Perpanjangan', 'route' => 'reports.extension'],
            'pencabutan' => ['name' => 'Laporan Pencabutan', 'route' => 'reports.revocation'],
        ];

        foreach ($reportTypes as $key => $report) {
            if (stripos($key, $query) !== false || stripos($report['name'], $query) !== false) {
                $reports[] = $report;
            }
        }

        return view('search.index', compact('employees', 'catalogs', 'reports', 'query'));
    }
}
