<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class Dspilot_Ajax {

     public function __construct(){
        // Add action hooks for AJAX requests
        add_action( 'wp_ajax_dspilot_get_variations_by_product_ids', array( $this, 'dspilot_get_variations_by_product_ids' ) );
        add_action( 'wp_ajax_nopriv_dspilot_get_variations_by_product_ids', array( $this, 'dspilot_get_variations_by_product_ids' ) );

        add_action( 'wp_ajax_dspilot_get_wc_countries', array( $this, 'dspilot_get_wc_countries' ) );
    }


    public function dspilot_get_variations_by_product_ids() {
        // Check nonce for security
        check_ajax_referer( 'dspilot_admin_nonce', 'nonce' );

        // Get product IDs from the request
        $product_id = isset( $_POST['pid'] ) ? intval( $_POST['pid'] ) : 0;
        $discount_index = isset( $_POST['discountIndex'] ) ? intval( $_POST['discountIndex'] ) : null;
        
        
        if ( $product_id <= 0 ) {
            wp_send_json_error( 'Invalid product ID.' );
        }
        
        // Fetch variations for the given product IDs
        $variations = Dspilot_Helper::get_product_variations($product_id);
        $selected_variation = null;

        if($discount_index){
            $dspilot_options = get_option('dspilot_options', array());
            $discounts = isset($dspilot_options['discounts']) ? $dspilot_options['discounts'] : array();

            // Get the specific discount for the given index
            $discount = isset($discounts[$discount_index]) ? $discounts[$discount_index] : null;

            if ($discount) {
                $selected_variation = isset($discount['bogo_y_product_variation_id']) ? $discount['bogo_y_product_variation_id'] : null;
            }
        }

        wp_send_json_success( array(
            'variations' => $variations,
            'selected_variation' => $selected_variation,
            'discount_index' => $discount_index,
            'discount' => isset($discount) ? $discount : null,
        ) );
    }

    public function dspilot_get_wc_countries() {
        // Check nonce for security
        check_ajax_referer( 'dspilot_admin_nonce', 'nonce' );

        // Get all countries and states
        $countries = Dspilot_Helper::get_all_wc_countries_and_states();

        if ( empty( $countries['countries'] ) ) {
            wp_send_json_error( 'No countries found.' );
        }

        wp_send_json_success( $countries['countries'] );
    }

}
// Initialize the AJAX class
new Dspilot_Ajax();