<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\DriverShift;
use App\Services\ShiftService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class DriverShiftController extends Controller
{
    public function index(Request $request): View
    {
        $companyId = $request->user()->company_id;

        $shifts = DriverShift::with(['driver', 'vehicle'])
            ->when($companyId, fn ($q) => $q->whereHas('driver', fn ($d) => $d->where('company_id', $companyId)))
            ->latest('started_at')
            ->get();

        return view('admin.shifts.index', compact('shifts'));
    }

    /**
     * Admin force-ends a shift the driver never closed themselves — mirrors
     * the old project's saveendshift, but as a clean boolean state change
     * (ended_at set) instead of the old SHF_TYPE/IS_ACTIVE pair, and cancels
     * any of the driver's still-open bookings rather than leaving them
     * silently orphaned.
     */
    public function forceEnd(Request $request, DriverShift $shift, ShiftService $shifts): RedirectResponse
    {
        $this->authorizeCompanyOwnership($shift->driver);

        $request->validate(['reason' => ['nullable', 'string', 'max:500']]);

        if ($shift->ended_at) {
            return back()->with('error', 'That shift has already ended.');
        }

        $shifts->end($shift, $request->user(), $request->input('reason'));

        return redirect()->route('admin.shifts.index')->with('success', 'Shift ended for '.$shift->driver->full_name.'.');
    }
}
