<?php

namespace App\Livewire\Admin\Customer;

use App\Models\GuestCustomer;
use App\Models\Order;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('layouts.admin')]
#[Title('Detail Customer')]
class Show extends Component
{
    use WithPagination;

    public string $type; // 'user' | 'guest'
    public int $customerId;

    // Data customer (di-load di mount, di-cache sebagai property)
    public string $name;
    public ?string $phone = null;
    public ?string $email = null;
    public ?bool $isActive = null;
    public $joinedAt;

    public function mount(string $type, int $id): void
    {
        abort_unless(in_array($type, ['user', 'guest']), 404);

        $this->type       = $type;
        $this->customerId = $id;

        if ($type === 'user') {
            $user = User::role('customer')->findOrFail($id);
            $this->name     = $user->name;
            $this->phone    = $user->phone;
            $this->email    = $user->email;
            $this->isActive = $user->is_active;
            $this->joinedAt = $user->created_at;
        } else {
            $guest = GuestCustomer::findOrFail($id);
            $this->name     = $guest->name;
            $this->phone    = $guest->phone;
            $this->email    = null;
            $this->isActive = null;
            $this->joinedAt = $guest->created_at;
        }
    }

    public function toggleActive(): void
    {
        abort_unless(Auth::user()->can('customer.deactivate'), 403);

        if ($this->type !== 'user') {
            return;
        }

        $user = User::role('customer')->findOrFail($this->customerId);
        $user->update(['is_active' => ! $user->is_active]);
        $this->isActive = $user->fresh()->is_active;

        $label = $this->isActive ? 'diaktifkan' : 'dinonaktifkan';
        $this->dispatch('notify', type: 'success', message: "Akun customer berhasil {$label}.");
    }

    private function ordersQuery()
    {
        return $this->type === 'user'
            ? Order::where('user_id', $this->customerId)
            : Order::where('guest_customer_id', $this->customerId);
    }

    public function render()
    {
        $ordersForList = $this->ordersQuery()->latest()->paginate(10);

        // Satu query agregat untuk seluruh statistik, hindari pemanggilan
        // ordersQuery() berulang kali yang masing-masing membuka query baru.
        $aggregate = $this->ordersQuery()
            ->selectRaw('COUNT(*) as total_orders, COALESCE(SUM(grand_total), 0) as total_spent, MAX(created_at) as last_order_at')
            ->first();

        $totalOrders = (int) $aggregate->total_orders;
        $totalSpent  = (float) $aggregate->total_spent;

        $stats = [
            'total_orders'  => $totalOrders,
            'total_spent'   => $totalSpent,
            'last_order_at' => $aggregate->last_order_at,
            'average_order' => $totalOrders > 0 ? $totalSpent / $totalOrders : 0,
        ];

        return view('livewire.admin.customer.show', [
            'orders' => $ordersForList,
            'stats'  => $stats,
        ]);
    }
}
