<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class CustomerController extends Controller
{
    public function index(Request $request)
    {
        $customers = User::where('role', 'customer')
            ->withCount('orders')
            ->when($request->filled('search'), fn ($q) => $q->where(function ($q) use ($request) {
                $q->where('name', 'like', '%'.$request->search.'%')
                    ->orWhere('email', 'like', '%'.$request->search.'%');
            }))
            ->latest()
            ->paginate(15)
            ->withQueryString();

        return view('admin.customers.index', compact('customers'));
    }

    public function show(User $customer)
    {
        abort_if($customer->role !== 'customer', 404);

        $customer->load(['orders' => fn ($q) => $q->latest(), 'addresses']);

        return view('admin.customers.show', compact('customer'));
    }

    public function toggleActive(User $customer): RedirectResponse
    {
        abort_if($customer->role !== 'customer', 404);

        $customer->update(['is_active' => ! $customer->is_active]);

        return back()->with('success', 'Customer status updated.');
    }
}
