<?php

namespace App\Http\Controllers\Admin\Rental;

use App\Http\Controllers\Controller;
use App\Models\Rental\VehicleInsurance;
use App\Models\Rental\InsuranceCompany;
use App\Models\Car;
use App\Services\Rental\InsuranceService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class VehicleInsuranceController extends Controller
{
    protected $insuranceService;

    public function __construct(InsuranceService $insuranceService)
    {
        $this->insuranceService = $insuranceService;
    }

    public function index()
    {
        $query = VehicleInsurance::with(['car.brand', 'company', 'creator'])->latest();
        
        $user = auth()->user();
        if (!$user->isAdmin() && $user->branch_id) {
            $query->where('branch_id', $user->branch_id);
        }
        
        $insurances = $query->paginate(15);
        return view('admin.rentals.insurances.index', compact('insurances'));
    }

    public function create()
    {
        $user = auth()->user();
        $companies = InsuranceCompany::where('is_active', true)->get();
        
        $carQuery = Car::query();
        if (!$user->isAdmin() && $user->branch_id) {
            $carQuery->where('branch_id', $user->branch_id);
        }
        $cars = $carQuery->get();
        
        return view('admin.rentals.insurances.create', compact('companies', 'cars'));
    }

    public function store(Request $request)
    {
        $user = auth()->user();
        $validated = $request->validate([
            'car_id' => 'required|exists:cars,id',
            'insurance_company_id' => 'required|exists:insurance_companies,id',
            'policy_number' => 'required|unique:vehicle_insurances',
            'insurance_type' => 'required|in:comprehensive,third_party',
            'coverage_amount' => 'nullable|numeric|min:0',
            'deductible_amount' => 'required|numeric|min:0',
            'start_date' => 'required|date',
            'end_date' => 'required|date|after:start_date',
            'premium_amount' => 'required|numeric|min:0',
            'payment_status' => 'required|in:paid,unpaid,partial',
            'notes' => 'nullable|string',
            'document_file' => 'nullable|file|mimes:pdf,jpg,png|max:2048'
        ]);

        if ($request->hasFile('document_file')) {
            $validated['document_path'] = $request->file('document_file')->store('insurances', 'public');
        }

        $validated['branch_id'] = $user->branch_id ?: null;
        $this->insuranceService->createInsurance($validated);

        return redirect()->route('admin.vehicle-insurances.index')->with('success', 'Insurance policy recorded successfully.');
    }

    public function show(VehicleInsurance $vehicle_insurance)
    {
        $vehicle_insurance->load(['car.brand', 'company', 'creator']);
        return view('admin.rentals.insurances.show', compact('vehicle_insurance'));
    }

    public function edit(VehicleInsurance $vehicle_insurance)
    {
        $user = auth()->user();
        $companies = InsuranceCompany::where('is_active', true)->get();
        
        $carQuery = Car::query();
        if (!$user->isAdmin() && $user->branch_id) {
            $carQuery->where('branch_id', $user->branch_id);
        }
        $cars = $carQuery->get();
        
        return view('admin.rentals.insurances.edit', compact('vehicle_insurance', 'companies', 'cars'));
    }

    public function update(Request $request, VehicleInsurance $vehicle_insurance)
    {
        $validated = $request->validate([
            'car_id' => 'required|exists:cars,id',
            'insurance_company_id' => 'required|exists:insurance_companies,id',
            'policy_number' => 'required|unique:vehicle_insurances,policy_number,' . $vehicle_insurance->id,
            'insurance_type' => 'required|in:comprehensive,third_party',
            'coverage_amount' => 'nullable|numeric|min:0',
            'deductible_amount' => 'required|numeric|min:0',
            'start_date' => 'required|date',
            'end_date' => 'required|date|after:start_date',
            'premium_amount' => 'required|numeric|min:0',
            'payment_status' => 'required|in:paid,unpaid,partial',
            'status' => 'required|in:active,expired,cancelled',
            'notes' => 'nullable|string',
            'document_file' => 'nullable|file|mimes:pdf,jpg,png|max:2048'
        ]);

        if ($request->hasFile('document_file')) {
            if ($vehicle_insurance->document_path) {
                Storage::disk('public')->delete($vehicle_insurance->document_path);
            }
            $validated['document_path'] = $request->file('document_file')->store('insurances', 'public');
        }

        $vehicle_insurance->update($validated);
        return redirect()->route('admin.vehicle-insurances.index')->with('success', 'Insurance policy updated successfully.');
    }

    public function destroy(VehicleInsurance $vehicle_insurance)
    {
        if ($vehicle_insurance->document_path) {
            Storage::disk('public')->delete($vehicle_insurance->document_path);
        }
        
        $vehicle_insurance->delete();
        return redirect()->route('admin.vehicle-insurances.index')->with('success', 'Insurance policy deleted successfully.');
    }
}
