<?php
declare(strict_types=1);

namespace App\Controller;

use App\Controller\AppController;
use cake\ORM\TableRegistry;
use Cake\Mailer\Email;
use Cake\Auth\DefaultPasswordHasher;
use Cake\Utility\Security;
use Cake\Core\Configure;
use Cake\I18n\Time;
use Cake\Event\EventInterface;


/**
 * Users Controller
 *
 * @property \App\Model\Table\UsersTable $Users
 * @method \App\Model\Entity\User[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
 */
class UsersController extends AppController
{
    public function initialize(): void
    {
        parent::initialize();
    }

    public function beforeFilter(EventInterface $event)
    {
        parent::beforeFilter($event);
        $this->Authentication->addUnauthenticatedActions(['login', 'logout']);

    }

    public function beforeRender(EventInterface $event)
    {
        parent::beforeRender($event);

        $this->viewBuilder()->setLayout('login');
    }

    // public function isAuthorized($user)
    // {
    //     return true;
    // }

    public function login()
    {
        $this->request->allowMethod(['get', 'post']);
        $result = $this->Authentication->getResult();

        // Check if the user is logged in successfully
        if ($result && $result->isValid()) {
            // Get authenticated user data
            $user = $result->getData();

            // Check if the user account is active
            if ($user['status_id'] == 1) {
                // Log successful login attempt
                $this->log('User ' . $user['email'] . ' logged in successfully.', 'info');

                // Redirect to home page or to the requested URL
                $redirect = $this->request->getQuery('redirect', [
                    'controller' => 'Home',
                    'action' => 'index',
                ]);

                return $this->redirect($redirect);
            } else {
                // Account is inactive or locked, display error
                $this->Flash->error(__('Account is not activated, Please activate your account'));
                return;
            }
        }

        // Handle failed login attempts
        if ($this->request->is('post')) {
            if (!$result->isValid()) {
                // Log failed login attempt
                $this->log('Failed login attempt for username: ' . $this->request->getData('username'), 'warning');

                // Show error message
                $this->Flash->error(__('Your username or password is incorrect.'));

                // Optionally, implement throttling or limit failed attempts
                // Example: check failed login count and lock the account after several attempts
                $this->handleFailedLogin($this->request->getData('username'));
            }
        }
    }

    /**
     * Handle actions after a failed login, like logging attempts or locking account.
     *
     * @param string $username
     */
    private function handleFailedLogin($username)
    {
        // You can implement logic to count failed login attempts
        // and lock the user account after multiple failures

        // Example:
        // $failedAttempts = $this->Users->getFailedLoginAttempts($username);
        // if ($failedAttempts >= 3) {
        //     $this->Users->lockAccount($username);
        //     $this->Flash->error(__('Your account is temporarily locked due to multiple failed login attempts.'));
        // }
    }

    public function logout()
    {
        $result = $this->Authentication->getResult();

        if ($result && $result->isValid()) {
            $this->Authentication->logout();
            $this->Flash->success('You are now logged out.');
            return $this->redirect(['controller' => 'Users', 'action' => 'login']);
        } else {
            $this->Flash->info('You are not logged in.');
            return $this->redirect(['controller' => 'Users', 'action' => 'login']);
        }
    }




}
