<?php

namespace App\Http\Controllers\Admin;

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

use App\Models\Setting;

class CustomerController extends Controller
{
    public function index(Request $request)
    {
        $currencySymbol = Setting::where('key', 'currency_symbol')->value('value') ?? '$';
        $query = User::latest();

        if ($request->has('search') && $request->search != '') {
            $search = $request->search;
            $query->where('name', 'like', "%$search%")
                  ->orWhere('email', 'like', "%$search%")
                  ->orWhere('phone', 'like', "%$search%");
        }

        $customers = $query->paginate(10);
        return view('admin.customers.index', compact('customers', 'currencySymbol'));
    }

    public function show($id)
    {
        $currencySymbol = Setting::where('key', 'currency_symbol')->value('value') ?? '$';
        $customer = User::withCount('orders')->findOrFail($id);
        $recentOrders = Order::where('user_id', $id)->latest()->take(5)->get();
        $totalSpent = Order::where('user_id', $id)->where('payment_status', 'paid')->sum('total');

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