<?php
    declare(strict_types=1);

    namespace Icing\Mailer;

    use Cake\Mailer\Mailer;
    use Cake\ORM\Exception\MissingTableClassException;
    use Cake\ORM\Locator\LocatorAwareTrait;
    use Cake\Routing\Router;
    use Icing\Model\Entity\User;
    use Icing\Model\Table\UsersTable;

    /**
     * Users mailer.
     * @property UsersTable $Users
     */
    class UsersMailer extends Mailer
    {

        use MailgunTrait;

        protected ?UsersTable $Users;

        /**
         * Mailer's name.
         *
         * @var string
         */
        public static string $name = 'Users';

        public function __construct($config = null)
        {
            parent::__construct($config);
            $table = $this->fetchTable('Icing.Users');
            if (!$table instanceof UsersTable) {
               throw new MissingTableClassException('Table for Alias Icing.Users not found');
            }
            $this->Users = $table;
        }

        public function passwordRecovery(User $user): void
        {
            $token = urlencode($this->Users->encryptResetToken($user->password_reset_token, $user->email));

            $url = Router::url(
                [
                    'controller' => 'Auth',
                    'action'     => 'passwordReset',
                    '?'          => [
                        'email' => $user->email,
                        'token' => $token
                    ]
                ],
                true
            );

            $this->setTo($user->email, $user->name)
                ->setSubject('Password Recovery')
                ->setEmailFormat('both')
                ->viewBuilder()
                ->setTemplate('Icing.Users/password_recovery')
                ->setVars(compact('user', 'url'));
        }
    }
