<?php

namespace App\Http\Controllers\Franchise;

use App\Http\Controllers\Controller;
use App\Models\Franchise;
use App\Models\Order;
use App\Services\PickupService;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class PickupController extends Controller
{
    public function index(Request $request): View
    {
        $tab = (string) $request->input('tab', 'pending');
        $franchise = Franchise::query()->where('created_by', auth()->id())->first();

        $statusMap = [
            'pending' => 'approved',
            'ready' => 'dispatched',
            'collected' => 'delivered',
        ];

        if (! isset($statusMap[$tab])) {
            $tab = 'pending';
        }

        $orders = Order::query()
            ->where('franchise_id', $franchise?->id)
            ->where('status', $statusMap[$tab])
            ->with('user')
            ->latest('id')
            ->paginate(15);

        return view('franchise.pickups', compact('orders', 'tab'));
    }

    public function verify(Request $request, Order $order, PickupService $pickupService): RedirectResponse
    {
        $validated = $request->validate([
            'otp' => ['required', 'string', 'max:50'],
        ]);

        $franchise = Franchise::query()->where('created_by', auth()->id())->first();
        if (! $franchise || $order->franchise_id !== $franchise->id) {
            return back()->withErrors(['order' => 'Unauthorized pickup order.']);
        }

        try {
            $pickupService->verify($order, $validated['otp'], auth()->id());
        } catch (\RuntimeException $exception) {
            return back()->withErrors(['otp' => $exception->getMessage()]);
        }

        return back()->with('status', 'Pickup verified and marked collected.');
    }
}

