<?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::withCount('orders')->latest();

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

        if ($request->status) {
            $query->where('status', $request->status);
        }

        $customers = $query->paginate(20)->withQueryString();

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

    public function create()
    {
        return view('admin.customers.create');
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email',
            'phone' => 'required|string|unique:users,phone',
            'password' => 'required|string|min:8|confirmed',
        ]);

        $data['password'] = \Illuminate\Support\Facades\Hash::make($data['password']);
        $data['status'] = 'active';

        $user = User::create($data);

        return redirect()->route('admin.customers.show', $user)->with('success', 'Customer created successfully.');
    }

    public function show(User $customer)
    {
        $customer->loadCount(['orders']);
        $customer->load(['wallet.transactions' => fn($q) => $q->limit(10)]);
        $orders = $customer->orders()->with('vendor')->latest()->paginate(10);

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

    public function block(User $customer)
    {
        $customer->update(['status' => 'blocked']);
        return back()->with('success', "Customer {$customer->name} has been blocked.");
    }

    public function unblock(User $customer)
    {
        $customer->update(['status' => 'active']);
        return back()->with('success', "Customer {$customer->name} has been unblocked.");
    }
}
