<?php

/**
 * Description of MY_Form_validation
 *
 * @author cvillegas
 */
class MY_Form_validation extends CI_Form_validation {

    public function __construct($config = array()) {
        parent::__construct($config);
    }

    /**
     * Valid Date
     *
     * Verify that the date value provided can be converted to a valid unix timestamp
     *
     * @param string  $str
     * @return    bool
     */
    public function date($str) {
        if (($str = strtotime($str)) === FALSE) {
            $this->CI->form_validation->set_message('date', '{field} debe ser una fecha valida.');
            return FALSE;
        }
        return TRUE;
    }

    /**
     * time
     *
     * Check if the input value is time in the format HH:MM:SS
     *
     *
     * @param	string	$time
     * @return	bool
     */
    public function time($time) {
        $valido = false;
        if (is_string($time)) {
            if (preg_match("/^[[:digit:]]{2}:[[:digit:]]{2}:[[:digit:]]{2}/", $time)) {
                $hora = explode(':', $time);
                if ($this->checktime($hora[0], $hora[1], $hora[2])) {
                    $valido = true;
                }
            } else {
                if (preg_match("/^[[:digit:]]{2}:[[:digit:]]{2}/", $time)) {
                    $hora = explode(':', $time);
                    if ($this->checktime($hora[0], $hora[1])) {
                        $valido = true;
                    }
                }
            }
        }
        $this->CI->form_validation->set_message('time', '{field} debe ser un horario valido.');
        return $valido;
    }

    /**
     * datetime
     *
     * Check if the input value is datetime in the format Y-m-d HH:MM:SS
     *
     *
     * @param	string	$datetime
     * @return	bool
     */
    public function datetime($datetime) {
        $valido = (DateTime::createFromFormat('Y-m-d H:i:s', $datetime) !== FALSE || DateTime::createFromFormat('Y-m-d H:i', $datetime) !== FALSE);
        $this->CI->form_validation->set_message('datetime', '{field} debe ser una fecha y horario validos.');
        return $valido;
    }

    /**
     * checktime
     *
     * cheque si el input tiene formato de hora para MySQL HH:mm:ss
     *
     *
     * @param	string	$str
     * @return	bool
     */
    private function checktime($hour, $min, $sec = 0) {
        if ($hour < 0 || $hour > 23 || !is_numeric($hour)) {
            return false;
        }
        if ($min < 0 || $min > 59 || !is_numeric($min)) {
            return false;
        }
        if ($sec < 0 || $sec > 59 || !is_numeric($sec)) {
            return false;
        }
        return true;
    }

}
