<?php

if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

class Captcha_tmodel extends \Ciext\Model\AbstractTableModel
{

    protected $table = 'captcha';
    protected $pkey = 'id_captcha';

    public function __construct()
    {
        parent::__construct();

        $this->load->config('callme/captcha');
        $this->attach($this->load->library('callme/listeners/unset_file_listener'));
    }

    public function new_captcha()
    {
        $this->load->helper('captcha');
        $captcha = create_captcha($this->config->item('captcha_config'));
        $data = [
            'captcha_time' => $captcha['time'],
            'ip_address'   => $this->input->ip_address(),
            'word'         => $captcha['word'],
            'filename'     => $captcha['filename'],
        ];

        return $this->add($data) > 0 ? $captcha : [];
    }

    public function check_captcha()
    {
        if ($this->input->post('captcha')) {
            $expiration = time() - $this->config->item('captcha_config')['expiration'];
            $files = $this->set_predicates(['captcha_time < ' => $expiration])->fetch_all();
            if (!empty($files)) {
                $this->delete(array_column($files, 'id_captcha'));
            }
            $query = $this->set_predicates([
                        'word'           => is_array($this->input->post('captcha')) ? '' : $this->input->post('captcha'),
                        'ip_address'     => $this->input->ip_address(),
                        'captcha_time >' => $expiration
                    ])->fetch_all();

            if (count($query) > 0) {
                $this->delete(array_column($query, 'id_captcha'));

                return true;
            }
        }

        return false;
    }

}
