<?php
declare(strict_types=1);

namespace App\Controller;

use Cake\Utility\Security; // ✅ Add this
use Cake\I18n\FrozenTime;
use Cake\Mailer\Mailer;
/**
 * Users Controller
 *
 * @property \App\Model\Table\UsersTable $Users
 */
class UsersController extends AppController
{
    public function forgotPassword()
    {
        if ($this->request->is('post')) {
            $email = $this->request->getData('email');
            $user = $this->Users->findByEmail($email)->first();

            if ($user) {
                $token = Security::hash(Security::randomBytes(32), 'sha256', true);
                $user->reset_token = $token;
                $user->reset_token_expires = FrozenTime::now()->addMinutes(30);

                if ($this->Users->save($user)) {
                    $mailer = new Mailer('default');
                    $mailer->setEmailFormat('both')
                        ->setTo($user->email)
                        ->setSubject('Reset your password')
                        ->setViewVars([
                            'first_name' => $user->first_name,
                            'last_name' => $user->last_name,
                            'email' => $user->email,
                            'nonce' => $token,
                        ])
                        ->viewBuilder()->setTemplate('reset_password');

                    $mailer->deliver();
                    $this->Flash->success('Please check your inbox (or spam folder) for a reset email.');
                    return $this->redirect(['action' => 'login']);
                }
            }

            $this->Flash->error('Email not found or failed to send.');
        }
    }



    public function beforeFilter(\Cake\Event\EventInterface $event)
    {
        parent::beforeFilter($event);

        $this->Authentication->allowUnauthenticated(['login','add','forgot', 'forgotPassword']);
        $this->loadComponent('Recaptcha.Recaptcha', [
            'enable' => true,     // true/false
            'sitekey' => '6LeG-v0qAAAAAGHvnPtDua3tNC31jEbHlfaGeweW', //if you don't have, get one: https://www.google.com/recaptcha/intro/index.html
            'secret' => '6LeG-v0qAAAAAI4yJleIr5MAXiMm35PL_lZNQiaE',
            'type' => 'image',  // image/audio
            'theme' => 'light', // light/dark
            'lang' => 'en', // default 'en'
            'size' => 'normal',  // normal/compact
            'callback' => null, // `callback` data attribute for the recaptcha div, default `null`
            'scriptBlock' => true // Value for `block` option for HtmlHelper::script() call
]);
    }

    /**
     * Initialize controller
     *
     * @return void
     */
    public function initialize(): void
    {
        parent::initialize();
        //$this->Authentication->allowUnauthenticated(['edit']);
        $this->loadComponent('Authentication.Authentication');
        $this->Authentication->allowUnauthenticated(['add']);
    }


    /**
     * Index method
     *
     * @return \Cake\Http\Response|null|void Renders view
     */
    public function index()
    {
        $query = $this->Users->find();
        $users = $this->paginate($query);

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

    /**
     * View method
     *
     * @param string|null $id User id.
     * @return \Cake\Http\Response|null|void Renders view
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function view($id = null)
    {
        $user = $this->Users->get($id, contain: []);
        $this->set(compact('user'));
    }

    /**
     * Add method
     *
     * @return \Cake\Http\Response|null|void Redirects on successful add, renders view otherwise.
     */
    public function add()
    {
        $user = $this->Users->newEmptyEntity();
        if ($this->request->is('post')) {
            $user = $this->Users->patchEntity($user, $this->request->getData());
            if ($this->Users->save($user)) {
                $this->Flash->success(__('The user has been saved.'));

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The user could not be saved. Please, try again.'));
        }
        $this->set(compact('user'));
    }

    /**
     * Edit method
     *
     * @param string|null $id User id.
     * @return \Cake\Http\Response|null|void Redirects on successful edit, renders view otherwise.
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function edit($id = null)
    {
        $user = $this->Users->get($id, contain: []);
        if ($this->request->is(['patch', 'post', 'put'])) {
            $user = $this->Users->patchEntity($user, $this->request->getData());
            if ($this->Users->save($user)) {
                $this->Flash->success(__('The user has been saved.'));

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The user could not be saved. Please, try again.'));
        }
        $this->set(compact('user'));
    }

    /**
     * Delete method
     *
     * @param string|null $id User id.
     * @return \Cake\Http\Response|null Redirects to index.
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function delete($id = null)
    {
        $this->request->allowMethod(['post', 'delete']);
        $user = $this->Users->get($id);
        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']);
    }

    /**
     * Login method
     *
     * @return \Cake\Http\Response|null|void Redirects on successful edit, renders view otherwise.
     * @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
     */
    public function login()
    {
        $result = $this->Authentication->getResult();
        // If the user is logged in send them away.
        if ($result && $result->isValid()) {
            $target = $this->Authentication->getLoginRedirect() ?? 'Messages/index';
            return $this->redirect($target);
        }
        if ($this->request->is('post')) {
            //$user = $this->Users->findByPassword($this->request->getData('password'))->first();
           //debug($user);  // Check if the user is being fetched correctly

            //debug($result);
            //echo 'Email: ' . $this->request->getData('email') . '<br>';
            //echo 'Password: ' . $this->request->getData('password') . '<br>';
            $this->Flash->error('Invalid username or password');
        }
    }
   // use Cake\Http\Exception\ForbiddenException;

    /*public function login(): void
    {
        // If already logged in, redirect
        if ($this->Authentication->getIdentity()) {
            $this->redirect(['controller' => 'Users', 'action' => 'index']);
        }

        // Handle login attempt
        if ($this->request->is('post')) {
            // Get the posted data
            $data = $this->request->getData();

            // Attempt to identify the user based on the provided email
            $user = $this->Users->findByEmail($data['email'])->first();

            if (!$user) {
                // User with the given email does not exist
                $this->Flash->error('Invalid email address. Please try again.');
                return;
            }

            // Check if the password matches
            if (!password_verify($data['password'], $user->password)) {
                // Password is incorrect
                $this->Flash->error('Invalid password. Please try again.');
                return;
            }

            // If email and password are correct, authenticate the user
            $this->Authentication->setIdentity($user);

            // Successful login, redirect to dashboard or home page
            $this->Flash->success('Login successful.');
            $this->redirect(['controller' => 'Users', 'action' => 'index']);
        }
    }*/

    /*public function login()
    {
        $result = $this->Authentication->getResult();
        // If the user is logged in send them away.
        if ($result && $result->isValid()) {
            $target = $this->Authentication->getLoginRedirect() ?? '/login';
            return $this->redirect($target);
        }
        if ($this->request->is('post')) {
            $this->Flash->error('Invalid username or password');
        }
    }*/


    public function logout()
    {
        $this->Authentication->logout();
        return $this->redirect(['controller' => 'Users', 'action' => 'login']);
    }
    public function forgot()
    {
        // If the form is submitted
        if ($this->request->is('post')) {
            // Your logic to send the password reset email (as described earlier)
        }
    }

}
