<?php

namespace App\Http\Controllers\Admin;

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

class CustomerController extends Controller
{
    public function index(Request $request)
    {
        $query = User::where('is_admin', false)->withCount('orders')->withSum('orders', 'total_amount');

        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('email', 'like', "%{$search}%")
                  ->orWhere('phone', 'like', "%{$search}%");
            });
        }

        $customers = $query->latest()->paginate(15);

        return view('admin.customers.index', [
            'customers' => $customers,
            'search' => $request->search,
        ]);
    }

    public function show(User $customer)
    {
        $customer->load(['orders.items']);
        $totalSpent = $customer->orders->sum('total_amount');
        $ordersCount = $customer->orders->count();
        $avgOrderValue = $ordersCount > 0 ? $totalSpent / $ordersCount : 0;

        $recentAddress = $customer->orders->first();

        return view('admin.customers.show', [
            'customer' => $customer,
            'totalSpent' => $totalSpent,
            'ordersCount' => $ordersCount,
            'avgOrderValue' => $avgOrderValue,
            'recentAddress' => $recentAddress,
        ]);
    }
}
