<?php

namespace App\Http\Controllers;

use App\Models\Visitor;
use App\Support\BranchContext;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;
use Illuminate\Support\Carbon;
use Illuminate\View\View;

class VisitorController extends Controller implements HasMiddleware
{
    public static function middleware(): array
    {
        return [
            new Middleware('can:visitors.view', only: ['index', 'pass']),
            new Middleware('can:visitors.create', only: ['create', 'store']),
            new Middleware('can:visitors.update', only: ['checkout']),
            new Middleware('can:visitors.delete', only: ['destroy']),
        ];
    }

    public function index(Request $request): View
    {
        $date = $request->date('date') ?: Carbon::today();
        $status = $request->input('status');

        $visitors = Visitor::with('recorder')
            ->whereDate('visit_date', $date)
            ->when($status, fn ($q) => $q->where('status', $status))
            ->latest('check_in')->get();

        return view('visitors.index', [
            'visitors' => $visitors,
            'date' => $date->toDateString(),
            'status' => $status,
            'insideCount' => $visitors->where('status', 'checked_in')->count(),
        ]);
    }

    public function create(): View
    {
        return view('visitors.create', ['visitor' => new Visitor()]);
    }

    public function store(Request $request, BranchContext $context): RedirectResponse
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:150'],
            'cnic' => ['nullable', 'string', 'max:20'],
            'phone' => ['nullable', 'string', 'max:30'],
            'purpose' => ['nullable', 'string', 'max:200'],
            'whom_to_meet' => ['nullable', 'string', 'max:150'],
            'party_size' => ['nullable', 'integer', 'min:1'],
            'remarks' => ['nullable', 'string', 'max:255'],
        ]);

        $branchId = $context->currentId() ?? auth()->user()->branch_id ?? \App\Models\Branch::min('id');

        $visitor = Visitor::create($data + [
            'branch_id' => $branchId,
            'pass_number' => Visitor::nextPass($branchId),
            'party_size' => $data['party_size'] ?? 1,
            'visit_date' => today(),
            'check_in' => now(),
            'status' => 'checked_in',
            'recorded_by' => auth()->id(),
        ]);

        return redirect()->route('visitors.pass', $visitor)->with('success', 'Visitor checked in. Pass '.$visitor->pass_number.'.');
    }

    public function checkout(Visitor $visitor): RedirectResponse
    {
        if ($visitor->status === 'checked_in') {
            $visitor->update(['status' => 'checked_out', 'check_out' => now()]);
        }

        return back()->with('success', 'Visitor checked out.');
    }

    public function pass(Visitor $visitor): View
    {
        return view('visitors.pass', compact('visitor'));
    }

    public function destroy(Visitor $visitor): RedirectResponse
    {
        $visitor->delete();

        return redirect()->route('visitors.index')->with('success', 'Visitor record deleted.');
    }
}
