<?php

namespace App\Http\Controllers;

use App\Models\Customer;
use App\Models\Order;
use App\Services\CustomerPortalService;
use App\Services\OrderService;
use Illuminate\Http\Request;

class PortalPreviewController extends Controller
{
    public function index(Request $request)
    {
        $branchId = $request->user()->isOwner() ? $request->integer('branch_id') : $request->user()->branch_id;
        $search = trim((string) $request->input('q'));

        return view('portal-preview.index', [
            'customers' => Customer::query()
                ->withCount(['orders', 'orderRequests'])
                ->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
                ->when($search !== '', fn ($q) => $q->where(fn ($inner) => $inner->where('name', 'like', "%{$search}%")->orWhere('phone', 'like', "%{$search}%")))
                ->latest()
                ->paginate(20)
                ->withQueryString(),
            'search' => $search,
        ]);
    }

    public function customer(Customer $customer, Request $request, OrderService $orderService)
    {
        $this->authorizeCustomer($customer);
        $query = trim((string) $request->input('invoice_no'));
        $ordersQuery = $customer->orders()->with('progressLogs')->latest();

        if ($query !== '') {
            $ordersQuery->where('invoice_no', 'like', "%{$query}%");
        }

        return view('portal.dashboard', [
            'customer' => $customer,
            'orders' => $ordersQuery->limit(15)->get(),
            'rewardProgress' => min(5, $orderService->paidInvoiceCountForReward($customer->id)),
            'invoiceQuery' => $query,
            'requests' => $customer->orderRequests()->latest()->limit(5)->get(),
            'previewMode' => true,
            'previewTitle' => 'Preview portal dari menu admin',
            'previewHomeUrl' => route('portal-preview.customer', $customer),
            'previewBackUrl' => route('portal-preview.index'),
            'portalRequestUrl' => route('portal-preview.requests', $customer),
            'portalAccountUrl' => route('portal-preview.account', $customer),
        ]);
    }

    public function requests(Customer $customer)
    {
        $this->authorizeCustomer($customer);

        return view('portal.requests', [
            'customer' => $customer,
            'orders' => $customer->orders()->latest()->limit(20)->get(),
            'requests' => $customer->orderRequests()->latest()->limit(20)->get(),
            'previewMode' => true,
            'previewHomeUrl' => route('portal-preview.customer', $customer),
            'previewBackUrl' => route('portal-preview.customer', $customer),
            'portalRequestUrl' => route('portal-preview.requests', $customer),
            'portalAccountUrl' => route('portal-preview.account', $customer),
        ]);
    }

    public function account(Customer $customer)
    {
        $this->authorizeCustomer($customer);

        return view('portal.account', [
            'customer' => $customer,
            'previewMode' => true,
            'previewHomeUrl' => route('portal-preview.customer', $customer),
            'previewBackUrl' => route('portal-preview.customer', $customer),
            'portalRequestUrl' => route('portal-preview.requests', $customer),
            'portalAccountUrl' => route('portal-preview.account', $customer),
        ]);
    }

    public function order(Customer $customer, Order $order, CustomerPortalService $portalService)
    {
        $this->authorizeCustomer($customer);
        abort_unless((int) $order->customer_id === (int) $customer->id, 403);

        return view('portal.order', [
            'tracking' => $portalService->trackingData($order),
            'order' => $order,
            'previewMode' => true,
            'previewHomeUrl' => route('portal-preview.customer', $customer),
            'previewBackUrl' => route('portal-preview.customer', $customer),
            'portalRequestUrl' => route('portal-preview.requests', $customer),
            'portalAccountUrl' => route('portal-preview.account', $customer),
        ]);
    }

    private function authorizeCustomer(Customer $customer): void
    {
        abort_unless(auth()->user()->isOwner() || auth()->user()->canAccessBranch((int) $customer->branch_id), 403);
    }
}
