<?php

namespace App\Http\Controllers;

use App\Models\TripPayment;
use App\Models\Trip;
use Illuminate\Http\Request;

class TripPaymentController extends Controller
{
    public function index()
    {
        $payments = TripPayment::with('trip.vehicle', 'trip.driver')->latest()->paginate(15);
        return view('payments.index', compact('payments'));
    }

    public function create(Request $request)
    {
        $trip_id = $request->get('trip_id');
        // Get trips that don't already have a payment record
        $trips = Trip::with('vehicle', 'driver')
            ->whereDoesntHave('payment')
            ->latest()
            ->get();
        return view('payments.create', compact('trips', 'trip_id'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'trip_id' => 'required|exists:trips,id',
            'advance' => 'required|numeric|min:0',
            'paid' => 'required|numeric|min:0',
            'method' => 'nullable|string',
        ]);

        $trip = Trip::findOrFail($validated['trip_id']);
        $totalPaid = $validated['advance'] + $validated['paid'];
        $validated['balance'] = $trip->rent_amount - $totalPaid;

        // Auto-determine status
        if ($validated['balance'] <= 0) {
            $validated['status'] = 'completed';
            $validated['balance'] = 0;
        } elseif ($totalPaid > 0) {
            $validated['status'] = 'partial';
        } else {
            $validated['status'] = 'pending';
        }

        TripPayment::create($validated);

        \App\Models\ActivityLog::log('created', 'Payment', 'Payment recorded for Trip #' . $trip->id . '. Advance: ₹' . $validated['advance'] . ', Paid: ₹' . $validated['paid']);

        return redirect()->route('payments.index')->with('success', 'Payment recorded successfully!');
    }

    public function edit(TripPayment $payment)
    {
        $payment->load('trip.vehicle', 'trip.driver');
        return view('payments.edit', compact('payment'));
    }

    public function update(Request $request, TripPayment $payment)
    {
        $validated = $request->validate([
            'advance' => 'required|numeric|min:0',
            'paid' => 'required|numeric|min:0',
            'method' => 'nullable|string',
        ]);

        $trip = $payment->trip;
        $totalPaid = $validated['advance'] + $validated['paid'];
        $validated['balance'] = $trip->rent_amount - $totalPaid;

        // Auto-determine status
        if ($validated['balance'] <= 0) {
            $validated['status'] = 'completed';
            $validated['balance'] = 0;
        } elseif ($totalPaid > 0) {
            $validated['status'] = 'partial';
        } else {
            $validated['status'] = 'pending';
        }

        $payment->update($validated);

        \App\Models\ActivityLog::log('updated', 'Payment', 'Payment updated for Trip #' . $trip->id . '. Status: ' . $validated['status']);

        return redirect()->route('payments.index')->with('success', 'Payment updated successfully!');
    }

    public function destroy(TripPayment $payment)
    {
        $tripId = $payment->trip_id;
        $payment->delete();

        \App\Models\ActivityLog::log('deleted', 'Payment', 'Payment deleted for Trip #' . $tripId);

        return redirect()->route('payments.index')->with('success', 'Payment deleted.');
    }
}
