<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class CustomerController extends Controller
{
    public function index(Request $request)
    {
        $customers = User::where('is_admin', false)
            ->withCount(['licenses', 'orders'])
            ->when($request->search, fn($q) => $q->where(function ($q) use ($request) {
                $q->where('name', 'like', "%{$request->search}%")
                  ->orWhere('email', 'like', "%{$request->search}%");
            }))
            ->latest()
            ->paginate((int) setting('items_per_page', 25));

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

    public function show(User $customer)
    {
        abort_if($customer->is_admin, 404);
        $customer->load(['licenses.product', 'orders', 'downloads']);
        return view('admin.customers.show', compact('customer'));
    }

    public function suspend(User $customer)
    {
        $customer->update(['is_active' => false]);
        return back()->with('success', 'Customer suspended.');
    }

    public function activate(User $customer)
    {
        $customer->update(['is_active' => true]);
        return back()->with('success', 'Customer activated.');
    }

    public function impersonate(Request $request, User $customer)
    {
        abort_if($customer->is_admin, 403);
        session(['impersonating' => auth()->id()]);
        auth()->login($customer);
        return redirect()->route('customer.dashboard')->with('info', "Impersonating {$customer->name}");
    }
}
