<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Models\OrderDetail;
use App\Notifications\LaundryProgressNotification;
use App\Services\PaymentService;
use App\Services\ProgressService;
use App\Services\WhatsAppGateway;
use Illuminate\Http\Request;

class LaundryOrderController extends Controller
{
    public function index(Request $request)
    {
        $branchId = $request->user()->isOwner() ? $request->integer('branch_id') : $request->user()->branch_id;

        return view('orders.index', [
            'orders' => Order::query()
                ->with('customer')
                ->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
                ->latest()
                ->paginate(20),
        ]);
    }

    public function show(Order $order)
    {
        $this->authorizeBranch($order);

        return view('orders.show', [
            'order' => $order->load(['customer', 'details.staff', 'progressLogs', 'payments']),
        ]);
    }

    public function receipt(Order $order)
    {
        $this->authorizeBranch($order);

        return view('orders.receipt', [
            'order' => $order->load(['branch', 'customer', 'cashier', 'details', 'payments']),
        ]);
    }

    public function updateStatus(Request $request, Order $order, ProgressService $progressService)
    {
        $this->authorizeBranch($order);
        $data = $request->validate([
            'status' => ['required', 'in:baru,proses,selesai,diambil'],
            'note' => ['nullable', 'string', 'max:1000'],
        ]);

        $progressService->updateCoreStatus($order, $data['status'], $request->user(), $data['note'] ?? null);

        return back()->with('status', 'Status order diperbarui.');
    }

    public function updateProgress(Request $request, Order $order, ProgressService $progressService)
    {
        $this->authorizeBranch($order);
        $data = $request->validate([
            'progress_status' => ['required', 'in:'.implode(',', Order::PROGRESS_STATUSES)],
            'note' => ['nullable', 'string', 'max:1000'],
        ]);

        $progressService->updateProgress($order, $data['progress_status'], $request->user(), $data['note'] ?? null);

        return back()->with('status', 'Progress pelanggan diperbarui.');
    }

    public function updateDetailProgress(Request $request, Order $order, OrderDetail $orderDetail, ProgressService $progressService)
    {
        $this->authorizeBranch($order);
        $data = $request->validate([
            'progress_status' => ['required', 'in:'.implode(',', Order::PROGRESS_STATUSES)],
            'note' => ['nullable', 'string', 'max:1000'],
        ]);

        $progressService->updateDetailProgress($order, $orderDetail, $data['progress_status'], $request->user(), $data['note'] ?? null);

        return back()->with('status', 'Progress item diperbarui.');
    }

    public function storePayment(Request $request, Order $order, PaymentService $paymentService)
    {
        $this->authorizeBranch($order);
        $data = $request->validate([
            'amount' => ['required', 'numeric', 'min:1'],
            'method' => ['required', 'in:cash,transfer,qris'],
            'reference' => ['nullable', 'string', 'max:120'],
            'note' => ['nullable', 'string', 'max:1000'],
        ]);

        $paymentService->recordPayment($order, (float) $data['amount'], $data['method'], $request->user(), $data['reference'] ?? null, $data['note'] ?? null);

        return back()->with('status', 'Pembayaran berhasil dicatat.');
    }

    public function sendWhatsApp(Order $order, WhatsAppGateway $gateway)
    {
        $this->authorizeBranch($order);
        (new LaundryProgressNotification($order->load('customer')))->sendWhatsApp($gateway);

        return back()->with('status', 'Update WhatsApp dikirim via gateway terkonfigurasi.');
    }

    private function authorizeBranch(Order $order): void
    {
        abort_unless(auth()->user()->canAccessBranch($order->branch_id), 403);
    }
}
