<?php

namespace App\Http\Controllers\Admin\Rental;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use App\Models\Rental\InsuranceClaim;
use App\Models\Car;
use App\Models\Rental\Rental;

class InsuranceClaimController extends Controller
{
    public function index()
    {
        $claims = InsuranceClaim::with(['car.brand', 'rental', 'creator'])->latest()->paginate(15);
        return view('admin.rentals.insurances.claims.index', compact('claims'));
    }

    public function create(Request $request)
    {
        $cars = Car::all();
        $rentals = Rental::where('status', 'open')->get();
        
        $selected_car = null;
        if ($request->car_id) {
            $selected_car = Car::find($request->car_id);
        }

        return view('admin.rentals.insurances.claims.create', compact('cars', 'rentals', 'selected_car'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'car_id' => 'required|exists:cars,id',
            'rental_id' => 'nullable|exists:rentals,id',
            'claim_number' => 'required|unique:insurance_claims',
            'accident_date' => 'required|date',
            'description' => 'required|string',
            'estimated_damage_cost' => 'nullable|numeric|min:0',
            'deductible_paid' => 'required|numeric|min:0',
            'claim_status' => 'required|in:pending,accepted,rejected,closed',
        ]);

        $validated['created_by'] = auth()->id();

        InsuranceClaim::create($validated);

        return redirect()->route('admin.insurance-claims.index')->with('success', 'Claim recorded successfully.');
    }

    public function show(InsuranceClaim $insurance_claim)
    {
        $insurance_claim->load(['car.brand', 'rental', 'creator']);
        return view('admin.rentals.insurances.claims.show', compact('insurance_claim'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }
}
