<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\VesselRecord;

class SearchController extends Controller
{
    public function search(Request $request)
    {
        try {
            $searchTerm = trim($request->get('term', ''));

            if (strlen($searchTerm) < 2) {
                return response()->json([
                    'success' => false,
                    'message' => 'Search term too short'
                ]);
            }

            $records = VesselRecord::with(['vessel', 'status'])
                ->whereHas('vessel', function($query) use ($searchTerm) {
                    $query->where('name', 'LIKE', "%{$searchTerm}%");
                })
                ->orWhere('invoice_no', 'LIKE', "%{$searchTerm}%")
                ->orWhere('port', 'LIKE', "%{$searchTerm}%")
                ->orWhere('description', 'LIKE', "%{$searchTerm}%")
                ->orWhere('company', 'LIKE', "%{$searchTerm}%")
                ->orderBy('date', 'desc')
                ->limit(100)
                ->get();

            $results = $records->map(function($record) {
                return [
                    'id' => $record->id,
                    'vessel_name' => $record->vessel->name,
                    'date' => $record->date,
                    'invoice_no' => $record->invoice_no,
                    'port' => $record->port,
                    'description' => $record->description,
                    'amount' => $record->amount,
                    'due_date' => $record->due_date,
                    'company' => $record->company,
                    'status_name' => $record->status ? $record->status->name : '',
                    'view_url' => route('vessel-records.show', $record->id)
                ];
            });

            return response()->json([
                'success' => true,
                'results' => $results
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error performing search: ' . $e->getMessage()
            ]);
        }
    }
}
