<?php

namespace Modules\Users\Controllers;

use App\Controllers\BaseController;
use App\Models\BranchModel;
use App\Models\DepartmentModel;
use App\Models\PermissionModel;
use App\Models\RoleModel;
use App\Models\RolePermissionModel;
use Modules\Auth\Models\UserModel;
use Modules\Tpin\Services\TpinService;
use Modules\Users\Services\UserService;

class UserController extends BaseController
{
    protected UserModel $users;
    protected UserService $service;
    protected RoleModel $roles;
    protected BranchModel $branches;
    protected DepartmentModel $departments;

    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->service     = new UserService();
        $this->roles       = new RoleModel();
        $this->branches    = new BranchModel();
        $this->departments = new DepartmentModel();
    }

    public function index()
    {
        $search       = trim((string) $this->request->getGet('q'));
        $status       = $this->request->getGet('status') ?: null;
        $roleId       = $this->request->getGet('role_id') ?: null;
        $branchId     = $this->request->getGet('branch_id') ?: null;
        $departmentId = $this->request->getGet('department_id') ?: null;
        $showTrashed  = (bool) $this->request->getGet('trashed');

        $query = $this->users->scopeForList($search ?: null, $status, $roleId ? (int) $roleId : null, $branchId ? (int) $branchId : null, $departmentId ? (int) $departmentId : null, $showTrashed);
        $users = $query->orderBy('created_at', 'DESC')->paginate(15);

        return view('Modules\Users\Views\index', array_merge($this->baseViewData(), [
            'title'       => 'User Management',
            'breadcrumbs' => ['Dashboard' => base_url('dashboard'), 'Users'],
            'users'       => $users,
            'pager'       => $this->users->pager,
            'roles'       => $this->roles->orderBy('name', 'ASC')->findAll(),
            'branches'    => $this->branches->orderBy('name', 'ASC')->findAll(),
            'departments' => $this->departments->orderBy('name', 'ASC')->findAll(),
            'filters'     => compact('search', 'status', 'roleId', 'branchId', 'departmentId', 'showTrashed'),
            'onlineIds'   => $this->onlineIdsFor($users),
        ]));
    }

    public function createForm()
    {
        $tpinPolicy = (new \Modules\Tpin\Services\TpinService())->companyPolicy();

        return view('Modules\Users\Views\create', array_merge($this->baseViewData(), [
            'title'       => 'Add User',
            'breadcrumbs' => ['Dashboard' => base_url('dashboard'), 'Users' => base_url('users'), 'Add User'],
            'roles'       => $this->roles->orderBy('name', 'ASC')->findAll(),
            'branches'    => $this->branches->orderBy('name', 'ASC')->findAll(),
            'departments' => $this->departments->orderBy('name', 'ASC')->findAll(),
            'groupedPerms' => (new PermissionModel())->grouped(),
            'assignedIds' => array_map('intval', (array) old('permissions', [])),
            'accessMode'  => old('access_mode', 'existing_role'),
            'tpinDefault' => $tpinPolicy['required_by_default'] && $tpinPolicy['enabled'],
        ]));
    }

    public function store()
    {
        $rules = [
            'first_name' => 'required|min_length[2]|max_length[100]',
            'last_name'  => 'required|min_length[2]|max_length[100]',
            'username'   => 'required|alpha_numeric_punct|min_length[3]|max_length[100]',
            'email'      => 'required|valid_email|max_length[191]',
            'phone'      => 'permit_empty|max_length[30]',
            'status'     => 'permit_empty|in_list[active,inactive]',
        ];

        if (! $this->validate($rules)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $result = $this->service->create($this->request->getPost(), (int) $this->session->get('user_id'));

        if (! $result['success']) {
            return redirect()->back()->withInput()->with('errors', $result['errors']);
        }

        return redirect()->to('/users')->with('success', "User created. Temporary password: {$result['tempPassword']} (share this securely — it will not be shown again).");
    }

    public function editForm(int $id)
    {
        $user = $this->users->withDeleted()->find($id);
        if (! $user) {
            return redirect()->to('/users')->with('error', 'User not found.');
        }

        $role          = $user->role_id ? $this->roles->find($user->role_id) : null;
        $isCustomRole  = $this->service->isCustomRole($role);
        $assignedIds   = $user->role_id
            ? (new RolePermissionModel())->permissionIdsForRole((int) $user->role_id)
            : [];

        return view('Modules\Users\Views\edit', array_merge($this->baseViewData(), [
            'title'        => 'Edit User',
            'breadcrumbs'  => ['Dashboard' => base_url('dashboard'), 'Users' => base_url('users'), 'Edit User'],
            'user'         => $user,
            'roles'        => $this->roles->orderBy('name', 'ASC')->findAll(),
            'branches'     => $this->branches->orderBy('name', 'ASC')->findAll(),
            'departments'  => $this->departments->orderBy('name', 'ASC')->findAll(),
            'groupedPerms' => (new PermissionModel())->grouped(),
            'assignedIds'  => array_map('intval', (array) old('permissions', $assignedIds)),
            'accessMode'   => old('access_mode', $isCustomRole ? 'custom_permissions' : 'existing_role'),
            'userRole'     => $role,
        ]));
    }

    public function update(int $id)
    {
        $rules = [
            'first_name' => 'required|min_length[2]|max_length[100]',
            'last_name'  => 'required|min_length[2]|max_length[100]',
            'username'   => 'required|alpha_numeric_punct|min_length[3]|max_length[100]',
            'email'      => 'required|valid_email|max_length[191]',
            'phone'      => 'permit_empty|max_length[30]',
        ];

        if (! $this->validate($rules)) {
            return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
        }

        $result = $this->service->update($id, $this->request->getPost(), (int) $this->session->get('user_id'));

        if (! $result['success']) {
            return redirect()->back()->withInput()->with('errors', $result['errors']);
        }

        return redirect()->to('/users')->with('success', 'User updated successfully.');
    }

    public function show(int $id)
    {
        $user = $this->users->withDeleted()->find($id);
        if (! $user) {
            return redirect()->to('/users')->with('error', 'User not found.');
        }

        $role         = $user->role_id ? $this->roles->find($user->role_id) : null;
        $permCount    = $user->role_id
            ? count((new RolePermissionModel())->permissionIdsForRole((int) $user->role_id))
            : 0;

        return view('Modules\Users\Views\show', array_merge($this->baseViewData(), [
            'title'       => 'User Profile',
            'breadcrumbs' => ['Dashboard' => base_url('dashboard'), 'Users' => base_url('users'), $user->getFullName()],
            'user'        => $user,
            'isOnline'    => $this->service->isOnline($id),
            'tpinStatus'  => (new TpinService())->statusFor($id),
            'userRole'    => $role,
            'permCount'   => $permCount,
            'isCustomRole' => $this->service->isCustomRole($role),
        ]));
    }

    public function uploadAvatar(int $id)
    {
        $file = $this->request->getFile('avatar');
        if (! $file) {
            return redirect()->back()->with('error', 'No file selected.');
        }

        $result = $this->service->uploadAvatar($id, $file);

        if (! $result['success']) {
            return redirect()->back()->with('error', $result['error']);
        }

        return redirect()->back()->with('success', 'Profile photo updated.');
    }

    public function activate(int $id)
    {
        $this->service->activate($id, (int) $this->session->get('user_id'));

        return redirect()->back()->with('success', 'User activated.');
    }

    public function deactivate(int $id)
    {
        $this->service->deactivate($id, (int) $this->session->get('user_id'));

        return redirect()->back()->with('success', 'User deactivated.');
    }

    public function destroy(int $id)
    {
        $this->service->softDelete($id, (int) $this->session->get('user_id'));

        return redirect()->to('/users')->with('success', 'User moved to trash.');
    }

    public function restore(int $id)
    {
        $this->service->restore($id, (int) $this->session->get('user_id'));

        return redirect()->back()->with('success', 'User restored.');
    }

    public function resetPassword(int $id)
    {
        $tempPassword = $this->service->adminResetPassword($id, (int) $this->session->get('user_id'));

        return redirect()->back()->with('success', "Password reset. Temporary password: {$tempPassword} (share this securely — it will not be shown again).");
    }

    /**
     * @param iterable $users
     */
    private function onlineIdsFor(iterable $users): array
    {
        $ids = [];
        foreach ($users as $u) {
            if ($this->service->isOnline($u->id)) {
                $ids[] = $u->id;
            }
        }

        return $ids;
    }
}
