<?php
declare(strict_types=1);

namespace App\Controller;

use Cake\Datasource\Exception\RecordNotFoundException;

/**
 * Users Controller
 *
 * @property \App\Model\Table\UsersTable $Users
 */
class UsersController extends AppController
{
    public function initialize(): void
    {
        parent::initialize();
        $this->loadComponent('Flash');
    }

    private function requireLoginAndAdminPassword()
    {
        $session = $this->request->getSession();
        $user = $session->read('Auth.User');

        if (empty($user)) {
            $this->Flash->error('You must be logged in to access this page.');
            return $this->redirect(['controller' => 'Auth', 'action' => 'login']);
        }

        if (!$session->read('Auth.AdminVerified')) {
            return $this->redirect(['action' => 'adminVerify']);
        }

        return null;
    }

    public function adminVerify()
    {
        $session = $this->request->getSession();
        $user = $session->read('Auth.User');

        if (empty($user)) {
            $this->Flash->error('You must be logged in to verify.');
            return $this->redirect(['controller' => 'Auth', 'action' => 'login']);
        }

        if ($this->request->is('post')) {
            $password = $this->request->getData('password');

            if (!empty($password)) {
                $hashedAdminPassword = '$2y$10$umVouBoKco2Jx7.tA0pDQu00NRkRee8Ak2o.vBCgsuk4mY.QYrQAm'; // "Admin123"

                if (password_verify($password, $hashedAdminPassword)) {
                    $session->write('Auth.AdminVerified', true);
                    $this->Flash->success('Admin access verified.');
                    return $this->redirect(['action' => 'index']);
                } else {
                    $this->Flash->error('Incorrect admin password.');
                }
            } else {
                $this->Flash->error('Please enter the admin password.');
            }
        }
    }

    public function index()
    {
        $redirect = $this->requireLoginAndAdminPassword();
        if ($redirect) return $redirect;

        $query = $this->Users->find();
        $users = $this->paginate($query);

        $this->set(compact('users'));
    }

    public function view($id = null)
    {
        $redirect = $this->requireLoginAndAdminPassword();
        if ($redirect) return $redirect;

        if (!is_numeric($id)) {
            $this->Flash->error('Invalid user ID.');
            return $this->redirect(['action' => 'index']);
        }

        try {
            $user = $this->Users->get((int)$id);
            $this->set(compact('user'));
        } catch (RecordNotFoundException $e) {
            $this->Flash->error('User not found.');
            return $this->redirect(['action' => 'index']);
        }
    }

    public function add()
    {
        $redirect = $this->requireLoginAndAdminPassword();
        if ($redirect) return $redirect;

        $user = $this->Users->newEmptyEntity();

        if ($this->request->is('post')) {
            // Get form data
            $data = $this->request->getData();

            // Check if a password is provided
            if (!empty($data['password'])) {
                // Hash the password using password_hash() before saving
                $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
            }

            // Patch user entity with form data
            $user = $this->Users->patchEntity($user, $data);

            // Check for validation errors
            if ($user->getErrors()) {
                $this->Flash->error(__('There were validation errors. Please, check the form.'));
            }

            // Save user data to the database
            if ($this->Users->save($user)) {
                $this->Flash->success(__('The user has been saved.'));
                return $this->redirect(['action' => 'index']);
            } else {
                $this->Flash->error(__('The user could not be saved. Please, try again.'));
            }
        }

        $this->set(compact('user'));
    }

    public function edit($id = null)
    {
        $redirect = $this->requireLoginAndAdminPassword();
        if ($redirect) return $redirect;

        if (!is_numeric($id)) {
            $this->Flash->error('Invalid user ID.');
            return $this->redirect(['action' => 'index']);
        }

        try {
            $user = $this->Users->get((int)$id);
        } catch (RecordNotFoundException $e) {
            $this->Flash->error('User not found.');
            return $this->redirect(['action' => 'index']);
        }

        if ($this->request->is(['patch', 'post', 'put'])) {
            // Get form data
            $data = $this->request->getData();

            // Check if password is provided
            if (!empty($data['password'])) {
                // Hash the new password using password_hash() before saving
                $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
            } else {
                // If no new password is provided, unset it to avoid overwriting the existing password
                unset($data['password']);
            }

            // Patch user entity with form data
            $user = $this->Users->patchEntity($user, $data);

            // Save user data to the database
            if ($this->Users->save($user)) {
                $this->Flash->success(__('The user has been saved.'));
                return $this->redirect(['action' => 'index']);
            } else {
                $this->Flash->error(__('The user could not be saved. Please, try again.'));
            }
        }

        $this->set(compact('user'));
    }

    public function delete($id = null)
    {
        $redirect = $this->requireLoginAndAdminPassword();
        if ($redirect) return $redirect;

        $this->request->allowMethod(['post', 'delete']);

        if (!is_numeric($id)) {
            $this->Flash->error('Invalid user ID.');
            return $this->redirect(['action' => 'index']);
        }

        try {
            $user = $this->Users->get((int)$id);
        } catch (RecordNotFoundException $e) {
            $this->Flash->error('User not found.');
            return $this->redirect(['action' => 'index']);
        }

        if ($this->Users->delete($user)) {
            $this->Flash->success(__('The user has been deleted.'));
        } else {
            $this->Flash->error(__('The user could not be deleted. Please, try again.'));
        }

        return $this->redirect(['action' => 'index']);
    }
}
