<?php

namespace App\Http\Controllers;

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

class TripController extends Controller
{
    public function index()
    {
        $trips = Trip::with(['vehicle', 'driver'])->latest()->paginate(10);
        return view('trips.index', compact('trips'));
    }

    /**
     * Show trips for the logged-in driver only.
     */
    public function myTrips()
    {
        $user = auth()->user();
        $driver = $user->driver;

        if (!$driver) {
            return redirect()->route('dashboard')->with('error', 'No driver profile linked to your account. Please contact admin.');
        }

        $trips = Trip::with(['vehicle', 'driver'])
            ->where('driver_id', $driver->id)
            ->latest()
            ->paginate(10);

        return view('trips.my_trips', compact('trips', 'driver'));
    }

    public function create()
    {
        $vehicles = \App\Models\Vehicle::where('status', 'active')->get();

        $user = auth()->user();
        $linkedDriver = null;
        $drivers = collect();

        if ($user->hasRole('Driver')) {
            $linkedDriver = $user->driver;
            if (!$linkedDriver) {
                return redirect()->route('dashboard')->with('error', 'No driver profile linked to your account. Please contact admin.');
            }
        } else {
            $drivers = \App\Models\Driver::where('status', 'active')->get();
        }

        return view('trips.create', compact('vehicles', 'drivers', 'linkedDriver'));
    }

    public function store(Request $request)
    {
        $user = auth()->user();

        if ($user->hasRole('Driver')) {
            $linkedDriver = $user->driver;
            if (!$linkedDriver) {
                return redirect()->route('dashboard')->with('error', 'No driver profile linked to your account.');
            }
            $request->merge(['driver_id' => $linkedDriver->id]);
        }

        $validated = $request->validate([
            'date' => 'nullable|date',
            'location' => 'nullable|string',
            'vehicle_id' => 'nullable|exists:vehicles,id',
            'driver_id' => 'nullable|exists:drivers,id',
            'trip_type' => 'nullable|in:rent,own,empty',
            'open_km' => 'nullable|numeric',
            'close_km' => 'nullable|numeric',
            'open_hour' => 'nullable',
            'close_hour' => 'nullable',
            'rent_amount' => 'nullable|numeric',
            'diesel_price' => 'nullable|numeric',
            'fuel_litre' => 'nullable|numeric',
        ]);

        // Set defaults for nullable fields
        $validated['date'] = $validated['date'] ?? now()->toDateString();
        $validated['open_km'] = $validated['open_km'] ?? 0;
        $validated['close_km'] = $validated['close_km'] ?? 0;
        $validated['rent_amount'] = $validated['rent_amount'] ?? 0;
        $validated['diesel_price'] = $validated['diesel_price'] ?? 0;
        $validated['fuel_litre'] = $validated['fuel_litre'] ?? 0;

        $validated['total_km'] = $validated['close_km'] - $validated['open_km'];
        $validated['fuel_cost'] = $validated['diesel_price'] * $validated['fuel_litre'];
        
        // Time diff logic
        $openHour = $validated['open_hour'] ?? null;
        $closeHour = $validated['close_hour'] ?? null;
        if ($openHour && $closeHour) {
            $validated['total_hour'] = (int)(abs(strtotime($closeHour) - strtotime($openHour)) / 3600);
        }

        $trip = Trip::create($validated);

        \App\Models\ActivityLog::log('created', 'Trip', 'New trip created to ' . $trip->location);

        if ($user->hasRole('Driver')) {
            return redirect()->route('trips.my')->with('success', 'Trip added successfully!');
        }

        return redirect()->route('trips.index')->with('success', 'Trip added successfully!');
    }

    public function edit(Trip $trip)
    {
        $user = auth()->user();

        // Driver can only edit their own trips
        if ($user->hasRole('Driver')) {
            $linkedDriver = $user->driver;
            if (!$linkedDriver || $trip->driver_id !== $linkedDriver->id) {
                return redirect()->route('trips.my')->with('error', 'You can only edit your own trips.');
            }
        }

        $vehicles = \App\Models\Vehicle::where('status', 'active')->get();
        $linkedDriver = null;
        $drivers = collect();

        if ($user->hasRole('Driver')) {
            $linkedDriver = $user->driver;
        } else {
            $drivers = \App\Models\Driver::where('status', 'active')->get();
        }

        return view('trips.edit', compact('trip', 'vehicles', 'drivers', 'linkedDriver'));
    }

    public function update(Request $request, Trip $trip)
    {
        $user = auth()->user();

        // Driver can only update their own trips
        if ($user->hasRole('Driver')) {
            $linkedDriver = $user->driver;
            if (!$linkedDriver || $trip->driver_id !== $linkedDriver->id) {
                return redirect()->route('trips.my')->with('error', 'You can only edit your own trips.');
            }
            $request->merge(['driver_id' => $linkedDriver->id]);
        }

        $validated = $request->validate([
            'date' => 'nullable|date',
            'location' => 'nullable|string',
            'vehicle_id' => 'nullable|exists:vehicles,id',
            'driver_id' => 'nullable|exists:drivers,id',
            'trip_type' => 'nullable|in:rent,own,empty',
            'open_km' => 'nullable|numeric',
            'close_km' => 'nullable|numeric',
            'open_hour' => 'nullable',
            'close_hour' => 'nullable',
            'rent_amount' => 'nullable|numeric',
            'diesel_price' => 'nullable|numeric',
            'fuel_litre' => 'nullable|numeric',
        ]);

        $validated['open_km'] = $validated['open_km'] ?? 0;
        $validated['close_km'] = $validated['close_km'] ?? 0;
        $validated['rent_amount'] = $validated['rent_amount'] ?? 0;
        $validated['diesel_price'] = $validated['diesel_price'] ?? 0;
        $validated['fuel_litre'] = $validated['fuel_litre'] ?? 0;

        $validated['total_km'] = $validated['close_km'] - $validated['open_km'];
        $validated['fuel_cost'] = $validated['diesel_price'] * $validated['fuel_litre'];

        $openHour = $validated['open_hour'] ?? null;
        $closeHour = $validated['close_hour'] ?? null;
        if ($openHour && $closeHour) {
            $validated['total_hour'] = (int)(abs(strtotime($closeHour) - strtotime($openHour)) / 3600);
        }

        $trip->update($validated);

        \App\Models\ActivityLog::log('updated', 'Trip', 'Trip updated: ' . $trip->location);

        if ($user->hasRole('Driver')) {
            return redirect()->route('trips.my')->with('success', 'Trip updated successfully!');
        }

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

    public function destroy(Trip $trip)
    {
        $location = $trip->location;
        $trip->delete();
        \App\Models\ActivityLog::log('deleted', 'Trip', 'Trip deleted: ' . $location);
        return redirect()->route('trips.index')->with('success', 'Trip deleted.');
    }
}
