<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}


add_action(
    'plugins_loaded',
    'tillpaid_cash_to_cash_payments_for_woocommerce_payment_gateway_init'
);

function tillpaid_cash_to_cash_payments_for_woocommerce_payment_gateway_init() {

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


    class TILLPAID_Cash_To_Cash_Payments_For_Woocommerce_Gateway extends WC_Payment_Gateway {
    
    private $version = '4.0.1';

        public function __construct() {
            $this->id = 'cash-to-cash-payments-for-woocommerce';
            $this->icon = plugins_url('../images/icons.png', __FILE__);
            $this->method_title = __('MTN MOMO', 'cash-to-cash-payments-for-woocommerce');
            
           
            $this->title = $this->method_title;
            $this->has_fields = true;

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

            $this->enabled = $this->get_option('enabled');
            $this->description = __('Cash to Cash Payments For Woocommerce: Recevez vos Paiements Cash2Cash en ligne par MTN Mobile Money', 'cash-to-cash-payments-for-woocommerce');
            $this->method_description = $this->description;

            $this->recipient_number = $this->get_option('recipient_number');
            $this->recipient_name = $this->get_option('recipient_name');

            add_action('woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'process_admin_options'));
            
            add_action('woocommerce_checkout_update_order_meta', array($this, 'save_post_meta'));
            add_action('woocommerce_admin_order_data_after_order_details', array($this, 'display_transaction_id'), 10, 1);

            add_action('woocommerce_after_checkout_validation', array($this, 'cash_to_cash_specific_validation'), 10, 2);
            
     add_action(
    'woocommerce_checkout_create_order',
    array($this, 'save_post_meta'),
    10,
    2
);       
            add_filter('woocommerce_process_checkout_errors', array($this, 'filter_competing_errors'), 999);
        }
        

        public function init_form_fields() {

    $this->form_fields = array(

        'enabled' => array(
            'title'   => __( 'Activer/Désactiver Cash to Cash Payments For Woocommerce', 'cash-to-cash-payments-for-woocommerce' ),
            'type'    => 'checkbox',
            'label'   => __( 'Activer le paiement par MTN MoMo', 'cash-to-cash-payments-for-woocommerce' ),
            'default' => 'no',
        ),

        'recipient_name' => array(
            'title'       => __( 'Identité du Bénéficiaire', 'cash-to-cash-payments-for-woocommerce' ),
            'type'        => 'text',
            'description' => wp_kses_post(
                __(
                    'Nom du Bénéficiaire du Compte MTN MoMo. <u><strong>E.g :</strong></u> Mamadou Diabate',
                    'cash-to-cash-payments-for-woocommerce'
                )
            ),
        ),

        'recipient_number' => array(
            'title'       => __( 'Numéro de compte MTN MoMo', 'cash-to-cash-payments-for-woocommerce' ),
            'type'        => 'number',
            'description' => wp_kses_post(
                __(
                    'Numéro du Bénéficiaire du Paiement avec indicatif du pays non précédé de 00. <u><strong>E.g :</strong></u> 2250197965267',
                    'cash-to-cash-payments-for-woocommerce'
                )
            ),
        ),

        'promotion' => array(
            'title'       => __( 'Notification', 'cash-to-cash-payments-for-woocommerce' ),
            'type'        => 'textarea',
            'description' => wp_kses_post(
                __(
                    '<a href="https://tillpaid.com" target="_blank" style="font-weight:bold;color:#0073aa;">Achetez ce plugin en Version Standard ou Ultimate en cliquant sur ce lien</a>',
                    'cash-to-cash-payments-for-woocommerce'
                )
            ),
            'default'     => __(
                'Cette version est gratuite sans possibilité de téléchargement de preuve de paiement ni vérification automatisée des paiements',
                'cash-to-cash-payments-for-woocommerce'
            ),
        ),

    );
}

        public function payment_fields() {
            if (!$this->recipient_name || !$this->recipient_number || !$this->description) {
                echo '<p class="error">' .
    esc_html__(
        'Configuration de paiement incomplète - veuillez contacter l\'administrateur',
        'cash-to-cash-payments-for-woocommerce'
    ) .
'</p>';
                return;
            }

            global $woocommerce;
            $cart_total_price = $woocommerce->cart->get_total();
            ?>

            <!-- Étape 1 : numéro de téléphone -->
            <div id="cash-to-cash-step-1" class="cash-to-cash-step active">
                <h4> 1• VOTRE NUMÉRO DE TÉLÉPHONE</h4></br>
                <label for="cash_to_cash_phone"><?php esc_html_e('Entrez votre numéro de téléphone', 'cash-to-cash-payments-for-woocommerce'); ?> <span style="color:red;">*</span></label><br>
                <input type="tel" id="cash_to_cash_phone" name="cash_to_cash_phone" pattern="[0-9]{8,15}" placeholder="<?php echo esc_attr__(
    'Ex: 229XXXXXXXX',
    'cash-to-cash-payments-for-woocommerce'
); ?>" required>
                <button type="button" id="cash_to_cash_phone_validate" class="button">
                    <?php esc_html_e('Valider', 'cash-to-cash-payments-for-woocommerce'); ?>
                </button>
                <div id="cash_to_cash_phone_error" class="cash-to-cash-error"><?php esc_html_e('Veuillez entrer un numéro valide.', 'cash-to-cash-payments-for-woocommerce'); ?></div>
            </div>

            <!-- Étape 2 : loader -->
            <div id="cash-to-cash-step-2" class="cash-to-cash-step">
                <span class="cash-to-cash-loader"></span>
                <span><?php esc_html_e('Vérification veuillez patienter...', 'cash-to-cash-payments-for-woocommerce'); ?></span>
            </div>

            <!-- Étape 3 : montant + numéro bénéficiaire + bouton finaliser le paiement + loader -->
            <div id="cash-to-cash-step-3" class="cash-to-cash-step">
                <h4> 2• PROCÉDEZ AU PAIEMENT </h4></br>
<p>
<?php
echo wp_kses_post(
    sprintf(
        /* translators: 1: Total order amount. 2: Mobile Money recipient name. */
        __(
            '<strong>💱 Montant Total : %1$s</strong><br>
            ✔️ Tapez votre code #USSD MTN MoMo<br>
            ✔️ Transférez le montant à %2$s',
            'cash-to-cash-payments-for-woocommerce'
        ),
        $cart_total_price,
        esc_html( $this->recipient_name )
    )
);
?>
</p>
                <label for="cash_to_cash_beneficiary_select">
    <strong><?php esc_html_e('Numéro du Bénéficiaire', 'cash-to-cash-payments-for-woocommerce'); ?></strong>
</label><br>
                <select id="cash_to_cash_beneficiary_select" disabled>
                    <option><?php echo esc_html($this->recipient_number); ?></option>
                </select>
                <button type="button" class="button" id="cash_to_cash_finalize_payment"><?php esc_html_e('Finaliser le paiement', 'cash-to-cash-payments-for-woocommerce'); ?></button>
                <!-- Loader sous le numéro du bénéficiaire après clic sur Finaliser -->
                <div id="cash-to-cash-step-3-loader" style="display:none; margin-top:18px; text-align:center;">
                    <span class="cash-to-cash-loader"></span>
                    <span style="font-size:1.1em; color:#198edc;"><?php esc_html_e('Traitement en cours, veuillez patienter...', 'cash-to-cash-payments-for-woocommerce'); ?></span>
                </div>
            </div>

            <!-- Loader avant étape finale -->
            <div id="cash-to-cash-step-4-loader" class="cash-to-cash-step">
                <span class="cash-to-cash-loader"></span>
                <span><?php esc_html_e('Vérification veuillez patienter...', 'cash-to-cash-payments-for-woocommerce'); ?></span>
            </div>

            <!-- Étape 4 : référence + preuve (cachée par défaut) -->
            <div id="cash-to-cash-step-4" class="cash-to-cash-step">
                <h4> 3•  VALIDATION </h4></br>
                <?php
                woocommerce_form_field('cash_to_cash_transaction_id', array(
                    'type' => 'text',
                    'label' => __('ID de Transaction', 'cash-to-cash-payments-for-woocommerce'),
                    'placeholder' => __('Vérifier votre sms de confirmation...', 'cash-to-cash-payments-for-woocommerce'),
                    'required' => true,
                    'class' => array('form-row-wide'),
                    'custom_attributes' => array(
                        'pattern' => '^[0-9]{6,15}$',
                        'maxlength' => '15',
                        'inputmode' => 'numeric',
                        'oninput' => "this.value = this.value.replace(/[^0-9]/g, '').slice(0,15);"
                    )
                ));
                ?>

                
            </div>

            <?php
        }

 public function cash_to_cash_specific_validation( $data, $errors ) {

    if (
        ! isset( $data['payment_method'] ) ||
        $data['payment_method'] !== $this->id
    ) {
        return;
    }

    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Verified by WooCommerce checkout process.
    $transaction_id = isset( $_POST['cash_to_cash_transaction_id'] )
        ? sanitize_text_field( wp_unslash( $_POST['cash_to_cash_transaction_id'] ) )
        : '';

    if ( empty( $transaction_id ) ) {

        $errors->add(
            'cash-to-cash-payments-for-woocommerce',
            __( 'ID transaction manquant', 'cash-to-cash-payments-for-woocommerce' )
        );

    } elseif ( ! preg_match( '/^[0-9]{6,15}$/', $transaction_id ) ) {

        $errors->add(
            'cash-to-cash-payments-for-woocommerce',
            __( 'ID transaction invalide (Entre 6 et 15 chiffres)', 'cash-to-cash-payments-for-woocommerce' )
        );

    }
}

        public function filter_competing_errors($errors) {
           // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Verified by WooCommerce checkout process.
            if (
    isset( $_POST['payment_method'] ) &&
    sanitize_text_field( wp_unslash( $_POST['payment_method'] ) ) === $this->id
) {
                foreach ($errors->errors as $code => $msg) {
                    if (strpos($code, 'cash-to-cash-payments-for-woocommerce') === false) {
                        $errors->remove($code);
                    }
                }
            }
            return $errors;
        }

        public function process_payment($order_id) {

    $order = wc_get_order($order_id);

    if (isset($_POST['cash_to_cash_transaction_id'])) {
        $order->update_meta_data(
            '_cash_to_cash_transaction_id',
            sanitize_text_field(wp_unslash($_POST['cash_to_cash_transaction_id']))
        );
    }

    if (isset($_POST['cash_to_cash_phone'])) {
        $order->update_meta_data(
            '_cash_to_cash_phone',
            sanitize_text_field(wp_unslash($_POST['cash_to_cash_phone']))
        );
    }

    $order->save();

    $order->update_status(
        'on-hold',
        __('Paiement en attente de vérification', 'cash-to-cash-payments-for-woocommerce')
    );

    WC()->cart->empty_cart();

    return array(
        'result'   => 'success',
        'redirect' => $this->get_return_url($order),
    );
}

        public function save_post_meta( $order_id ) {
// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Verified by WooCommerce checkout process.
    if ( ! empty( $_POST['cash_to_cash_transaction_id'] ) ) {
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Verified by WooCommerce checkout process.
        update_post_meta(
            $order_id,
            '_cash_to_cash_transaction_id',
            sanitize_text_field( wp_unslash( $_POST['cash_to_cash_transaction_id'] ) )
        );
    }
    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Verified by WooCommerce checkout process.

    if ( ! empty( $_POST['cash_to_cash_phone'] ) ) {
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Verified by WooCommerce checkout process.
        update_post_meta(
            $order_id,
            '_cash_to_cash_phone',
            sanitize_text_field( wp_unslash( $_POST['cash_to_cash_phone'] ) )
        );
    }
}

            

        public function display_transaction_id($order) {
            if ($order->get_payment_method() === $this->id) {
                $transaction_id = $order->get_meta('_cash_to_cash_transaction_id');
                
                $phone = $order->get_meta('_cash_to_cash_phone');

                echo '<div class="order_data_column">';
                echo '<h3>' . esc_html__( 'Détails MTN MOMO', 'cash-to-cash-payments-for-woocommerce' ) . '</h3>';
                if ($phone) {
                    echo '<p><strong>' .
    esc_html__( 'Téléphone client:', 'cash-to-cash-payments-for-woocommerce' ) .
    '</strong> ' .
    esc_html( $phone ) .
    '</p>';
                }
                echo '<p><strong>' .
    esc_html__( 'ID Transaction:', 'cash-to-cash-payments-for-woocommerce' ) .
    '</strong> ' .
    esc_html( $transaction_id ) .
    '</p>';

                
                echo '</div>';
            }
        }

        
} 

function tillpaid_add_cash_to_cash_payments_for_woocommerce_gateway($methods) {
    $methods[] = 'TILLPAID_Cash_To_Cash_Payments_For_Woocommerce_Gateway';
    return $methods;
}

add_filter(
    'woocommerce_payment_gateways',
    'tillpaid_add_cash_to_cash_payments_for_woocommerce_gateway'
);
}
