<?php

use Sipago\WooCommerce\SipagoCheckout\Controllers\ResponseSipagoController;
use Sipago\WooCommerce\SipagoCheckout\Controllers\WebhookSipagoController;

use Sipago\WooCommerce\SipagoCheckout\Controllers\ThankYouPageController;
use Sipago\WooCommerce\SipagoCheckout\Helpers\DatabaseTableInstaller;
use Sipago\WooCommerce\SipagoCheckout\Helpers\LogHandler;
use Sipago\WooCommerce\SipagoCheckout\Helpers\SessionMessageHelper;
use Sipago\WooCommerce\SipagoCheckout\Helpers\WordpressPluginVersion;
use Sipago\WooCommerce\SipagoCheckout\Models\Transaction;
use Sipago\WooCommerce\SipagoCheckout\ClientSipago\SipagoCheckoutRest;

if (!defined('ABSPATH')) {
    exit();
} // Exit if accessed directly

/**
 * The plugin bootstrap file.
 *
 * This file is read by WordPress to generate the plugin information in the plugin
 * admin area. This file also includes all of the dependencies used by the plugin,
 * registers the activation and deactivation functions, and defines a function
 * that starts the plugin.
 *
 * @wordpress-plugin
 * Plugin Name: Sipago
 * Plugin URI: https://www.sipago.coop/
 * Description: Recibe pagos en línea en tu WooCommerce a través de Sipago.
 * Version: 1.9.22.0
 * Author: SipagoDevelopers
 * Author URI: https://www.sipago.coop/
 * WC requires at least: 3.4.0
 * WC tested up to: 5.5.1
 */
add_action('plugins_loaded', 'woocommerce_sipago_rest_init', 0);

$sipagoPluginData = null;
//todo: Eliminar todos estos require y usar PSR-4 de composer
require_once plugin_dir_path(__FILE__).'vendor/autoload.php';
require_once plugin_dir_path(__FILE__).'libsipagopay/ConnectionSipagoCheck.php';
require_once plugin_dir_path(__FILE__).'libsipagopay/ReportGenerator.php';

register_activation_hook(__FILE__, 'sipago_pay_rest_on_sipagopay_rest_plugin_activation');
add_action('admin_init', 'on_sipago_rest_sipagopay_plugins_loaded');
add_action('wp_ajax_check_connection', 'ConnectionSipagoCheck::check');
add_action('wp_ajax_download_report', \Sipago\WooCommerce\ReportGenerator::class.'::download');
add_filter('woocommerce_payment_gateways', 'woocommerce_add_sipago_gateway');
add_action('woocommerce_before_cart', 'sipago_rest_before_cart');


add_action('admin_enqueue_scripts', function () {
    wp_enqueue_style('tbk-styles', plugins_url('/css/tbk.css', __FILE__), [], '1.1');
    wp_enqueue_style('tbk-font-awesome', plugins_url('/css/font-awesome/all.css', __FILE__));
    wp_enqueue_script('tbk-ajax-script', plugins_url('/js/admin.js', __FILE__), ['jquery']);
    wp_enqueue_script('tbk-thickbox', plugins_url('/js/swal.min.js', __FILE__));
    wp_localize_script('tbk-ajax-script', 'ajax_object', [
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce'    => wp_create_nonce('my-ajax-nonce'),
    ]);
});

add_filter('plugin_action_links_'.plugin_basename(__FILE__), 'sipago_pay_rest_add_rest_action_links');

add_action('init', function () {
    global $sipagoPluginData;

    try {
        $sipagoPluginData = get_plugin_data(__FILE__);
    } catch (Throwable $e) {
    }

    if (!headers_sent() && '' == session_id()) {
        session_start([
            'read_and_close' => true,
        ]);
    }
});

function woocommerce_sipago_rest_init()
{
    if (!class_exists('WC_Payment_Gateway')) {
        return;
    }


    /**
     * @property string icon
     * @property string  method_title
     * @property string title
     * @property string description
     * @property string id
     */
    class WC_Gateway_Sipago_Sipago_REST extends WC_Payment_Gateway
    {

        const WOOCOMMERCE_API_SLUG = 'wc_gateway_sipago_pay';
        private static $URL_FINAL;

        protected $plugin_url;
        protected $log;
        protected $config;

        public function __construct()
        {
            self::$URL_FINAL = home_url('/').'?wc-api=SipagoSipagoCheckoutThankYouPage';
            $this->enabled = true;
            $this->id = 'sipago_pay';
            $this->icon = plugin_dir_url(__FILE__).'images/app-icon.svg';
            $this->method_title = __('Sipago', 'sipago_pay');
            $this->title = 'Sipago Checkout';
            $this->description = 'Permite el pago de productos y/o servicios, con tarjetas de crédito, débito y prepago a través de Sipago Checkout';
            $this->method_description = 'Permite el pago de productos y/o servicios, con tarjetas de crédito, débito y prepago a través de Sipago Checkout';
            $this->plugin_url = plugins_url('/', __FILE__);
            $this->log = new LogHandler();

            $this->supports = [
                'products',
                'refunds',
            ];

            $this->config = [
                'MODO'                 => trim($this->get_option('sipago_pay_environment', 'LIVE')),
                'ECOMMERCE'            => 'woocommerce',
                'STATUS_AFTER_PAYMENT' => $this->get_option('sipagopay_rest_after_payment_order_status', null),
                'CLIENT_ID'              => $this->get_option('geopago_rest_client_id', null),
                /* NewFeature 24 may */
                'ONLY_1_TOTAL'              => $this->get_option('only1Total', null),
                'CLIENT_SECRECT'              => $this->get_option('geopago_rest_client_secret', null),
                'URL_SUCCESS'              => 'https://www.mitienda.com/success',
                'URL_FAILED'              => 'https://www.mitienda.com/failed'
            ];

   


            $this->init_form_fields();
            $this->init_settings();

            add_action('woocommerce_thankyou', [new ThankYouPageController($this->config), 'show'], 1);
            add_action('woocommerce_update_options_payment_gateways_'.$this->id, [$this, 'process_admin_options']);
            add_action('woocommerce_api_wc_gateway_'.$this->id, [$this, 'check_ipn_response']);
            //feature 15 agosto 2024
            add_action('woocommerce_api_wc_gateway_webhook_'.$this->id, [$this, 'webhookSipago']);
/*
woocommerce_api_custom_gateway
            add_action( 'woocommerce_api_wc_gateway_webhook', function () {
                register_rest_route( 'wc/v3', '/products/category/(?P<slug>[^/]+)', array(
                    'methods' => 'GET',
                    'callback' => 'webhookSipago',
                ) );
            } );
            */

          
        }


        public static function is_valid_for_use()
        {
            return in_array(get_woocommerce_currency(), ['ARS']);
        }

        public function init_form_fields()
        {
            $this->form_fields = [
   

                'enabled' => [
                    'title'   => __('Activar/Desactivar', 'sipago_pay'),
                    'type'    => 'checkbox',
                    'default' => 'no',
                ],
                'only1Total' => [
                    'title'   => __('Se omite el detalle del pago y en link de pago que se genera solo aparece el monto total a pagar', 'sipago_pay'),
                    'type'    => 'checkbox',
                    'default' => 'no',
                ],
                'geopago_rest_client_id' => [
                    'title'       => __('client_id', 'sipago_pay'),
                    'type'        => 'text',
                    'default'     => '',
                ],
                'geopago_rest_client_secret' => [
                    'title'       => __('client_secret', 'sipago_pay'),
                    'type'        => 'text',
                    'default'     => '',
                ],

            ];
        }

 
        //feature 15 agosto 2024
        public function webhookSipago()
        {
         

                $dataGet = $_GET ;
                $dataPost = $_POST ;
                $response = new WP_REST_Response();
                return (new WebhookSipagoController($this->config))->response($response,$dataGet,$dataPost);
          
        }


        public function check_ipn_response()
        {
            @ob_clean();
            if (isset($_POST)) {
                header('HTTP/1.1 200 OK');
                $data = ($_SERVER['REQUEST_METHOD'] === 'GET') ? $_GET : $_POST;

                return (new ResponseSipagoController($this->config))->response($data);
            } else {
                echo 'Ocurrió un error al procesar su compra';
            }
        }


        public function process_payment($order_id)
        {
            //NewFeature 24May
            $amount_totals_details=-1;


            $token = time();
            $returnUrl = add_query_arg('wc-api', static::WOOCOMMERCE_API_SLUG, home_url('/')).'&order_id='.$order_id.'&ref='.$token;

            $returnUrlWebhook = add_query_arg('wc-api', 'wc_gateway_webhook_'.$this->id, home_url('/')).'&order_id='.$order_id.'&ref='.$token;
            
         
            $sipagoApiRest = new SipagoCheckoutRest($this->config['CLIENT_ID'],$this->config['CLIENT_SECRECT']);
            
           
            $order = new WC_Order($order_id);
            $amount = $order->get_total();
            $amount_tax_totals = $order->get_total_tax();
            $total_discount=$order->get_total_discount();            
 


            if($this->config['ONLY_1_TOTAL']!="no"){
                $amount_totals_details=($amount)*100;
            }


            $stackItems = [];
            foreach ( $order->get_items() as $item_id => $item ) {
                $product_name = $item->get_name();
                $subtotal = $item->get_subtotal();
                $total =$item->get_total();
                $quantity = $item->get_quantity();
    
                $product_id = $item->get_product_id();
                $totalUnit=$subtotal/$quantity;
                array_push($stackItems,[
                    'productId'=>$product_id
                    ,'productName'=>$product_name
                    ,'quantity'=>$quantity
                    ,'total'=>$totalUnit*100

                ]);
            }
            

            $shipping_total = $order->get_shipping_total();
            $shipping_method= $order->get_shipping_method();

            $shipping_Items = [];
            if($shipping_total>0){
                array_push($shipping_Items,[
                    'method'=>$shipping_method
                    ,'total'=>$shipping_total*100
                    
                ]);
            }


            $coupons = [];


            array_push($coupons,[
                'discount_type'=>"Descuento"
                ,'coupon_amount'=>-1*$total_discount*100
            ]);


            /*

            foreach( $order->get_coupon_codes() as $coupon_code ) {
                // Get the WC_Coupon object
                $coupon = new WC_Coupon($coupon_code);

                array_push($coupons,[
                    'discount_type'=>$coupon->get_discount_type()
                    ,'coupon_amount'=>-1*$coupon->get_amount()*100
                ]);
            }
            */


    
         
            $orderKey = $order->get_order_key();
            $order_total=($amount);

            do_action('sipago_pay_starting_transaction', $order);
            $resultLink= $sipagoApiRest->flowLink($returnUrl,$returnUrlWebhook,$order_id,$stackItems,$coupons,$shipping_Items, $amount_totals_details);
            

            if ($resultLink['error'] ) {
                wc_add_notice(
                    'Ocurrió un error al intentar conectar con Sipago. Por favor intenta más tarde.<br/>',
                    'error'
                );

                return;
           
            }


            $statusSipago=$resultLink['statusSipago'] ;
            $productSipago='SipagoCheckout';
            $uuidSipago=$resultLink['uuid'] ;
            $orderNumberSipago=$resultLink['orderNumber'];
           Transaction::createTransaction([
                'order_id'    => $order_id,
                'buy_order'   => $orderNumberSipago,
                'amount'      => $order_total ,
                'token'       => $token,
                'session_id'  => $uuidSipago,
                'environment' => 'LIVE',
                'product'     => $productSipago,
                'status'      => $statusSipago,
            ]);

            

            do_action('sipago_pay_transaction_started', $order, $uuidSipago);

            return [
                'result'   => 'success',
                'redirect' => $resultLink['link'],
            ];

 
        }
      

  
        public function admin_options()
        {
            $showedWelcome = get_site_option('sipago_pay_rest_showed_welcome_message');
            update_site_option('sipago_pay_rest_showed_welcome_message', true);
            $tab = 'options';
            $environment = $this->config['MODO'];
            include __DIR__.'/views/admin/options-tabs.php';
        }

        /**
         * @return mixed
         */
        public function getPluginVersion()
        {
            return (new WordpressPluginVersion())->get();
        }
    }


    function woocommerce_add_sipago_gateway($methods)
    {
        $methods[] = WC_Gateway_Sipago_Sipago_REST::class;

        return $methods;
    }

    function pay_sipago_pay_content($orderId)
    {
    }
}

function sipago_pay_rest_add_rest_action_links($links)
{
    $newLinks = [
        '<a href="'.admin_url('admin.php?page=wc-settings&tab=checkout&section=sipago_pay').'">Configurar Sipago</a>',
    ];

    return array_merge($links, $newLinks);
}

function sipago_pay_rest_on_sipagopay_rest_plugin_activation()
{
    woocommerce_sipago_rest_init();
    if (!class_exists(WC_Gateway_Sipago_Sipago_REST::class)) {
        exit('Se necesita tener WooCommerce instalado y activo para poder activar este plugin');

        return;
    }
    $pluginObject = new WC_Gateway_Sipago_Sipago_REST();
}

function on_sipago_rest_sipagopay_plugins_loaded()
{
    DatabaseTableInstaller::createTableIfNeeded();
}

function sipago_rest_remove_database()
{
    DatabaseTableInstaller::deleteTable();
}

add_action('admin_notices', function () {
    if (!class_exists(WC_Gateway_Sipago_Sipago_REST::class)) {
        return;
    }
    if (!WC_Gateway_Sipago_Sipago_REST::is_valid_for_use()) {
        ?>
        <div class="notice notice-error">
            <p><?php _e('Woocommerce debe estar configurado en pesos argentino (ARS) para habilitar Sipago', 'sipago_wc_plugin'); ?></p>
        </div>
        <?php
    }
});
register_uninstall_hook(__FILE__, 'sipago_rest_remove_database');

add_action('add_meta_boxes', function () {
    add_meta_box('sipago_check_payment_status', __('Verificar estado del pago', 'sipago_wc_plugin'), function ($post) {
        $order = new WC_Order($post->ID);
        $transaction = Transaction::getApprovedByOrderId($order->get_id());
        include __DIR__.'/views/get-status.php';
    }, 'shop_order', 'side', 'core');
});

add_action('admin_menu', function () {
    add_submenu_page('woocommerce', __('Configuración de Sipago', 'sipago_wc_plugin'), 'Sipago', 'administrator', 'sipago_pay', function () {
        $tab = filter_input(INPUT_GET, 'tbk_tab', FILTER_SANITIZE_STRING);
        if (!in_array($tab, ['healthcheck', 'logs', 'phpinfo', 'transactions'])) {
            wp_redirect(admin_url('admin.php?page=wc-settings&tab=checkout&section=sipago_pay&tbk_tab=options'));
        }

        $log = new LogHandler();
        include __DIR__.'/views/admin/options-tabs.php';
    }, null);


});

function sipago_rest_before_cart()
{
    SessionMessageHelper::printMessage();
}


