<?php

namespace App\Controllers\Api\V1;

use App\Controllers\BaseController;
use App\Models\UserModel;
use App\Services\Support\ActivityLogger;
use App\Services\Support\AuditService;
use Config\Database;

/**
 * Super Admin only — gives visibility into every registered user across
 * all roles (candidates, recruiters, agency owners, super admins), not
 * just agencies. The Agencies page already covers company-level
 * management; this covers individual accounts.
 */
class AdminUserController extends BaseController
{
    private UserModel $users;
    private AuditService $audit;
    private ActivityLogger $activity;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->users = new UserModel();
        $this->audit = new AuditService();
        $this->activity = new ActivityLogger();
    }

    public function index()
    {
        $role = $this->request->getGet('role');
        $status = $this->request->getGet('status');
        $q = $this->request->getGet('q');

        $db = Database::connect();
        $builder = $db->table('users u')
            ->select('u.id, u.name, u.email, u.phone, u.status, u.username, u.email_verified_at, u.mobile_verified_at, u.last_login_at, u.created_at, r.slug as role_slug, r.name as role_name, a.company_name')
            ->join('roles r', 'r.id = u.role_id')
            ->join('agencies a', 'a.id = u.agency_id', 'left');

        if ($role) {
            $builder->where('r.slug', $role);
        }
        if ($status) {
            $builder->where('u.status', $status);
        }
        if ($q) {
            $builder->groupStart()
                ->like('u.name', $q)
                ->orLike('u.email', $q)
                ->orLike('u.phone', $q)
            ->groupEnd();
        }

        $users = $builder->orderBy('u.created_at', 'DESC')->limit(200)->get()->getResultArray();

        return $this->jsonSuccess($users);
    }

    /**
     * Complete activity history for ONE specific user — whatever role
     * they are (candidate, recruiter, agency owner). Lets Super Admin
     * drill into "what has this exact person done on the platform",
     * rather than scrolling the platform-wide Audit Log looking for them.
     */
    public function userActivity(int $id)
    {
        $user = $this->users->findWithRole($id);
        if (! $user) {
            return $this->jsonError([['code' => 'NOT_FOUND', 'message' => 'User not found.']], 404);
        }

        $db = Database::connect();
        $page = max(1, (int) ($this->request->getGet('page') ?? 1));
        $perPage = 50;

        $builder = $db->table('activity_logs al')->where('al.user_id', $id);
        $total = $builder->countAllResults(false);

        $rows = $builder->orderBy('al.created_at', 'DESC')->limit($perPage, ($page - 1) * $perPage)->get()->getResultArray();

        return $this->jsonSuccess([
            'user' => ['id' => $user->id, 'name' => $user->name, 'email' => $user->email, 'role_slug' => $user->role_slug],
            'activity' => $rows,
        ], ['page' => $page, 'per_page' => $perPage, 'total' => $total]);
    }

    public function suspend(int $id)
    {
        $user = $this->users->find($id);
        if (! $user) {
            return $this->jsonError([['code' => 'NOT_FOUND', 'message' => 'User not found.']], 404);
        }
        if ($user->role_id === $this->currentUser()->role_id && $id === $this->currentUser()->id) {
            return $this->jsonError([['code' => 'CANNOT_SUSPEND_SELF', 'message' => 'You cannot suspend your own account.']], 422);
        }

        $before = ['status' => $user->status];
        $this->users->update($id, ['status' => 'inactive']);
        $this->audit->record($this->currentUser()->id, 'users', 'suspend', $id, $before, ['status' => 'inactive']);

        return $this->jsonSuccess(['message' => 'User suspended.']);
    }

    public function activate(int $id)
    {
        $user = $this->users->find($id);
        if (! $user) {
            return $this->jsonError([['code' => 'NOT_FOUND', 'message' => 'User not found.']], 404);
        }

        $before = ['status' => $user->status];
        $this->users->update($id, ['status' => 'active']);
        $this->audit->record($this->currentUser()->id, 'users', 'activate', $id, $before, ['status' => 'active']);

        return $this->jsonSuccess(['message' => 'User activated.']);
    }

    public function ban(int $id)
    {
        $user = $this->users->find($id);
        if (! $user) {
            return $this->jsonError([['code' => 'NOT_FOUND', 'message' => 'User not found.']], 404);
        }
        if ($id === $this->currentUser()->id) {
            return $this->jsonError([['code' => 'CANNOT_BAN_SELF', 'message' => 'You cannot ban your own account.']], 422);
        }

        $before = ['status' => $user->status];
        $this->users->update($id, ['status' => 'banned']);
        $this->audit->record($this->currentUser()->id, 'users', 'ban', $id, $before, ['status' => 'banned']);

        return $this->jsonSuccess(['message' => 'User banned.']);
    }
}
