<?php

namespace App\Models;

use App\Libraries\HashLibrary;
use App\Libraries\SendEmail;
use Carbon\Carbon;
use CodeIgniter\Model;
use Config\Services;

class UserModel extends Model
{
    protected $table            = 'tbl_user';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $protectFields    = true;
    protected $allowedFields    = [
        'first_name',
        'last_name',
        'email',
        'password',
        'role',
        'status',
    ];

    protected bool $allowEmptyInserts = false;
    protected bool $updateOnlyChanged = true;

    protected array $casts = [];
    protected array $castHandlers = [];

    // Dates
    protected $useTimestamps = true;
    protected $dateFormat    = 'datetime';
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $deletedField  = 'deleted_at';

    // Validation
    protected $validationRules      = [];
    protected $validationMessages   = [];
    protected $skipValidation       = false;
    protected $cleanValidationRules = true;

    // Callbacks
    protected $allowCallbacks = true;
    protected $beforeInsert   = [];
    protected $afterInsert    = ['sendVerificationEmail'];
    protected $beforeUpdate   = [];
    protected $afterUpdate    = [];
    protected $beforeFind     = [];
    protected $afterFind      = [];
    protected $beforeDelete   = [];
    protected $afterDelete    = [];

    public function getUsers($limit = null)
    {
        return $this->db->table($this->table)
            ->orderBy('created_at', 'desc')
            ->get()
            ->getResultObject();
    }
    public function getUser($id)
    {
        return $this->db->table($this->table)
            ->getWhere(['id' => (int)$id])
            ->getFirstRow();
    }
    protected function sendVerificationEmail($data)
    {
        //sendEmail($data);
        $token = HashLibrary::generateToken();
        $email = $data['data']['email'];
        $model = model('TokenModel');

        $old_token = $model->asObject()
            ->where('email', $email)->first();
        if ($old_token) {
            try {
                $model->where('email', $email)
                    ->set([
                        'token' => $token,
                        'created_at' => Carbon::now(),
                    ])->update();
            } catch (\ReflectionException $e) {
                return false;
            }
        } else {
            try {
                $model->insert([
                    'token' => $token,
                    'email' => $email,
                    'created_at' => Carbon::now(),
                ]);
            } catch (\ReflectionException $e) {
                return false;
            }
        }

        $link = url_to('set_password', $token);
        $mail_data = [
            'link' => $link,
            'name' => join(' ', [$data['data']['first_name'], $data['data']['last_name']]),
        ];
        $view = Services::renderer();

        $mail_body = $view->setVar('mail_data', $mail_data)
            ->render('templates/verification-email-template');

        SendEmail::send($email, $mail_body, 'Email Verification - ' . APP_NAME);

        return $data;
    }
}
