<?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('role', 'customer')->withCount('orders');

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

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

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

    public function show(User $customer)
    {
        if ($customer->role !== 'customer') {
            abort(404);
        }

        $customer->load(['orders.items.product', 'orders.payments']);
        $orders = $customer->orders()->latest()->paginate(10);

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

    public function updateStatus(Request $request, User $customer)
    {
        if ($customer->role !== 'customer') {
            abort(404);
        }

        $validated = $request->validate([
            'is_active' => ['boolean'],
        ]);

        // Using soft delete for deactivation
        if (isset($validated['is_active']) && ! $validated['is_active']) {
            $customer->delete();
            $message = 'Customer account disabled.';
        } else {
            $customer->restore();
            $message = 'Customer account enabled.';
        }

        return redirect()->route('admin.customers.show', $customer)
            ->with('success', $message);
    }
}
