<?php

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

// AJAX Constructor
// ======================================================

class Cryptoniq_AJAX {

    public function __construct() {
        add_action( 'admin_init', array( $this, 'init' ) );
    }

    public function init() {
        add_action( 'wp_ajax_cryptoniq_paybox_checker', array( $this, 'tx_checker' ) );	
        add_action( 'wp_ajax_nopriv_cryptoniq_paybox_checker', array( $this, 'tx_checker' ) );
    }

    // Nonce Security
    private function security() {
        check_ajax_referer( 'cryptoniq_front_ajax_nonce', 'nonce' );
    }

    // Public caller for security (if needed elsewhere)
    public function sec_caller() {
        $this->security();
    }

    // Update Option Txlist
    public static function options_txlist_update( $txid = '', $id = '' ) {
        if ( empty( $txid ) || empty( $id ) ) {
            return;
        }

        $tx_list = get_option( 'cryptoniq_pay_txlist' );

        if ( $tx_list === false ) {
            // Doesn't exist — create new
            add_option( 'cryptoniq_pay_txlist', array( $txid => $id ), '', 'yes' );
        } else {
            if ( ! is_array( $tx_list ) ) {
                $tx_list = array();
            }

            if ( ! array_key_exists( $txid, $tx_list ) ) {
                $tx_list = array( $txid => $id ) + $tx_list;
                update_option( 'cryptoniq_pay_txlist', $tx_list, 'yes' );
            }
        }
    }

	// Update WooCommerce Order Status
	public static function order_status_update( $id = '', $txid = '', $status = '' ) {
		if ( empty( $id ) ) {
			return;
		}

		$order = wc_get_order( $id );
		if ( ! $order ) {
			return;
		}

		$default_status = cryptoniq_get_option( 'order_status' );

		if ( empty( $status ) ) {
			if ( ! empty( $default_status ) ) {
				$status = $default_status;
			} else {
				$status = 'processing';
			}
		}

		// Determine order status and set custom flags
		switch ( $status ) {
			case 'failed':
				$order->update_status( 'failed' );
				$order->update_meta_data( 'cryptoniq_is_failed', 1 );
				$order->save();
				
				break;

			case 'completed':
			case 'processing':
			case 'on-hold':
				$order->update_status( $status );
				break;

			default:
				$order->update_status( 'processing' );
				break;
		}

		// Always set payment-related meta
		$order->update_meta_data( 'cryptoniq_is_paid', 1 );
		$order->update_meta_data( 'cryptoniq_tx', $txid );
		$order->save();

		// Clear cart if available
		if ( isset( WC()->cart ) && method_exists( WC()->cart, 'empty_cart' ) ) {
			WC()->cart->empty_cart();
		}

		// Reduce stock for these statuses
		if ( in_array( $status, [ 'completed', 'processing', 'on-hold' ], true ) ) {
			$order->reduce_order_stock();
		}
	}

    // AJAX: Check Transaction Status
    public function tx_checker() {
        $this->security();

        $id = isset( $_POST['id'] ) ? intval( $_POST['id'] ) : 0;

        if ( empty( $id ) ) {
            wp_send_json_error( array( 'error' => 'Missing order ID' ) );
        }

        $order = wc_get_order( $id );

        if ( ! $order ) {
            wp_send_json_error( array( 'error' => 'Invalid order ID' ) );
        }

        $is_paid   = intval( $order->get_meta('cryptoniq_is_paid') );
        $is_failed = intval( $order->get_meta('cryptoniq_is_failed') );

        $data = array();

        if ( $is_failed === 1 ) {
            $data['failed'] = true;
        }

        if ( $is_paid === 1 ) {
            $data['paid'] = true;
            $data['redirect'] = $order->get_checkout_order_received_url();
        }

        wp_send_json( $data );
    }
}

new Cryptoniq_AJAX();