/**
 * Template: ms-lms-starter-theme
 * Theme Name: MasterStudy Templates Child
 * Theme URI: https://starter.stylemixthemes.com/
 * Author: StylemixThemes
 * Author URI: https://stylemixthemes.com/
 * Description: MasterStudy Templates Child Theme is the child theme for the MasterStudy Templates. With this child theme, you can customize your eLearning website appearance without changing the original templates.
 * License: GNU General Public License v2 or later
 * License URI: http://www.gnu.org/licenses/gpl-2.0.html
 * Tags: classes, courses, Education, education center, e-commerce, learning center, tutoring, teaching, study, studying, learning, lessons, instructor, teacher, mentor
 * Text Domain: starter-text-domain
 * Version: 1.0.0
 */


<?php
/**
 * Plugin Name: TopPay Payment Gateway
 * Description: MonCash & NatCash payments via TopPay for WooCommerce
 * Version: 1.0.0
 * Author: SB Techno LLC
 */

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

add_action('plugins_loaded', 'init_toppay_gateway');

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

    class WC_TopPay_Gateway extends WC_Payment_Gateway {
        public function __construct() {
            $this->id = 'toppay';
            $this->icon = '';
            $this->has_fields = true;
            $this->method_title = 'TopPay';
            $this->method_description = 'Pay with MonCash or NatCash';

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

            $this->title = $this->get_option('title');
            $this->description = $this->get_option('description');
            $this->api_key = $this->get_option('api_key');
            $this->api_url = 'https://tsgjmgwtzybauporkmdb.supabase.co/functions/v1';
            $this->webhook_secret = $this->get_option('webhook_secret');

            add_action('woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'process_admin_options'));
            add_action('woocommerce_api_toppay', array($this, 'webhook_handler'));
        }

        public function init_form_fields() {
            $this->form_fields = array(
                'enabled' => array(
                    'title' => 'Enable/Disable',
                    'type' => 'checkbox',
                    'label' => 'Enable TopPay',
                    'default' => 'no'
                ),
                'title' => array(
                    'title' => 'Title',
                    'type' => 'text',
                    'default' => 'MonCash / NatCash'
                ),
                'description' => array(
                    'title' => 'Description',
                    'type' => 'textarea',
                    'default' => 'Pay securely with MonCash or NatCash mobile money.'
                ),
                'api_key' => array(
                    'title' => 'API Key',
                    'type' => 'password',
                    'description' => 'Get your API key from TopPay dashboard'
                ),
                'webhook_secret' => array(
                    'title' => 'Webhook Secret',
                    'type' => 'password',
                    'description' => 'Get webhook secret from TopPay dashboard'
                ),
            );
        }

        public function payment_fields() {
            echo '<p>' . esc_html($this->description) . '</p>';
            echo '<fieldset>';
            echo '<p class="form-row form-row-wide">';
            echo '<label>Payment Method <span class="required">*</span></label>';
            echo '<select name="toppay_method" required>';
            echo '<option value="moncash">MonCash</option>';
            echo '<option value="natcash">NatCash</option>';
            echo '</select>';
            echo '</p>';
            echo '<p class="form-row form-row-wide">';
            echo '<label>Phone Number <span class="required">*</span></label>';
            echo '<input type="tel" name="toppay_phone" placeholder="+509 XXXX XXXX" required />';
            echo '</p>';
            echo '</fieldset>';
        }

        public function process_payment($order_id) {
            $order = wc_get_order($order_id);
            $payment_method = sanitize_text_field($_POST['toppay_method']);
            $phone = sanitize_text_field($_POST['toppay_phone']);

            $response = wp_remote_post($this->api_url . '/create-payment', array(
                'headers' => array(
                    'Content-Type' => 'application/json',
                    'X-API-Key' => $this->api_key
                ),
                'body' => json_encode(array(
                    'order_id' => (string) $order_id,
                    'amount' => (float) $order->get_total(),
                    'currency' => $order->get_currency(),
                    'payment_method' => $payment_method,
                    'customer_phone' => $phone,
                    'customer_email' => $order->get_billing_email(),
                    'return_url' => $this->get_return_url($order),
                    'metadata' => array(
                        'wc_order_id' => $order_id,
                        'customer_name' => $order->get_billing_first_name() . ' ' . $order->get_billing_last_name()
                    )
                )),
                'timeout' => 30
            ));

            if (is_wp_error($response)) {
                wc_add_notice('Payment error: ' . $response->get_error_message(), 'error');
                return;
            }

            $body = json_decode(wp_remote_retrieve_body($response), true);

            if (!empty($body['success']) && !empty($body['payment_url'])) {
                $order->update_meta_data('_toppay_transaction_id', $body['transaction_id']);
                $order->save();

                return array(
                    'result' => 'success',
                    'redirect' => $body['payment_url']
                );
            }

            wc_add_notice('Payment error: ' . ($body['error'] ?? 'Unknown error'), 'error');
            return;
        }

        public function webhook_handler() {
            $payload = file_get_contents('php://input');
            $signature = $_SERVER['HTTP_X_TOPPAY_SIGNATURE'] ?? '';
            
            // Verify signature
            $expected = hash_hmac('sha256', $payload, $this->webhook_secret);
            if (!hash_equals($expected, $signature)) {
                status_header(401);
                exit('Invalid signature');
            }

            $data = json_decode($payload, true);
            $order_id = $data['order_id'] ?? null;

            if (!$order_id) {
                status_header(400);
                exit('Missing order_id');
            }

            $order = wc_get_order($order_id);
            if (!$order) {
                status_header(404);
                exit('Order not found');
            }

            switch ($data['status']) {
                case 'completed':
                    $order->payment_complete($data['transaction_id']);
                    $order->add_order_note('TopPay payment completed. Ref: ' . $data['provider_reference']);
                    break;
                case 'failed':
                    $order->update_status('failed', 'TopPay payment failed.');
                    break;
            }

            status_header(200);
            exit('OK');
        }
    }

    function add_toppay_gateway($methods) {
        $methods[] = 'WC_TopPay_Gateway';
        return $methods;
    }
    add_filter('woocommerce_payment_gateways', 'add_toppay_gateway');
}
