<?php

namespace App\Http\Controllers\Api;

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');

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

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

        $customers = $query->withCount('orders')
            ->orderBy('created_at', 'desc')
            ->paginate($request->per_page ?? 15);

        return response()->json(['success' => true, 'data' => $customers]);
    }

    public function show(User $user)
    {
        $user->load(['orders' => fn($q) => $q->latest()->take(10)]);
        $user->loadCount('orders');
        $user->total_spent = $user->orders()->where('payment_status', 'paid')->sum('total');

        return response()->json(['success' => true, 'data' => $user]);
    }

    public function toggleStatus(User $user)
    {
        $user->update(['is_active' => !$user->is_active]);
        return response()->json([
            'success' => true,
            'data' => $user,
            'message' => 'Customer status updated',
        ]);
    }

    public function stats()
    {
        return response()->json([
            'success' => true,
            'data' => [
                'total' => User::where('role', 'customer')->count(),
                'active' => User::where('role', 'customer')->where('is_active', true)->count(),
                'new_today' => User::where('role', 'customer')->whereDate('created_at', today())->count(),
                'new_this_month' => User::where('role', 'customer')->whereMonth('created_at', now()->month)->count(),
            ],
        ]);
    }
}
