<?php

namespace App\Http\Controllers\Frontdesk;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\Payment;
use App\Services\OrderTotalsService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class PaymentController extends Controller
{
    public function __construct(private readonly OrderTotalsService $totalsService)
    {
    }

    public function store(Request $request, Order $order): RedirectResponse
    {
        $this->ensureOrderAccessible($request, $order);

        $data = $request->validate([
            'amount' => ['required', 'numeric', 'min:0.01'],
            'method' => ['required', 'in:cash,transfer,pos,card,online,other'],
            'reference' => ['nullable', 'string', 'max:255'],
            'paid_at' => ['nullable', 'date'],
        ]);

        $order->payments()->create([
            'amount' => (float) $data['amount'],
            'method' => $data['method'],
            'reference' => $data['reference'] ?? null,
            'received_by' => $request->user()->id,
            'paid_at' => $data['paid_at'] ?? now(),
        ]);

        $this->totalsService->recalculate($order);

        return back()->with('success', 'Payment recorded.');
    }

    public function destroy(Request $request, Order $order, Payment $payment): RedirectResponse
    {
        $this->ensureOrderAccessible($request, $order);

        if ((int) $payment->order_id !== (int) $order->id) {
            abort(404);
        }

        $payment->delete();
        $this->totalsService->recalculate($order);

        return back()->with('success', 'Payment deleted.');
    }

    private function ensureOrderAccessible(Request $request, Order $order): void
    {
        $user = $request->user();
        if (in_array($user->role, ['lab_manager', 'lab_staff'], true) && (int) $order->lab_id !== (int) $user->lab_id) {
            abort(403, 'Unauthorized order access.');
        }
    }
}
