<?php

class WPAdverts_CF_Field_Date {
    
    /**
     * Class constructor
     * 
     * Registers init action
     * 
     * @since 1.0
     * @return self
     */
    public function __construct() {
        add_action( "init", array( $this, "init" ), 5 );
        $this->init();
        
        wp_register_script(
            "wpadverts-cf-datepicker",
            dirname( ADVERTS_URL ) . "/wpadverts-custom-fields/assets/js/datepicker.js",
            array( "jquery", "jquery-ui-datepicker" ),
            "1.0.1",
            true  
        );
        
        
        wp_register_style(
            'wpadverts-cf-datepicker', 
            dirname( ADVERTS_URL ) . "/wpadverts-custom-fields/assets/css/jquery-ui-date-picker.css",
            array(),
            "1.0"
        );
        
        add_filter( "wpadverts_cf_editor_fields", array( $this, "editor_fields"), 10, 3 );
    }
    
    public function editor_fields( $fields, $data, $form ) {
        
        if( $form["name"] == "advert" ) {
            $fields[] = $this->_editor_advert();
        } else if( $form["name"] == "search" ) {
            $fields[] = $this->_editor_search();
        } else if( $form["name"] == "author_profile") {
            $fields[] = $this->_editor_advert();
        } else if( $form["name"] == "contact" ) {
            $fields[] = $this->_editor_contact();
        } else if( $form["name"] == "author_search" ) {
            $fields[] = $this->_editor_search();
        } else if( $form["name"] == "author_contact" ) {
            $fields[] = $this->_editor_contact();
        }
        return $fields;
    }
    
    protected function _editor_advert() {
        return array(
            "type" => "adverts_cf_field_date",
            "template_id" => "cf-visual-adverts_cf_field_date",
            "callback_template" => array( $this, "field_visual" ),
            "label" => __( "Date & Time", "wpadverts-custom-fields" ),
            "config" => array(
                array(
                    "name" => "_header_common",
                    "callback_template" => "wpadverts_custom_fields_option_header",
                    "label" => __( "Common Settings", "wpadverts-custom-fields" )
                ),
                array(
                    "name" => "name",
                    "callback_template" => "wpadverts_custom_fields_option_name",
                    "callback_js" => "wpadverts_custom_fields_js_name",
                ),
                array(
                    "name" => "label",
                    "callback_template" => "wpadverts_custom_fields_option_label",
                    "callback_js" => "wpadverts_custom_fields_js_label"
                ),
                array(
                    "name" => "is_required",
                    "callback_template" => "wpadverts_custom_fields_option_is_required",
                    "callback_js" => "wpadverts_custom_fields_js_is_required"
                ),
                array(
                    "name" => "class",
                    "callback_template" => "wpadverts_custom_fields_option_class",
                    "callback_js" => "wpadverts_custom_fields_js_class"
                ),
                array(
                    "name" => "_header_specific",
                    "callback_template" => "wpadverts_custom_fields_option_header",
                    "label" => __( "Field Specific Settings", "wpadverts-custom-fields" )
                ),
                array(
                    "name" => "date",
                    "callback_template" => array( $this, "field_specific_html" ),
                    "callback_js" => array( $this, "field_specific_js" )
                ),
                array(
                    "name" => "_header_display",
                    "callback_template" => "wpadverts_custom_fields_option_header",
                    "label" => __( "Display Settings", "wpadverts-custom-fields" )
                ),
                array(
                    "name" => "display",
                    "callback_template" => "wpadverts_custom_fields_option_display",
                    "callback_js" => "wpadverts_custom_fields_js_display"
                ),
            )
        );
    }
    
    protected function _editor_search() {
        return array(
            "type" => "adverts_cf_field_date",
            "template_id" => "cf-visual-adverts_cf_field_date",
            "callback_template" => array( $this, "field_visual" ),
            "label" => __( "Date & Time", "wpadverts-custom-fields" ),
            "config" => array(
                array(
                    "name" => "_header_common",
                    "callback_template" => "wpadverts_custom_fields_option_header",
                    "label" => __( "Common Settings", "wpadverts-custom-fields" )
                ),
                array(
                    "name" => "name",
                    "callback_template" => "wpadverts_custom_fields_option_name",
                    "callback_js" => "wpadverts_custom_fields_js_name",
                ),
                array(
                    "name" => "label",
                    "callback_template" => "wpadverts_custom_fields_option_label",
                    "callback_js" => "wpadverts_custom_fields_js_label"
                ),
                array(
                    "name" => "_header_specific",
                    "callback_template" => "wpadverts_custom_fields_option_header",
                    "label" => __( "Field Specific Settings", "wpadverts-custom-fields" )
                ),
                array(
                    "name" => "date",
                    "callback_template" => array( $this, "field_specific_html" ),
                    "callback_js" => array( $this, "field_specific_js" )
                ),
                array(
                    "name" => "search_type",
                    "callback_template" => "wpadverts_custom_fields_option_search_type",
                    "callback_js" => "wpadverts_custom_fields_js_search_type"
                ),
                array(
                    "name" => "_header_search",
                    "callback_template" => "wpadverts_custom_fields_option_header",
                    "label" => __( "Search", "wpadverts-custom-fields" )
                ),
                array(
                    "name" => "cf_search_field",
                    "callback_template" => "wpadverts_custom_fields_option_cf_search_field",
                    "callback_js" => "wpadverts_custom_fields_js_cf_search_field"
                ),
            )
        );
    }
    
    protected function _editor_contact() {
        return array(
            "type" => "adverts_cf_field_date",
            "template_id" => "cf-visual-adverts_cf_field_date",
            "callback_template" => array( $this, "field_visual" ),
            "label" => __( "Date & Time", "wpadverts-custom-fields" ),
            "config" => array(
                array(
                    "name" => "_header_common",
                    "callback_template" => "wpadverts_custom_fields_option_header",
                    "label" => __( "Common Settings", "wpadverts-custom-fields" )
                ),
                array(
                    "name" => "name",
                    "callback_template" => "wpadverts_custom_fields_option_name",
                    "callback_js" => "wpadverts_custom_fields_js_name",
                ),
                array(
                    "name" => "label",
                    "callback_template" => "wpadverts_custom_fields_option_label",
                    "callback_js" => "wpadverts_custom_fields_js_label"
                ),
                array(
                    "name" => "is_required",
                    "callback_template" => "wpadverts_custom_fields_option_is_required",
                    "callback_js" => "wpadverts_custom_fields_js_is_required"
                ),
                array(
                    "name" => "_header_specific",
                    "callback_template" => "wpadverts_custom_fields_option_header",
                    "label" => __( "Field Specific Settings", "wpadverts-custom-fields" )
                ),
                array(
                    "name" => "date",
                    "callback_template" => array( $this, "field_specific_html" ),
                    "callback_js" => array( $this, "field_specific_js" )
                ),
            )
        );
    }
    
    public function field_specific_html() {
        ?>
        <div class="wpacf-config-field">
            <label class="wpacf-config-label"><?php _e("Date Format", "wpadverts-custom-fields") ?></label>
            <div class="wpacf-config-input">
                <# var format_date = ( field.get("format", "date") == "" ? "YYYY-MM-DD" : field.get("format", "date") ) #>

                <?php foreach( wpadverts_custom_fields_get_date_formats() as $kdf => $df ): ?>
                <label style="display:block;line-height:1.6em">
                    <input type="radio" value="<?php echo esc_attr( $kdf ) ?>" name="format_date" {{ HTML.checked( format_date == "<?php echo esc_attr( $kdf ) ?>" ) }} />
                    <?php echo date( $df["php"] ) ?> &nbsp; <code><?php echo esc_html( $df["php"] ) ?></code>
                </label>
                <?php endforeach; ?>
                

            </div>
        </div>

        <div class="wpacf-config-field">
            <label class="wpacf-config-label"><?php _e("Time", "wpadverts-custom-fields") ?></label>
            <div class="wpacf-config-input">
                <label>
                    <input type="checkbox" value="HH:ii" name="format_time" {{ HTML.checked( field.get("format", "time") == "HH:ii" ) }} />
                    <?php _e( "Show 'hour' and 'minutes' inputs.", "wpadverts-custom-fields") ?>
                </label>

            </div>
        </div>

        <input type="hidden" name="format_db" value="Y-m-d H:i:s" />
        <input type="hidden" name="format_gmt" value="0" />

        <?php
    }
    
    public function field_specific_js($field) {
        ?>
        <script type="text/javascript">
        _WPADVERTS_CF_CALLBACK.<?php echo $field["type"] ?>.push(function(field, form) {
            field.format = {
                date: form.find("input[name=format_date]:checked").val(),
                time: form.find("input[name=format_time]").is(":checked") ? form.find("input[name=format_time]").val() : "none",
                db: form.find("input[name=format_db]").val(),
                gmt: form.find("input[name=format_gmt]").val()
            };
            return field;
        });
        </script>
        <?php
    }
    
    public function field_visual($field, $form, $post ) {
        ?>
        <script type="text/html" id="tmpl-cf-visual-adverts_cf_field_date">
            <# var field = new WPADVERTS.CF.Helper(data) #>
            <# var HTML = WPADVERTS.CF.HTML; #>
            <div class="inside wpacf-mode-visual">
                <div class="main wpacf-visual">
                    <span class="wpacf-visual-label">
                        <# if( data.label.length > 0 ) { #>
                            <span class="wpacf-visual-label-pad">{{ data.label }}</span>

                            <# if( field.hasValidator("is_required") ) { #>
                            <span class="wpacf-field-is-required">*</span>
                            <# } #>
                        <# } #>
                    </span>

                    <# var time_format = field.get("format", "time"); #>
                    
                    <div class="wpacf-visual-input-wrap" style="">
                        
                        <# if( time_format && time_format != "none" ) { #>
                        <div style="display: flex; width:100%">
                            <input type="text" name="{{ data.name }}" placeholder="{{ field.get("format", "date") }}" style="flex-grow:2;" />
                            <div style="flex-basis: 0; display: flex; flex-wrap: nowrap">
                                <input type="number" name="{{ data.name }}--hours" placeholder="00" style="width:50px" />
                                <span style="line-height: 30px">:</span>
                                <input type="number" name="{{ data.name }}--hours" placeholder="00" style="width:50px" />
                            </div>
                        </div>
                        <# } else { #>
                        <input type="text" name="{{ data.name }}" placeholder="{{ field.get("format", "date") }}" />
                        <# } #>
                    </div>

                    <div class="wpacf-visual-actions">
                        <a href="#" class="wpacf-action-edit button-primary"><span class="dashicons dashicons-edit"></span></a>
                        <a href="#" class="wpacf-action-trash button-secondary"><span class="dashicons dashicons-trash"></span></a>
                    </div>
                </div>
                <div class="main wpacf-config" style="display:none">
                    <form action="" method="get" class="wpacf-config-form">

                        <?php
                            foreach($field["config"] as $config) {
                                call_user_func( $config["callback_template"], $config, $form, $post );
                            }
                        ?>

                    </form>
                    <hr/>
                    <button class="button wpacf-action-update"><?php _e("Update", "wpadverts-custom-fields") ?></button>
                    <button class="button wpacf-action-cancel"><?php _e("Cancel", "wpadverts-custom-fields") ?></button>
                </div>
            </div>
        </script>
        <?php
    }
    
    public function get_date_formats() {
        return wpadverts_custom_fields_get_date_formats();
    }
    
    public function get_date_format( $format, $default = "YYYY-MM-DD" ) {
        
        $formats = $this->get_date_formats();
        if( isset( $formats[$format] ) ) {
            return $formats[$format];
        } else {
            return $formats[$default];
        }
    }
    
    /**
     * Init Action
     * 
     * Executed by "init" action registered in self::__construct()
     * 
     * @see init action
     * @see self::__construct()
     * 
     * @since 1.0
     * @return void
     */
    public function init() {
        // Register <input> <input> input
        adverts_form_add_field("adverts_cf_field_date", array(
            "renderer" => array( $this, "renderer" ),
            "callback_save" => array( $this, "save" ),
            "callback_bind" => array( $this, "bind" ),
        ));
        
        adverts_form_add_validator("cf_is_date", array(
            "callback" => array( $this, "is_date" ),
            "label" => __( "Is Date", "wpadverts-custom-fields" ),
            "params" => array(),
            "default_error" => __( "Provided date format is invalid.", "wpadverts" ),
            "validate_empty" => false
        ));
    }
    
    public function is_date( $value ) {
        
        $dt = DateTime::createFromFormat("Y-m-d H:i:s", $value);
        
        if($dt !== false && !array_sum($dt::getLastErrors()) ) {
            return true;
        } else {
            return "invalid";
        }
    }
    
    /**
     * Renderer for the fullname field
     * 
     * This function displays HTML for the fullname input field.
     * 
     * The renderer is registered in self::init()
     * 
     * @since 1.0
     * 
     * @param   array   $field      Field params
     * @return  void
     */
    public function renderer( $field = null ) {
        
        wp_enqueue_script('wpadverts-cf-datepicker');
        wp_enqueue_style('wpadverts-cf-datepicker');
        
        if( ! isset( $field["format"] ) ) {
            $field["format"] = array(
                "date" => "Y-m-d"
            );
        }
        
        $field["placeholder"] = $field["format"]["date"]; //$field["date_format"];
        $field["class"] = "wpadverts-cf-datepicker";
        
        if( ! isset( $field["attr"] ) || ! is_array( $field["attr"] ) ) {
            $field["attr"] = array();
        }
        
        // format value for displat in the frontend!
        $date = "";
        $hours = "";
        $minutes = "";
        
        list( $date, $hours, $minutes ) = $this->format_frontend( $field );
        
        $date_format = $this->get_date_format( $field["format"]["date"] );

        echo "<div class=\"wpadverts-cf-date-field\">";
        echo adverts_field_hidden(array(
            "name" => $field["name"],
            "class" => "wpadverts-cf-input-full",
            "value" => isset( $field["value"] ) ? $field["value"] : ""
        ));
        
        $field["attr"]["data-date-format"] = $date_format["js"];
        $field["name"] = $field["name"] . "--date";
        $field["class"] = "wpadverts-cf-input-date";
        $field["value"] = $date;
        
        
        echo adverts_field_text( apply_filters( "wpadverts_cf_field_date_args", $field ) );
        
        if( isset( $field["format"]["time"] ) && $field["format"]["time"] != "none" ) {
            echo "<div class=\"wpadverts-cf-input-time\">";
            echo "<span>&nbsp;</span>";
            adverts_field_text(array(
                "subtype" => "number",
                "name" => $field["name"] . "--hours",
                "class" => "wpadverts-cf-input-hours",
                "value" => $hours,
                "placeholder" => "00",
                "attr" => array( 
                    "min" => "0",
                    "max" => "23",
                    "step" => "1"
                )
            ));
            echo "<strong>&nbsp;:&nbsp;</strong>";
            adverts_field_text(array(
                "subtype" => "number",
                "name" => $field["name"] . "--minutes",
                "class" => "wpadverts-cf-input-minutes",
                "value" => $minutes,
                "placeholder" => "00",
                "attr" => array( 
                    "min" => "0",
                    "max" => "59",
                    "step" => "1"
                )
            ));
            echo "</div>";
        }
        
        echo "</div>";

    }
    
    /**
     * Binds fullname data in the form
     * 
     * This function is executed using adverts_form_bind filter registered in
     * self::init()
     * 
     * @see adverts_form_load filter
     * 
     * @since 1.0
     * 
     * @param   array   $field  Field scheme
     * @param   mixed   $value  Value submitted via form
     * @return  mixed           Updated value to match field requirements
     */
    public function bind( $field, $value ) {
        return adverts_bind_single($field, $value);
    }
    
    public function format_frontend( $field ) {
        
        if( ! isset( $field["value"] ) ) {
            return array( 0, 0, 0 );
        } else if( empty( $field["value"] ) ) {
            return array( $field["value"], 0, 0 );
        }

        $date = DateTime::createFromFormat( $field["format"]["db"], $field["value"] );
        
        if( $date === false ) {
            return array( $field["value"], 0, 0 );
        }
        
        $format = $this->get_date_format( $field["format"]["date"] );
        
        $result = array( $date->format( $format["php"] ), $date->format( "H" ), $date->format( "i" ) ); 
        
        return $result;
    }
    
    /**
     * Save function
     * 
     * Do nothing - we do not want to save form data in post meta fields. 
     * 
     * @since 1.0
     * 
     * @param int       $post_id    Post ID
     * @param string    $key        Meta key
     * @param string    $value      Meta value
     * @return void
     */
    public function save( $post_id, $key, $value ) {
        return adverts_save_single($post_id, $key, $value);
    }
}