<?php

if (!defined('ABSPATH'))
    exit;

/**
 * Class NF_Action_Square_Payment
 */
final class NF_Actions_SquarePayment extends NF_Abstracts_Action {

    /**
     * @var string
     */
    protected $_name = 'squarepayment';

    /**
     * @var array
     */
    protected $_tags = array(

    );

    /**
     * @var string
     */
    protected $_timing = 'early';

    /**
     * @var int
     */
    protected $_priority = 10;

    /**
     * Constructor
     */
    public function __construct() {
        
        parent::__construct();
        $this->_nicename = __('Square Payment ', 'ninja-square');
        $settings = $this->config('ActionSquarePaymentSettings');
        $setting_one =  $this->get_ninja_forms_get_fields();
        $new_setting = array_merge( $settings ,$setting_one );
        $this->_settings = array_merge(  $this->_settings, $new_setting);
        add_filter('ninja_forms_action_email_message',array($this,'custom_ninja_forms_action_email_message'),99,3);
    }


    /**
     * @param $form_data array
     * @return void
     */


    public function get_ninja_forms_get_fields() {

        $field_results = array();
        if(!empty($_GET['form_id'])) {

            $fields = Ninja_Forms()->form($_GET['form_id'])->get_fields();

           $field_results['form_id'] = array(
                'name' => 'form_id',
                'type' => 'toggle',
                'group' => 'primary',
                'label' => __('Form ID ', 'ninja-square'),
                'width' => 'full',
                'value' => '',
            );


            foreach ($fields as $field) {

                if ($field->get_setting('label_pos') == 'default') {
                    $field_results[$field->get_setting('type')] = array(
                        'name' => $field->get_setting('type'),
                        'type' => 'toggle',
                        'group' => 'primary',
                        'label' => __($field->get_setting('label'), 'ninja-square'),
                        'label_post' => 'inside',
                        'width' => 'full',
                        'value' => '',
                    );
                }
            }
            $field_results['notice'] = array(
                'name' => 'notice',
                'type' => 'html',
                'group' => 'primary',
                'width' => 'full',
                'value' => '<div style="padding: 20px 0;"><strong>Notice</strong>: There is a limit of 500 characters for transaction notes in Square API,<br> so if you exceed this limit it will automatically ignore.</div>'
            );

        }

        return $field_results;
    }

    /*
     * PUBLIC METHODS
     */

    public function save($action_settings) {

    }
    public function custom_ninja_forms_action_email_message($message, $data, $action_settings) {
        $default_ninja_mail_error_status = get_option('default_ninja_mail_error_status');
        $note = '';
         foreach ($data['fields'] as $field) {

            foreach($field as $key => $type){
                if (@$action_settings['type'] == 'squarepayment' && !empty($type['value'])) {
                    
                    $note = $type['label'] . '-' . $type['value'] . ".  ";
                }
            }

            if ($field['type'] == 'squareform') {

                $nonce = $field['value'];
                $form_type = 'squareform';
                $id = $field['id'];
                // $ninja_mail_error = get_post_meta($this->get_sub_id($data),'_field_'.$id);
                $transactionData = get_transient( 'sq_data_'.$id);
                
                if (isset($transactionData['payment']['id'])) {
                    $this->update_submission($this->get_sub_id($data), array(
                        'square_transaction_id' => $transactionData['payment']['id']
                    ));
                    Ninja_Forms()->merge_tags['square']->set('transaction_id', $transactionData['payment']['id']);
                }
                
            }
                
        }
                
      
        return $message;
    }

    public function process($action_settings, $form_id, $data) {

          
        global $wpdb;
        $app_id = "";
        $token = "";
        $location_id = "";
        $form_type = "";
        $form_type = "";
        $note = '';


        if($action_settings['form_id'] == 1){
            $note .= 'Form ID'.'-'. $form_id . ".  ";
        }

        foreach ($data['fields'] as $field) {

            foreach($field as $key => $type){
            
            if (@$action_settings['type'] == 'squarepayment' && !empty($type['value'])) {
                    $nonce = $field['value'];
                    $note .= $type['label'] . '-' . $type['value'] . ".  ";
                }
            }

            if ($field['type'] == 'squareform') {
                // $nonce = $field['value'];
                $form_type = 'squareform';
                $id = $field['id'];
            }

        }
    
        $note=substr($note, 0, 500);


        if ($form_type == "squareform" && $nonce) {
            if(!empty($action_settings['square_price'])) {
                $amount = round($action_settings['square_price'], 2) * 100;
            }

            $currency = Ninja_Forms()->get_setting( 'currency' );
            try {
                $idempotencyKey = time();
                $options = get_option('square_setting_options');
                $mode_type = $options['square_setting_mode'];
                $api_config = new \SquareConnect\Configuration();

                if ($mode_type == 'Test') {

                    $app_id = $options['square_setting_test_app_id'];
                    $token = $options['square_setting_test_token'];
                    $location_id = $options['square_setting_test_location_id'];
                    $api_config->setHost("https://connect.squareupsandbox.com");


                }

                if ($mode_type == 'Live') {

                    $app_id = $options['square_setting_live_app_id'];
                    $token = $options['square_setting_live_token'];
                    $location_id = $options['square_setting_live_location_id'];
                    $api_config->setHost("https://connect.squareup.com");

                }


                $api_config->setAccessToken($token);
                $api_client = new \SquareConnect\ApiClient($api_config);
                $payments_api = new \SquareConnect\Api\PaymentsApi($api_client);
                $body = new \SquareConnect\Model\CreatePaymentRequest();
                $amountMoney = new \SquareConnect\Model\Money();
                $amountMoney->setAmount($amount);
                //$amountMoney->setCurrency("USD");
                $amountMoney->setCurrency($currency);
                $body->setSourceId($nonce);
                $body->setAmountMoney($amountMoney);
                $body->setLocationId($location_id);
                if(!empty($note)) {
                    $body->setNote($note);
                }
                $body->setIdempotencyKey((string) $idempotencyKey);

                $transaction = $payments_api->createPayment($body);

                $transactionData = json_decode($transaction, true);
                $sub_id = $this->get_sub_id($data);
                
                
                set_transient( 'sq_data_'.$id, $transactionData, 3000 );
                

            } catch (\SquareConnect\ApiException $e) {

                $errors = $e->getResponseBody()->errors;
                
                
                foreach ($errors as $error) {
                    $message = $error->detail;
                    if (isset($error->field))
                        $message = $error->field . ' - ' . $error->detail;
                    $data['errors']['form']['square'] = $message;
                }
                
                if($errors[0]){
                    $sub_id = $this->get_sub_id($data);
                    set_transient( 'sq_data_'.$sub_id, $data, 3000 );
                    $ninja_mail_error =  get_post_meta($sub_id,'_field_'.$id);
                }
                if ( !empty ($message) ) {
                        $this->update_submission($this->get_sub_id($data), array(
                            'square_error' => $message
                        ));
                        Ninja_Forms()->merge_tags['square']->set('square_error_message', $message);
                    }
                
                

            }
        }
        return $data;
    }

    private function update_submission($sub_id, $data = array()) {
        if (!$sub_id)
            return;

        $sub = Ninja_Forms()->form()->sub($sub_id)->get();

        foreach ($data as $key => $value) {
            $sub->update_extra_value($key, $value);
        }

        $sub->save();
    }

    private function get_sub_id($data) {
        if (isset($data['actions']['save']['sub_id'])) {
            return $data['actions']['save']['sub_id'];
        }
        return FALSE;
    }

    /**
     * Config
     *
     * @param $file_name
     * @return mixed
     */
    function config($file_name) {
        return include NINJA_SQUARE_INTEGRATION_PATH . 'includes/config/' . $file_name . '.php';
    }

}

$obj = new NF_Actions_SquarePayment();


