<?php

namespace App\Http\Controllers;

use App\Models\Operator;
use App\Http\Requests\OperatorRequest;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;

class OperatorController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request): View
    {
        $query = Operator::query();

        // Search functionality
        if ($request->filled('search')) {
            $search = $request->get('search');
            $query->where(function ($q) use ($search) {
                $q->where('name', 'ILIKE', "%{$search}%")
                  ->orWhere('description', 'ILIKE', "%{$search}%");
            });
        }

        // Filter by status
        if ($request->filled('status')) {
            $query->where('is_active', $request->get('status') === 'active');
        }

        $operators = $query->latest()->paginate(15)->withQueryString();

        return view('operators.index', compact('operators'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create(): View
    {
        return view('operators.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(OperatorRequest $request): RedirectResponse
    {
        $operator = Operator::create($request->validated());

        return redirect()
            ->route('operators.show', $operator)
            ->with('success', 'Operator created successfully!');
    }

    /**
     * Display the specified resource.
     */
    public function show(Operator $operator): View
    {
        return view('operators.show', compact('operator'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Operator $operator): View
    {
        return view('operators.edit', compact('operator'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(OperatorRequest $request, Operator $operator): RedirectResponse
    {
        $operator->update($request->validated());

        return redirect()
            ->route('operators.show', $operator)
            ->with('success', 'Operator updated successfully!');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Operator $operator): RedirectResponse
    {
        $operator->delete();

        return redirect()
            ->route('operators.index')
            ->with('success', 'Operator deleted successfully!');
    }
}