<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    protected $auditLog;

    public function __construct(\App\Services\AuditLogService $auditLog)
    {
        $this->auditLog = $auditLog;
    }

    public function index(Request $request)
    {
        \Log::debug('DB_INFO_ADMIN', [
            'database' => \DB::connection()->getDatabaseName(),
            'host' => \DB::connection()->getConfig('host'),
            'port' => \DB::connection()->getConfig('port'),
            'count' => \App\Models\User::count(),
        ]);
        
        $query = User::with(['role', 'subscriptions.plan']);

        if ($request->filled('search')) {
            $query->where('name', 'like', "%{$request->search}%")
                  ->orWhere('email', 'like', "%{$request->search}%");
        }

        if ($request->filled('role')) {
            $query->whereHas('role', fn($q) => $q->where('name', $request->role));
        }

        $users = $query->latest()->paginate(20);
        return view('admin.users.index', compact('users'));
    }

    public function show(User $user)
    {
        $user->load(['role', 'subscriptions.manual_payments', 'member_profile', 'leasing_profile']);
        return view('admin.users.show', compact('user'));
    }

    public function toggleStatus(User $user)
    {
        $newStatus = $user->account_status === 'active' ? 'suspended' : 'active';
        $user->update(['account_status' => $newStatus]);
        
        $this->auditLog->log('USER_STATUS_TOGGLED', $user, null, ['new_status' => $newStatus]);
        
        return back()->with('success', "Status akun {$user->name} berhasil diperbarui menjadi {$newStatus}.");
    }
}
