<?php

/**
 * Abstract Integration Class from which all others should be done
 */

if( ! defined( 'ABSPATH' ) ) {
    return;
}

abstract class GA_Integration extends GiveASAP_WordPressSettings {
    /**
     * Active Indicator
     * @var boolean
     */
    public $active = false;

    /**
     * Integration Image
     * @var string
     */
    public $image = '';

    /**
     * Integration Title
     * @var string
     */
    public $title = '';

    /**
     * Integration Description
     * @var string
     */
    public $desc = '';

    /**
     * Used for displaying a documentation screen and button
     * If true, the method documentation() should be defined 
     * @var boolean
     */
    public $has_documentation = false;

     /**
     * Setting initial params
     */
    public function __construct() {
        add_action( 'integration_save_' . $this->settings_id, array( $this, 'save_settings' ) );
        add_action( 'integration_save_' . $this->settings_id, array( $this, 'save_integration' ) );
    }

     /**
     * Save if the button for this menu is submitted
     * @return void 
     */
    public function save_if_submit() {
        if( isset( $_POST[ $this->settings_id . '_save' ] ) ) {

            do_action( 'integration_save_' . $this->settings_id );
            do_action( 'integration_save', $_POST );
        }
    }

    /**
     * Setting Fields
     */
    public function set_fields() {
        $this->fields = apply_filters( 'integration_fields_' . $this->settings_id, array() );
    }

    public function get_fields() {
        if( ! $this->fields ) {
            $this->set_fields();
        }

        // Making sure the integraiton always have an active checkbox
        $this->fields = array_merge( 
            array( 'active' => array(
                'type' => 'checkbox',
                'name' => 'active',
                'title' =>  __( 'Activate this integration', 'giveasap' ),
                'default' => $this->is_active_integration() ? 1 : 0,
                'desc' => __( 'Check this option to activate this integration', 'giveasap' )
            )),
            $this->fields
        );

    }

    /**
     * Rendering fields 
     * @param  string $tab slug of tab
     * @return void  
     */
    public function render_fields( $tab = '' ) {

        if( ! $this->fields ) {
            $this->get_fields();
        }

        $loadColorPicker = false;
        $loadDatePicker = false;
        foreach ( $this->fields as $name => $field ) {

            $field = $this->get_field_with_defaults( $field );
            if( $field['type'] == 'color' ) {
                $loadColorPicker = true;
            }

            if( $field['type'] == 'datetime' ) {
                $loadDatePicker = true;
            }

            if( 'custom' === $field['type'] ) {
                if( $field['render'] ) {
                    $field_func = $field['render'];
                    unset( $field['render'] );
                    call_user_func( $field_func, $field );
                }
            } else {
                $this->{ 'render_' . $field['type'] }( $field );
            }
        }
        ?>
        <script type="text/javascript">

            jQuery(document).ready(function() {
                <?php if( $loadColorPicker ): ?>
                    jQuery('.color-picker').wpColorPicker();
                <?php endif; ?>
                <?php if( $loadDatePicker ) : ?>
                    jQuery('.datepicker').datepicker({
                        dateFormat : 'dd-mm-yy',
                    });
                <?php endif; ?>
            });

            </script>
        <?php
    }

    /**
     * Get the settings from the database
     * @return void 
     */
    public function init_settings() {
    
        $this->settings = (array) get_option( $this->settings_id );
        if( ! $this->fields ) {
            $this->get_fields();
        }

        foreach ( $this->fields as $name => $field ) {
            
            if( isset( $this->settings[ $name ] ) ) {
                $this->fields[ $name ]['default'] = $this->settings[ $name ];
            }   
            
        }

    }

    /**
     * Save settings from POST
     * @return [type] [description]
     */
    public function save_settings(){
         
        $this->posted_data = $_POST;

        if( empty( $this->settings ) ) {
            $this->init_settings();
        }

        foreach ( $this->fields as $name => $field ) {
             
                if( 'custom' === $field['type'] ) {
                    if( ! isset( $this->posted_data[ $name ] ) ) { continue; }
                    if( isset( $field['validate'] ) && '' !== $field['validate'] ) {
                        $func = $field['validate'];
                        $this->settings[ $name ] = call_user_func( $func, $this->posted_data[ $name ] );
                    } else {
                        $this->settings[ $name ] = $this->posted_data[ $name ];
                    }
                } else {
                    $this->settings[ $name ] = $this->{ 'validate_' . $field['type'] }( $name );
                }
             
        }
        update_option( $this->settings_id, $this->settings );   
    }

    /**
     * Update the Settings
     * @param  array $settings 
     * @return boolean           
     */
    public function update_settings( $settings ) {
        $bool = update_option( $this->settings_id, $settings );
        $this->settings = $settings;
        return $bool;
    }

    /**
     * Saving Active Integrations
     * @param  $_POST $data 
     * @return void       
     */
    public function save_integration() {
        $active_integrations = get_option( 'giveasap_active_integrations', array() );
        $data = $_POST;
        
        if( isset( $data['active'] ) ) {
            if( ! isset( $active_integrations[ $this->settings_id ] ) ) {
                $active_integrations[ $this->settings_id ] = get_class( $this );
                do_action( 'giveasap_' . $this->settings_id . '_integration_activated' );
            }
        } elseif( isset( $active_integrations[ $this->settings_id ] ) ) {

            unset( $active_integrations[ $this->settings_id ] );
            do_action( 'giveasap_' . $this->settings_id . '_integration_deactivated' );
        }
 
        update_option( 'giveasap_active_integrations', $active_integrations );
    }

	/**
	 * @return bool
	 */
    public function is_active_integration() {
	    $active_integrations = get_option( 'giveasap_active_integrations', array() );
        if ( isset( $active_integrations[ $this->settings_id ] ) ) {
            return true;
        }

        return false;
    }

    /**
     * Gets and option from the settings API, using defaults if necessary to prevent undefined notices.
     *
     * @param  string $key
     * @param  mixed  $empty_value
     * @return mixed  The value specified for the option or a default value for the option.
     */
    public function get_option( $key, $empty_value = null ) {
        if ( empty( $this->settings ) ) {
            $this->init_settings();
        }
        // Get option default if unset.
        if ( ! isset( $this->settings[ $key ] ) ) {
            $form_fields = $this->fields;
 
            if( isset( $form_fields[ $key ] ) ) {
            
                $this->settings[ $key ] = isset( $form_fields[ $key ]['default'] ) ? $form_fields[ $key ]['default'] : '';
            
            }
            
        }
        if ( ! is_null( $empty_value ) && empty( $this->settings[ $key ] ) && '' === $this->settings[ $key ] ) {
            $this->settings[ $key ] = $empty_value;
        }
        return $this->settings[ $key ];
    }

    /**
     * Buttons to be shown on the Integrations screen
     * @return void 
     */
    public function buttons( $integrations ) {

        if( ! isset( $integrations[ $this->settings_id ] ) ) {
                ?>
                    <button type="button" data-integration="<?php echo $this->settings_id; ?>" class="button button-primary button-integration-activate"><?php _e( 'Activate', 'givasap' ); ?></button>
                <?php
            } else {
                ?>
                    <button type="button" data-integration="<?php echo $this->settings_id; ?>" class="button button-default button-integration-deactivate"><?php _e( 'Deactivate', 'givasap' ); ?></button>
                <?php
            }
        ?>
        <div style="float:right;">
            <?php if( $this->has_documentation ) { ?>
                <a type="button" href="<?php echo admin_url( 'edit.php?post_type=giveasap&page=giveasap_integrations&integration=' . $this->settings_id . '&section=documentation' ); ?>" class="button button-secondary"><?php _e( 'Documentation', 'givasap' ); ?></a>
            <?php } ?>
            <a type="button" href="<?php echo admin_url( 'edit.php?post_type=giveasap&page=giveasap_integrations&integration=' . $this->settings_id ); ?>" class="button button-secondary"><?php _e( 'Settings', 'givasap' ); ?></a>
        </div>

        <?php
    }

    /**
     * Integration Documentation
     * @return void 
     */
    public function documentation() {

    }
}