<?php

/**
 * Plugin Name: Payfaci Payment Gateway
 * Description: Integrate Payfaci payment gateway with WooCommerce.
 * Plugin URI:  https://payfaci.com
 * Version:     1.2.15
 * Author:      Payfaci Developer
 * Author URI:  https://payfaci.com
 * Text Domain: woocommerce-payfaci-payment
 * Domain Path: /languages
 */

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

define('PAYFACI_FILE', __FILE__);
define('PAYFACI_DIR', dirname(PAYFACI_FILE));
define('PAYFACI_PLUGIN_DIR', plugin_dir_url(__FILE__));

// Required versions
define('PAYFACI_REQUIRED_WP_VERSION', '5.8');
define('PAYFACI_REQUIRED_WC_VERSION', '8.9.3');

// Include the library for plugin updates
require 'plugin-update-checker/plugin-update-checker.php';
use YahnisElsts\PluginUpdateChecker\v5\PucFactory;
// Initialize the plugin update checker
$myUpdateChecker = PucFactory::buildUpdateChecker(
    //'https://payfaci.com/assets/wooplugin/payfaciupdate.json',
	'https://github.com/Payfaci/Payfaci-Woocommerce-Plugin/',
    __FILE__,
    'woocommerce-payfaci-payment'
);

//Set the branch that contains the stable release.
$myUpdateChecker->setBranch('main');

//Optional: If you're using a private repository, specify the access token like this:
$myUpdateChecker->setAuthentication('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');

 $myUpdateChecker->getVcsApi()->enableReleaseAssets();

// Check if WooCommerce is active
if (in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {


    add_action('plugins_loaded', 'custom_gateway_init', 11);

    function custom_gateway_init()
    {
        if (!class_exists('WC_Payment_Gateway')) return;

             // Version checks
             if (version_compare(get_bloginfo('version'), PAYFACI_REQUIRED_WP_VERSION, '<')) {
                add_action('admin_notices', function() {
                    echo '<div class="error"><p>' . sprintf(__('Payfaci Payment Gateway requires WordPress version %s or higher.', 'woocommerce-payfaci-payment'), PAYFACI_REQUIRED_WP_VERSION) . '</p></div>';
                });
                return;
            }

            if (defined('WC_VERSION') && version_compare(WC_VERSION, PAYFACI_REQUIRED_WC_VERSION, '<')) {
                add_action('admin_notices', function() {
                    echo '<div class="error"><p>' . sprintf(__('Payfaci Payment Gateway requires WooCommerce version %s or higher.', 'woocommerce-payfaci-payment'), PAYFACI_REQUIRED_WC_VERSION) . '</p></div>';
                });
                return;
            }
    
        class WC_Custom_Gateway extends WC_Payment_Gateway
        {
    
            // Sınıf özelliklerini tanımlayın
            public $apikey;
    
            public function __construct()
            {
                $this->id = 'payfaci-payment';
                $this->icon = '';
                $this->has_fields = true;
                $this->method_title = 'Payfaci';
                $this->method_description = 'Payfaci Payment Gateway Integration';
    
                // Load the settings
                $this->init_form_fields();
                $this->init_settings();
    
                // Define user settings
                $this->title = $this->get_option('title');
                $this->description = $this->get_option('description');
                $this->apikey = $this->get_option('apikey');
    
                // Actions
                add_action('woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'process_admin_options'));
                add_action('woocommerce_receipt_' . $this->id, array($this, 'receipt_page'));
                add_action('woocommerce_thankyou_' . $this->id, array($this, 'thankyou_page'));
                add_action('woocommerce_api_wc_' . $this->id, array($this, 'check_response'));
    
                // Allow payment for "On Hold" orders
                add_filter('woocommerce_valid_order_statuses_for_payment', array($this, 'custom_valid_order_statuses_for_payment'), 10, 2);
                add_filter('woocommerce_payment_successful_result', array($this, 'custom_payment_successful_result'), 10, 2);
            }
    
            public function custom_valid_order_statuses_for_payment($statuses, $order)
            {
                if ($order->get_payment_method() === $this->id) {
                    $statuses[] = 'on-hold';
                }
                return $statuses;
            }
    
            public function custom_payment_successful_result($result, $order_id)
            {
                $order = wc_get_order($order_id);
                if ($order->get_payment_method() === $this->id) {
                    $result['redirect'] = $order->get_checkout_payment_url(true);
                }
                return $result;
            }
    
            public function init_form_fields()
            {
                $this->form_fields = array(
                    'enabled' => array(
                        'title' => 'Enable/Disable',
                        'type' => 'checkbox',
                        'label' => 'Enable Custom Payment Gateway',
                        'default' => 'yes'
                    ),
                    'title' => array(
                        'title' => 'Title',
                        'type' => 'text',
                        'description' => 'This controls the title which the user sees during checkout.',
                        'default' => 'Payfaci Payment Gateway',
                        'desc_tip' => true,
                    ),
                    'description' => array(
                        'title' => 'Description',
                        'type' => 'textarea',
                        'description' => 'This controls the description which the user sees during checkout.',
                        'default' => 'Pay with Payfaci payment gateway.',
                    ),
                    'apikey' => array(
                        'title' => 'API Key',
                        'type' => 'text',
                        'description' => 'Your Payfaci API Key.',
                        'default' => '',
                        'desc_tip' => true,
                    ),
                );
            }
    
            public function payment_fields()
            {
              echo '<p>Make payment using PayPal, Credit or Debit Card.</p>';
              echo '<div style="display:flex; width:auto;">
                  <div style="display:flex; width: 500px; height: 90px;">
                     <img src="' . plugin_dir_url(__FILE__) . 'payfaciframe.png" alt="Payfaci" style="width: 606px; height: 127px;" />
                   </div>
                   </div>';
            }
    
            public function process_payment($order_id)
            {
                $order = wc_get_order($order_id);
    
                // Mark as on-hold (we're awaiting the payment)
                $order->update_status('on-hold', __('Awaiting custom payment', 'woocommerce'));
    
                // Reduce stock levels
                wc_reduce_stock_levels($order_id);
    
                // Empty cart
                WC()->cart->empty_cart();
    
                // Return thank you page redirect
                return array(
                    'result' => 'success',
                    'redirect' => $order->get_checkout_payment_url(true)
                );
            }
    
            public function receipt_page($order_id)
            {
    
    
                $order = wc_get_order($order_id);
                $callback_url = home_url('/wc-api/wc_' . $this->id . '?order_id=' . $order_id);
                $api_check_url = rest_url('custom_payment/v1/check_status?order_id=' . $order_id);
                $thank_you_url = $order->get_checkout_order_received_url();
                $email = $order->get_billing_email();
				
				 $billing_info = array(
                  'first_name' => $order->get_billing_first_name(),
                  'last_name' => $order->get_billing_last_name(),
                  'company' => $order->get_billing_company(),
                  'address_1' => $order->get_billing_address_1(),
                  'address_2' => $order->get_billing_address_2(),
                  'city' => $order->get_billing_city(),
                  'state' => $order->get_billing_state(),
                  'postcode' => $order->get_billing_postcode(),
                  'country' => $order->get_billing_country(),
                  'email' => $order->get_billing_email(),
                  'phone' => $order->get_billing_phone(),
              );
              $billing_data = base64_encode(json_encode($billing_info, JSON_PRETTY_PRINT));
              $items = $order->get_items();
              $products = array();
          
              foreach ($items as $item_id => $item) {
                  $product = $item->get_product();
                  $products[] = array(
                      'name' => $item->get_name(),
                      'quantity' => $item->get_quantity(),
                      'total' => $item->get_total(),
                      'sku' => $product ? $product->get_sku() : '',
                  );
              }
          

              $order_infoJson = base64_encode(json_encode($products, JSON_PRETTY_PRINT));
    
                echo '<div class="payfaci_container"><p>' . __('Thank you for your order, Please click the button below to complete the order and make the payment.', 'woocommerce') . '</p>';
                echo '<button id="custom-payment-button" class="payfaci_btn" type="button" onclick="openPaymentPopup(popupUrl)">Pay Now</button></div>';
                echo '
                <script type="text/javascript">
    
    
                 var apiKey = "' . esc_js($this->apikey) . '";
                            var currencyCode = "' . get_woocommerce_currency() . '";
                            var amount = "' . esc_js($order->get_total()) . '";
                            var url = "' . esc_js($callback_url) . '";
    
                         var popupUrl = "https://payfaci.com/ipn/gateway?api_key=" + apiKey +
                            "&currency_code=" + currencyCode +
                            "&wooData=" + "' . esc_js($billing_data) . '" +
                            "&wooOrderInformation=" + "' . esc_js($order_infoJson) . '" +
                            "&amount=" + amount + 
                            "&url=" + url;
    
    
                    jQuery(document).ready(function($){
                        var checkOrderStatus = setInterval(function() {
                        $.get("' . esc_js($api_check_url) . '", function(response) {
                            if (response.status === "success") {
                                clearInterval(checkOrderStatus);
                                window.location.href = "' . esc_js($thank_you_url) . '";
                            }
                        });
                    }, 5000); // Her 5 saniyede bir kontrol et
                    });
                </script>';
    
    
                echo <<<EOL
    
                    <style>
                    .payfaci_btn{
                        color: #fff;
                        font-size: large;
                        background: linear-gradient(180deg, #9BE06B 33.69%, #6FA14C 91.89%);
                        box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.25);
                        border-radius: 30px; */
                        padding: 10px 20px;
                        gap: 10px;
                        width: 190px;
                        height: 37px;
                        left: 38px;
                        top: 20px;
                        background: linear-gradient(180deg, #9BE06B 33.69%, #6FA14C 91.89%);
                        box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.25);
                        border-radius: 20px;
                    }
                    .payfaci_container{
                        display: flex;
                        flex-direction: column;
                        align-items: center;
                        justify-content: center;
                        gap: 10px;
                    }
    
                    </style>
    
    
                        <script type="text/javascript">
                          var PaymentPopup = {
                          overlayId: 'payment-overlay',
                          popupId: 'payment-popup',
                          closeBtnId: 'payment-close',
                          iframeId: 'payment-iframe',
                          popupUrl: '',
                        
                          init: function () {
                            this.injectStyles();
                            this.createOverlay();
                            this.createPopup();
                            this.createCloseButton();
                            this.createIframe();
                            this.attachEvents();
                          },
                        
                          injectStyles: function () {
                            var css = `
                                #payment-overlay {
                                  display: none;
                                  position: fixed;
                                  top: 0;
                                  left: 0;
                                  width: 100%;
                                  height: 100%;
                                  background-color: rgba(0, 0, 0, 0.5);
                                  z-index: 9998;
                                }
                                #payment-popup {
                                  display: none;
                                  position: fixed;
                                  top: 50%;
                                  left: 50%;
                                  transform: translate(-50%, -50%);
                                  width: 700px;
                                  height: 500px;
                                  border: 1px solid #ccc;
                                  background-color: #fff;
                                  z-index: 9999;
                                }
                                #payment-close {
                                  position: absolute;
                                  top: -30px;
                                  right: 10px;
                                  cursor: pointer;
                                }
                                   @media (max-width: 600px) {
                                #payment-popup {
                                  width: 95%;
                                  height: 70%;
                                }
                                #payment-close {
                                  top: 5px;
                                  right: 5px;
                                  font-size: 18px;
                                }
                              }
                              `;
                            var style = document.createElement('style');
                            style.innerHTML = css;
                            document.head.appendChild(style);
                          },
                        
                          createOverlay: function () {
                            var overlay = document.createElement('div');
                            overlay.id = this.overlayId;
                            document.body.appendChild(overlay);
                          },
                        
                          createPopup: function () {
                            var popup = document.createElement('div');
                            popup.id = this.popupId;
                            document.body.appendChild(popup);
                          },
                        
                          createCloseButton: function () {
                            var closeButton = document.createElement('button');
                            closeButton.id = this.closeBtnId;
                            closeButton.textContent = 'Close';
                            closeButton.addEventListener('click', function () {
                              PaymentPopup.closePopup();
                            });
                            document.getElementById(this.popupId).appendChild(closeButton);
                          },
                        
                          createIframe: function () {
                            var iframe = document.createElement('iframe');
                            iframe.id = this.iframeId;
                            iframe.frameBorder = 0;
                            iframe.width = '100%';
                            iframe.height = '100%';
                            document.getElementById(this.popupId).appendChild(iframe);
                          },
                        
                          attachEvents: function () {
                            var self = this;
                           
                        
                            document
                              .getElementById(this.overlayId)
                              .addEventListener('click', function () {
                                // self.closePopup();
                              });
                            document
                              .getElementById(this.closeBtnId)
                              .addEventListener('click', function () {
                                self.closePopup();
                              });
                            window.addEventListener('payfaci', function (event) {
                              var paymentResponse = event.data;
                              if (paymentResponse.success) {
                                alert('Payment successful!');
                                self.closePopup();
                              } else {
                                alert('Payment cancelled or failed. Please try again.');
                                self.closePopup();
                              }
                            });
                          },
                        
                          openPopup: function (url) {
                          console.log(url);
                            if (
                              document.getElementById(this.overlayId).style.display === 'block' &&
                              document.getElementById(this.popupId).style.display === 'block'
                            ) {
                              return;
                            }
                            document.getElementById(this.overlayId).style.display = 'block';
                            document.getElementById(this.popupId).style.display = 'block';
                            document.getElementById(this.iframeId).src = url;
    
                          },
                        
                          closePopup: function () {
                            document.getElementById(this.overlayId).style.display = 'none';
                            document.getElementById(this.popupId).style.display = 'none';
                            document.getElementById(this.iframeId).src = '';
                          },
                        };
                        
                        document.addEventListener('DOMContentLoaded', function () {
                          PaymentPopup.init();
                        });
                        
                        function openPaymentPopup(url) {
                        console.log(url);
                          PaymentPopup.openPopup(url);
                        }
                        
    
                    </script>
    EOL;
            }
    
            public function thankyou_page($order_id)
            {
                $order = wc_get_order($order_id);
                echo '<p>' . __('Thank you for your order! Your payment has been received and your order is now being processed.', 'woocommerce') . '</p>';
            }
    
            public function check_response()
            {
                // Handle response from the payment gateway
                $order_id = $_GET['order_id']; 
                $order = wc_get_order($order_id);
    
                // Callback JSON verisini al
                $response = json_decode(file_get_contents('php://input'), true);
    
                // Check Status
                if ($order && isset($response['paymentStatus'])) {
                    $payment_status = $response['paymentStatus'];
                    if ($payment_status == 'success') {
                        $order->payment_complete();
                        $order->add_order_note(__('Payment completed via Payfaci Payment Gateway', 'woocommerce'));
                    } else {
                        $order->update_status('failed', __('Payment failed via Payfaci Payment Gateway', 'woocommerce'));
                    }
                }
    
                // HTTP yanıtı olarak 200 OK gönder
                http_response_code(200);
                exit;
            }
        }
    
        // Add the gateway to WooCommerce
        add_filter('woocommerce_payment_gateways', 'add_custom_gateway_class');
        function add_custom_gateway_class($gateways)
        {
            $gateways[] = 'WC_Custom_Gateway';
            return $gateways;
        }
    
        add_action('rest_api_init', function () {
            register_rest_route('custom_payment/v1', '/check_status', array(
                'methods' => 'GET',
                'callback' => 'custom_check_order_status',
                'permission_callback' => '__return_true',
            ));
        });
    
        function custom_check_order_status(WP_REST_Request $request)
        {
            $order_id = $request->get_param('order_id');
            $order = wc_get_order($order_id);
    
            if ($order) {
                $order_status = $order->get_status();
                if ($order_status !== 'on-hold') {
                    return new WP_REST_Response(array('status' => 'success'), 200);
                } else {
                    return new WP_REST_Response(array('status' => 'pending'), 200);
                }
            } else {
                return new WP_REST_Response(array('status' => 'error', 'message' => 'Order not found'), 404);
            }
        }
    }




}
