<?php
declare(strict_types=1);

namespace App\Controller;

use App\Controller\AppController;
use Cake\ORM\TableRegistry;
use Cake\I18n\DateTime;
use Cake\Mailer\Mailer;

class AuthController extends AppController
{
    protected $Users;

    public function initialize(): void
    {
        parent::initialize();

        $this->Users = TableRegistry::getTableLocator()->get('Users');

        $this->loadComponent('Recaptcha.Recaptcha', [
            'enable'      => true,
            'sitekey'     => '6LenGxorAAAAAGNmZWr3PrIsNkuPXtVs24mHFOGt',
            'secret'      => '6LenGxorAAAAACExlCRgoqaYlAC3SG8oyVl0MEaF',
            'type'        => 'image',
            'theme'       => 'light',
            'lang'        => 'en',
            'size'        => 'normal',
            'scriptBlock' => true,
        ]);

        $this->loadComponent('Flash');
    }

    public function login()
    {
        if ($this->request->is('post')) {
            if (!$this->Recaptcha->verify()) {
                $this->Flash->error('Please complete the CAPTCHA.');
                return;
            }

            $email    = $this->request->getData('email');
            $password = $this->request->getData('password');
            $user     = $this->Users->findByEmail($email)->first();

            if ($user && password_verify($password, $user->password)) {
                $this->request->getSession()->write('Auth.User', $user);
                $this->Flash->success('You are now logged in.');
                if ((int)$user->is_admin === 1) {
                    return $this->redirect(['controller' => 'Admin', 'action' => 'dashboard']);
                }

                return $this->redirect('/contact-form');
            }

            $this->Flash->error('Invalid email or password.');
        }
    }

    public function logout()
    {
        $this->request->getSession()->destroy();
        $this->Flash->success('You have been logged out.');
        return $this->redirect('/');
    }

    public function register()
    {
        $user = $this->Users->newEmptyEntity();

        if ($this->request->is('post')) {
            $user = $this->Users->patchEntity($user, $this->request->getData(), [
                'fields' => ['email', 'password', 'password_confirm']
            ]);

            if ($this->Users->save($user)) {
                $this->Flash->success('Registration successful! You can now log in.');
                return $this->redirect(['action' => 'login']);
            }

            $this->Flash->error('Registration failed. Please fix the errors below.');
        }

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

    public function forgotPassword()
    {
        if ($this->request->is('post')) {
            $email = $this->request->getData('email');
            $user  = $this->Users->findByEmail($email)->first();

            if ($user) {
                $user->nonce        = bin2hex(random_bytes(32));
                $user->nonce_expiry = DateTime::now()->addHours(1);
                $this->Users->save($user);

                try {
                    $mailer = new Mailer('default');
                    $mailer->setTo($user->email)
                           ->setSubject('Reset your password')
                           ->setEmailFormat('text')
                           ->viewBuilder()->setTemplate('reset_password');
                    $mailer->setViewVars(['user' => $user]);
                    $mailer->deliver();

                    $this->log('Password reset email sent to ' . $user->email, 'debug');
                } catch (\Exception $e) {
                    $this->log('Email sending failed: ' . $e->getMessage(), 'error');
                    $this->Flash->error('We could not send the reset email. Please try again later.');
                    return;
                }
            }

            $this->Flash->success('An email with your link has been sent! Please check your inbox.');
        }
    }

    public function resetPassword($nonce = null)
    {
        $user = $this->Users->find()
            ->where([
                'nonce'           => $nonce,
                'nonce_expiry >=' => DateTime::now()
            ])
            ->first();

        if (!$user) {
            $this->Flash->error('Invalid or expired reset link.');
            return $this->redirect(['action' => 'login']);
        }

        if ($this->request->is(['post', 'put'])) {
            $user = $this->Users->patchEntity($user, $this->request->getData(), [
                'fields' => ['password', 'password_confirm']
            ]);
            $user->nonce        = null;
            $user->nonce_expiry = null;

            if ($this->Users->save($user)) {
                $this->Flash->success('Password has been updated.');
                return $this->redirect(['action' => 'login']);
            }

            $this->Flash->error('Could not reset password.');
        }

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

    public function testEmail()
    {
        try {
            $mailer = new Mailer('default');
            $mailer->setTo('test@u25s1019.iedev.org')
                   ->setSubject('PowerPro Internal Email Test')
                   ->setEmailFormat('text')
                   ->deliver('✅ This is a test sent to your internal iedev.org address.');

            echo "✅ Internal email sent successfully to test@u25s1019.iedev.org";
        } catch (\Exception $e) {
            echo '❌ Email failed: ' . $e->getMessage();
            $this->log('EMAIL TEST ERROR: ' . $e->getMessage(), 'error');
        }

        die();
    }
}
