<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

class form_hash
{
    private $CI;
    public $time_point = 3; // default - count of seconds

    public function __construct()
    {
        if (!isset($this->CI)) {
            $this->CI = &get_instance();
        }
    }

    /**
     * Set time point
     *
     * @param int $time_point
     * @return Callme_hash
     */
    public function set_time_point($time_point)
    {
        $this->time_point = (int) $time_point;

        return $this;
    }

    /**
     * Set in form hidden field with hash. Also set hash in session.
     *
     * @return string
     */
    public function set_form_hash()
    {
        return '<input type="hidden" name="hash" value="'.$this->create_hash().'" />';
    }

    /**
     * Check hash from form
     *
     * @return bolean
     */
    public function check_form_hash()
    {
        $post_hash = $this->CI->input->post('hash');
        if (!empty($post_hash)) {
            $data_hash = $this->CI->session->userdata('form_hash');
            foreach ($data_hash as $hash => $time) {
                if ($post_hash == $hash && $this->check_time_point($time)) {
                    //unset hash
                    unset($data_hash[$hash]);
                    $this->CI->session->set_userdata('form_hash', $data_hash);

                    return true;
                }
            }
        }

        return false;
    }

    /**
     * Check time to filing form
     *
     * @param string $time
     * @return bolean
     */
    protected function check_time_point($time)
    {
        return date('H:i:s', strtotime('-'.$this->time_point.' seconds', strtotime(date('H:i:s')))) >= $time;
    }

    /**
     * Create new hash
     *
     * @return string
     */
    protected function create_hash()
    {
        // create hash
        $hash = substr(md5(md5(microtime()).$this->CI->config->item('encryption_key')), 0, 15);

        $data = $this->CI->session->userdata('form_hash');
        if (!is_array($data)) {
            $data = [];
        }

        // push new hash
        $data[$hash] = date('H:i:s');

        $this->CI->session->set_userdata('form_hash', $data);

        return $hash;
    }
}
