<?php

namespace App\Http\Controllers\Admin\Rental;

use App\Http\Controllers\Controller;
use App\Models\Car;
use App\Models\Rental\MaintenanceRecord;
use App\Models\Rental\Rental;
use Illuminate\Http\Request;

class MaintenanceController extends Controller
{
    public function index(Request $request)
    {
        $this->authorize('manageMaintenance', Rental::class);
        
        $query = MaintenanceRecord::with('car');
        
        $user = auth()->user();
        if (!$user->isAdmin() && $user->branch_id) {
            $query->where('branch_id', $user->branch_id);
        }

        // General search
        if ($request->filled('search')) {
            $search = $request->input('search');
            $query->where(function($q) use ($search) {
                $q->whereHas('car', function($q2) use ($search) {
                    $q2->where('title', 'like', "%{$search}%")
                       ->orWhere('plate_number', 'like', "%{$search}%");
                })->orWhere('description', 'like', "%{$search}%");
            });
        }

        // Car filter
        if ($request->filled('car_id')) {
            $query->where('car_id', $request->input('car_id'));
        }

        // Date range filter
        if ($request->filled('from_date')) {
            $query->whereDate('maintenance_date', '>=', $request->input('from_date'));
        }
        if ($request->filled('to_date')) {
            $query->whereDate('maintenance_date', '<=', $request->input('to_date'));
        }

        // Cost range filter
        if ($request->filled('min_cost')) {
            $query->where('cost', '>=', $request->input('min_cost'));
        }
        if ($request->filled('max_cost')) {
            $query->where('cost', '<=', $request->input('max_cost'));
        }

        // Sorting
        $sort = $request->input('sort', 'date_desc');
        switch($sort) {
            case 'date_asc':
                $query->oldest();
                break;
            case 'cost_high':
                $query->orderBy('cost', 'desc');
                break;
            case 'cost_low':
                $query->orderBy('cost', 'asc');
                break;
            default:
                $query->latest();
        }
        
        $records = $query->paginate(15);

        // Get all cars for filter dropdown
        $carsQuery = Car::query();
        if (!$user->isAdmin() && $user->branch_id) {
            $carsQuery->where('branch_id', $user->branch_id);
        }
        $cars = $carsQuery->get();

        return view('admin.rentals.maintenance.index', compact('records', 'cars'));
    }

    public function create()
    {
        $this->authorize('manageMaintenance', Rental::class);
        
        $user = auth()->user();
        $carQuery = Car::query();
        if (!$user->isAdmin() && $user->branch_id) {
            $carQuery->where('branch_id', $user->branch_id);
        }
        $cars = $carQuery->get();

        return view('admin.rentals.maintenance.create', compact('cars'));
    }

    public function store(Request $request)
    {
        $this->authorize('manageMaintenance', Rental::class);

        $user = auth()->user();
        $validated = $request->validate([
            'car_id' => 'required|exists:cars,id',
            'description' => 'required|string',
            'cost' => 'required|numeric|min:0',
            'maintenance_date' => 'required|date',
            'next_due_km' => 'nullable|integer|min:0',
            'next_due_date' => 'nullable|date',
            'set_car_maintenance' => 'boolean',
        ]);

        $validated['branch_id'] = $user->branch_id;
        $record = MaintenanceRecord::create($validated);

        if ($request->set_car_maintenance) {
            Car::find($validated['car_id'])->update(['rental_status' => 'maintenance']);
        }

        return redirect()->route('admin.maintenance.index')
            ->with('success', 'Maintenance record added successfully.');
    }
}
