<?php

namespace App\Services\Admin;

use App\Models\Hub;
use App\Models\User;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Cache;

// ══════════════════════════════════════════════════════════════════
//  InPractice — Admin\UserService
//  Location: app/Services/Admin/UserService.php
//
//  All admin user management logic lives here.
//  Controller calls these methods — nothing else.
//
//  Methods:
//    index()        → paginated member list with filters
//    toggleActive() → suspend or reactivate a member account
// ══════════════════════════════════════════════════════════════════

class UserService
{
    /**
     * Paginated member list for the admin users table.
     *
     * Filters: search (name / email / nickname), hub_id,
     *          experience_level, status (active / suspended)
     */
    public function index(array $filters = []): array
    {
        $query = User::where('role', 'member')
            ->with(['hubs:id,name_en,name_ar,color'])
            ->select([
                'id',
                'name',
                'nickname',
                'email',
                'profession',
                'experience_level',
                'is_active',
                'created_at',
            ])
            ->orderByDesc('created_at');

        // ── Search ─────────────────────────────────────────────
        if (!empty($filters['search'])) {
            $term = $filters['search'];
            $query->where(function ($q) use ($term) {
                $q->where('name',     'like', "%{$term}%")
                  ->orWhere('email',    'like', "%{$term}%")
                  ->orWhere('nickname', 'like', "%{$term}%");
            });
        }

        // ── Hub filter ─────────────────────────────────────────
        if (!empty($filters['hub_id'])) {
            $query->whereHas('hubs', function ($q) use ($filters) {
                $q->where('hubs.id', $filters['hub_id']);
            });
        }

        // ── Experience level filter ────────────────────────────
        if (!empty($filters['experience_level'])) {
            $query->where('experience_level', $filters['experience_level']);
        }

        // ── Status filter ──────────────────────────────────────
        if (isset($filters['status']) && $filters['status'] !== '') {
            $query->where('is_active', $filters['status'] === 'active');
        }

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

        // Map to safe array — never expose passwords or tokens
        $users->getCollection()->transform(fn ($u) => [
            'id'               => $u->id,
            'name'             => $u->name,
            'nickname'         => $u->nickname,
            'email'            => $u->email,
            'profession'       => $u->profession,
            'experience_level' => $u->experience_level,
            'is_active'        => $u->is_active,
            'created_at'       => $u->created_at->format('d M Y'),
            'created_at_diff'  => $u->created_at->diffForHumans(),
            'hubs'             => $u->hubs->map(fn ($h) => [
                'id'      => $h->id,
                'name_en' => $h->name_en,
                'color'   => $h->color,
            ])->toArray(),
        ]);

        return [
            'users'   => $users,
            'hubs'    => $this->getHubs(),
            'filters' => $filters,
        ];
    }

    /**
     * Toggle a member's active status.
     * Returns the new is_active value so Vue can update without reload.
     */
    public function toggleActive(User $user): bool
    {
        $newStatus = ! $user->is_active;

        $user->update(['is_active' => $newStatus]);

        // Clear the admin stats cache — member counts need to refresh
        Cache::forget('admin.member_stats');

        return $newStatus;
    }

    // ── Private helpers ───────────────────────────────────────

    private function getHubs(): array
    {
        return Cache::remember('hubs.active', 3600, function () {
            return Hub::where('is_active', true)
                ->select('id', 'name_en', 'name_ar', 'color')
                ->orderBy('id')
                ->get()
                ->toArray();
        });
    }
}
