<?php
namespace Formipay\Payment;
use Formipay\Traits\SingletonTrait;
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) exit;

abstract class Payment {

    use SingletonTrait;

    abstract public function add_gateway($gateways);
    abstract public function add_transaction($order_data);
    abstract public function process_payment($order_data);
    abstract public function cancel_payment($order_data);

    protected function __construct() {

        add_filter( 'formipay/global-settings',             [$this, 'add_setting_payment_menu'], 20 );
        add_filter( 'formipay/form-config',                 [$this, 'add_form_payment_menu'], 79 );

        add_filter( 'formipay/form-config/tab:payments',    [$this, 'add_responsive_grid'],         1012 );
        add_filter( 'formipay/frontend/payment-list',       [$this, 'add_payment_list'],            999, 2 );

        add_filter( 'formipay/order/shortcodes',            [$this, 'add_order_shortcodes'],        999, 4 );
        add_filter( 'formipay/thankyou/shortcodes',         [$this, 'add_order_shortcodes'],        999, 4 );
        add_filter( 'formipay/order/process-data',          [$this, 'add_payment_in_process_data'], 999, 2 );
        add_filter( 'formipay/order/payment-details',       [$this, 'render_payment_details'],      999, 4 );

        add_action( 'init',						            [$this, 'set_endpoint'], 999);
		add_filter( 'query_vars',				            [$this, 'set_query_vars'], 899);
        add_action( 'wp_enqueue_scripts',                   [$this, 'frontend_enqueue'] );
        add_filter( 'pre_get_document_title',               [$this, 'payment_confirm_page_title'], 1000 );

    }

    public function add_setting_payment_menu($fields){

        $general_payment_settings = array();

        $payment_settings = apply_filters( 'formipay/global-settings/tab:payment', $general_payment_settings );

        if(!empty($payment_settings)){
            $fields['payment'] = array(
                'name' => __('Payment', 'formipay'),
                'fields' => $payment_settings
            );
        }

        return $fields;

    }

    public function add_form_payment_menu($fields) {

        $payment_fields = [
            'payment_section_group' => array(
                'type' => 'group_title',
                'label' => __( 'Payment Section', 'formipay' ),
                'submenu' => __( 'General', 'formipay' ),
                'group' => 'started'
            ),
            'allowed_currencies' => array(
                'type' => 'multi_checkbox',
                'searchable' => true,
                'required' => true,
                'label' => __( 'Allowed Currencies', 'formipay' ),
                'options' => formipay_global_currency_options(),
                'submenu' => __( 'General', 'formipay' ),
                'description' => __( 'Activate multicurrency and set more than one currency to enable this option. Default, only default currency is allowed.', 'formipay' )
            ),
            'default_currencies' => array(
                'type' => 'select',
                'searchable' => true,
                'required' => true,
                'label' => __( 'Default Currency', 'formipay' ),
                'options' => formipay_global_currency_options(),
                'submenu' => __( 'General', 'formipay' ),
                'description' => __( 'First apply currency before buyer select.', 'formipay' )
            ),
            'payment_section_title' => array(
                'type' => 'text',
                'label' => __( 'Payment Section Title', 'formipay' ),
                'submenu' => __( 'General', 'formipay' ),
                'value' => 'Payment Methods',
            ),
            'payment_label' => array(
                'type' => 'checkbox',
                'label' => __( 'Show Payment Label', 'formipay' ),
                'description' => __( 'Show payment label in the payment options on the frontend.', 'formipay' ),
                'submenu' => __( 'General', 'formipay' ),
                'group' => 'ended'
            )
        ];

        $payment_fields = apply_filters( 'formipay/form-config/tab:payments', $payment_fields );

        $fields['formipay_form_settings']['payments'] = array(
            'name'      => __( 'Payments', 'formipay' ),
            'fields'    => $payment_fields
        );

        return $fields;
        
    }

    public function add_responsive_grid($channels) {
        $channels['payment_responsive_box'] = array(
            'type'  => 'group_title',
            'label' => __( 'Responsive', 'formipay' ),
            'description' => __( 'Set responsive grid payment card options' , 'formipay' ),
            'submenu' => __( 'General', 'formipay' ),
            'group' => 'started',
        );

        $channels['payment_desktop_columns'] = array(
            'type' => 'number',
            'label' => __( 'Desktop View', 'formipay' ),
            'submenu' => __( 'General', 'formipay' ),
            'value' => 4
        );

        $channels['payment_tablet_columns'] = array(
            'type' => 'number',
            'label' => __( 'Tablet View', 'formipay' ),
            'submenu' => __( 'General', 'formipay' ),
            'value' => 3
        );

        $channels['payment_mobile_columns'] = array(
            'type' => 'number',
            'label' => __( 'Mobile View', 'formipay' ),
            'submenu' => __( 'General', 'formipay' ),
            'value' => 2,
            'group' => 'ended'
        );

        return $channels;
    }

    public function add_payment_list($payment_list, $form_id) {

        $formipay_settings = get_option('formipay_settings');

        $payment_gateways = json_decode(formipay_get_post_meta($form_id, 'payment_gateways'), true);
        foreach($payment_gateways as $payment){
            if($payment['id'] == 'active' && !empty($payment['options'])){
                foreach($payment['options'] as $option){
                    $id = $option['id'];
                    $_pay = explode(':::', $id);
                    $gateway = $_pay[0];
                    if(formipay_get_post_meta($form_id, 'product_type') == 'digital' && $gateway == 'cod'){
                        continue;
                    }
                    if(isset($formipay_settings[$gateway.'_channels']) && isset($_pay[1])){
                        $channel = $_pay[1];
                        if(strpos($channel, '-')){
                            $channel = explode('-', $channel);
                            $channel_index = $channel[1];
                            $payment_list[$id] = $formipay_settings[$gateway.'_channels'][$channel_index];
                        }
                    }else{
                        $label = $icon = '';
                        if(isset($formipay_settings[$gateway.'_label']) && !empty($formipay_settings[$gateway.'_label'])){
                            $label = $formipay_settings[$gateway.'_label'];
                        }
                        if(isset($formipay_settings[$gateway.'_icon']) && !empty($formipay_settings[$gateway.'_icon'])){
                            $icon = $formipay_settings[$gateway.'_icon'];
                        }
                        $payment_list[$id] = array(
                            $gateway.'_name' => apply_filters( 'formipay/payment-list/'.$gateway.'/label', $label),
                            $gateway.'_logo' => apply_filters( 'formipay/payment-list/'.$gateway.'/logo', $icon)
                        );
                    }
                }
            }
        }

        return $payment_list;

    }

    public function add_order_shortcodes($shortcodes, $form_id, $order_data, $submit_action_type) {

        $shortcodes['payment_details'] = apply_filters( 'formipay/order/payment-details', '', $form_id, $order_data, $submit_action_type );

        return $shortcodes;

    }

    public function render_payment_details($render, $form_id, $order_data, $submit_action_type) {

        $payment_gateway = $order_data['payment_gateway'];

        $render = apply_filters( 'formipay/order/payment-details/'.$payment_gateway, $render, $form_id, $order_data, $submit_action_type );
        
        ob_start();
        echo wp_kses($render, formipay_thankyoupage_allowed_html());
        $content = ob_get_contents();
        ob_get_clean();

        return $content;

    }

    public function add_payment_in_process_data($order_data, $form_id) {

        $payment = explode(':::', $order_data['payment']);
        $payment_gateway = $payment[0];
        $order_data['payment_gateway'] = $payment_gateway;

        return $order_data;

    }

    public function set_endpoint() {

		add_rewrite_rule( 
            '^payment-confirm/([^/]*)/([^/]*)/?',
            'index.php?formipay-payment-confirm=1&gateway=$matches[1]&formipay-token=$matches[2]',
            'top'
        );

        flush_rewrite_rules();
        
    }

    public function set_query_vars($vars){

        $vars[] = 'formipay-payment-confirm';
        $vars[] = 'gateway';
        $vars[] = 'formipay-token';
        return $vars;

    }

    public function frontend_enqueue() {

        global $wp_query;

        if(
			is_array($wp_query->query) &&
			array_key_exists('formipay-payment-confirm', $wp_query->query) &&
            true === boolval($wp_query->query['formipay-payment-confirm'])
        ) :

            wp_enqueue_style( 'formipay-payment-confirm', FORMIPAY_URL . 'public/assets/css/payment-confirm.css', [], FORMIPAY_VERSION, 'all' );
            wp_enqueue_script( 'formipay-payment-confirm', FORMIPAY_URL . 'public/assets/js/payment-confirm.js', ['jquery'], FORMIPAY_VERSION, true );

        endif;

    }

    public function payment_confirm_page_title($title) {
        global $wp_query;

        if(
			is_array($wp_query->query) &&
			array_key_exists('formipay-payment-confirm', $wp_query->query) &&
            true === boolval($wp_query->query['formipay-payment-confirm'])
        ) :
            
            $gateway = $wp_query->query['gateway'];
            $gateway = strlen($gateway) > 3 ? ucwords( str_replace('_', ' ', $gateway) ) : strtoupper($gateway);

            $title = $gateway . ' Confirmation' . ' - ' . get_bloginfo('name');

        endif;

        return $title;

    }
    
}