<?php

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

// Register the admin menu
function gift_card_admin_menu() {
    add_options_page(
        'Cardivo Setting',
        'Cardivo',
        'manage_options',
        'cardivo-settings',
        'cardivo_settings_page'
    );
}
add_action('admin_menu', 'gift_card_admin_menu');

// Render the settings page
function cardivo_settings_page() {
    if (!current_user_can('manage_options')) {
        wp_die(__('You do not have sufficient permissions to access this page.'));
    }

    // Save or update authentication code
    if (isset($_POST['cardivo_variable_value'])) {
        $variable_value = sanitize_text_field($_POST['cardivo_variable_value']);
        update_option('cardivo_authentication_code', $variable_value);
    }

    // Get the authentication code
    $authentication_code = get_option('cardivo_authentication_code');

    // Display settings form
    ?>
    <div class="wrap">
        <h1>Cardivo Gift Cards</h1>
        <form method="post">
            <table class="form-table">
                <tr valign="top">
                    <th scope="row">
                        <label for="cardivo_variable_value">Enter your Cardivo Access token</label>
                    </th>
                    <td>
                        <input type="text" id="cardivo_variable_value" name="cardivo_variable_value" value="<?php echo esc_attr($authentication_code); ?>" />
                        <p>You need to generate this token via the <a href="https://app.cardivo.com/settings" target="_blank">Integrations tab</a> in your Cardivo settings</p>
                    </td>
                </tr>
            </table>
            <p class="submit">
                <input type="submit" class="button-primary" value="Save" />
            </p>
        </form>
    </div>
    <?php
}

//add script and css for admin and for default flow
function add_cardivo_scripts() {
  wp_enqueue_style( 'cardivo-style', plugin_dir_url( __FILE__ ) . 'assets/css/cardivo.css', array(), '1.1', 'all');
}
add_action( 'wp_enqueue_scripts', 'add_cardivo_scripts' );

function cardivo_admin_script() {
    if(is_admin()){
      wp_enqueue_script('cardivo-admin-js', plugin_dir_url( __FILE__ ) . 'assets/js/admin.js', array('jquery'));
      wp_enqueue_style( 'cardivo-admin-style', plugin_dir_url( __FILE__ ) . 'assets/css/cardivo-admin.css', array(), '1.1', 'all');
    }   
    wp_enqueue_script( 'cardivo-custom-js', plugin_dir_url( __FILE__ ) . 'assets/js/cardivo-custom.js', array('jquery'));
}
add_action('init', 'cardivo_admin_script');

// Add gift card input field and Apply Gift Card button to WooCommerce checkout page
function add_gift_card_field() {
    echo '<div id="giftCardField"><div class="top-header"><img src="https://pub-7103d88a43754ed6a73fcfa6ebce51bf.r2.dev/Plugin/Images/np_gift-card_4917673_000000.svg"><a href="javascript:void(0)" id="redeem-gift-card">Redeem a gift card</a></div><div class="custom-input-box" style="display:none;">';
    woocommerce_form_field('giftCardCode', array(
        'type' => 'text',
        'class' => array('form-row-wide'),
        'placeholder' => 'Enter your gift card',
        'required' => true,
    ), '');
    echo '<button id="applyGiftCard" class="button alt">Apply</button>';
    echo '</div><div id="message" style="display:none;"><span><div id="gift-price"></div>gift card applied</span><button class="remove-cardivo-gift-card">Remove</button><div class="bottom-msg"></div></div>'; // Placeholder for message
    echo '<div class="error-msg" style="display:none;"></div></div>';
}
add_action('woocommerce_review_order_before_payment', 'add_gift_card_field');

// Enqueue the JavaScript file
function enqueue_giftcard_ajax_script() {
    wp_enqueue_script('giftcard-ajax',  plugin_dir_url( __FILE__ ) . 'assets/js/cardivo-api.js', array('jquery'), '1.0', true);
    wp_localize_script('giftcard-ajax', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php')));
}
add_action('wp_enqueue_scripts', 'enqueue_giftcard_ajax_script');

// AJAX action to apply the gift card and update the checkout
add_action('wp_ajax_apply_gift_card', 'apply_gift_card');
add_action('wp_ajax_nopriv_apply_gift_card', 'apply_gift_card');

function apply_gift_card() {
    $gift_card_code = $_POST['giftCardCode'];
    $api_key = get_option('cardivo_authentication_code');

    // Perform API call to validate the gift card and get its value
    $api_endpoint = 'http://app.cardivo.com/api/v1/gift_cards/status';

    if(!empty($api_key)){
        $api_key = $api_key;
    }else{
        wp_send_json_error(array('message' => 'Please ask the administrator of this site to check their Cardivo settings as they are configured incorrectly.'));
        wp_die();
    }

    $response = wp_remote_post($api_endpoint, array(
        'headers' => array(
            'Authorization' => 'Bearer ' . $api_key,
            'Content-Type' => 'application/json',
        ),
        'body' => wp_json_encode(array('gift_card_number' => $gift_card_code)),
    ));

    if (!is_wp_error($response)) {
        $gift_card_data = json_decode(wp_remote_retrieve_body($response), true);
        $message = $gift_card_data['checkout_description'];
        $cart = WC()->cart;
        $gift_currency = $gift_card_data['currency'];
        $gift_currency_symbol = html_entity_decode(get_woocommerce_currency_symbol());
        $wc_currency = get_woocommerce_currency();

        if ($gift_card_data && $gift_card_data['status'] === 'valid') {
            $gift_card_value = $gift_card_data['value_balance']; // Assuming API returns the gift card value balance
            if($wc_currency != $gift_currency){
                wp_send_json_error(array("message" => "The gift card currency (".$gift_currency.") doesn't match the order currency (".$wc_currency."). Please use a gift card in the same currency."));
                wp_die();
            } else {
                global $woocommerce;
                if ($gift_card_value > 0) {
                    $cart_total = WC()->cart->total;            
                    $updated_total = $cart_total - $gift_card_value;

                    if ($gift_card_value >= $cart_total) {
                        WC()->session->set('gift_card_value', $cart_total);
                        wp_send_json_success(array('message' => $message, 'gift_card_value' => $cart_total, 'gift_currency'=>$gift_currency_symbol));
                    } else {
                        WC()->session->set('gift_card_value', $gift_card_value);
                        wp_send_json_success(array('message' => $message, 'gift_card_value' => $gift_card_value, 'gift_currency'=>$gift_currency_symbol));
                    }
                }
                else {
                    wp_send_json_error(array('message' => $message));
                    wp_die();
                }
            } // if currency is valid
        }else{
            wp_send_json_error(array('message' => $message));
            wp_die();
        } // if status valid 
    } else {
        wp_send_json_error(array('message' => "There's some issue while applying gift card."));
    }
    wp_die();
}

// Function to calculate and add shipping fee
function calculate_shipping_fee() {
    if (WC()->session->get('gift_card_value')) {
        $gift_card_value = WC()->session->get('gift_card_value');
        WC()->cart->add_fee('Cardivo gift card:', -$gift_card_value);
    }
}
add_action('woocommerce_cart_calculate_fees', 'calculate_shipping_fee');

// Update order total just before order finalization
/* add_action('woocommerce_checkout_update_order_review', 'update_order_total_before_finalization');
function update_order_total_before_finalization($post_data) {
    if (isset($post_data['payment_method']) && isset($post_data['woocommerce-process-checkout-nonce'])) {
        // Check if payment method and nonce are set to ensure it's the final checkout step
        if (WC()->session->get('gift_card_value')) {
            $gift_card_value = WC()->session->get('gift_card_value');
            WC()->cart->add_fee('Cardivo Gift Card:', -$gift_card_value); // Apply negative fee to deduct the gift card value from the total
        }
    }
} */

// Send data to redeem API after order processing
//add_action('woocommerce_checkout_order_processed', 'send_data_to_redeem_api_classic');

add_action('woocommerce_checkout_order_processed', 'send_data_to_redeem_api_classic', 10, 2);
//add_action('woocommerce_store_api_checkout_order_processed', 'send_data_to_redeem_api_classic', 10, 2);
function send_data_to_redeem_api_classic($order_id) {
    
    error_log("send_data_to_redeem_api_classic triggered for Order ID: " . $order_id);
    //break;

    static $already_processed = false;

    if ($already_processed) {
        return;
    }
    
    $already_processed = true;

    // Get the order object
    $order = wc_get_order($order_id);

    global $wp;
    $current_page_url = home_url(add_query_arg(array(), $wp->request));
    // Get the necessary data from the order
    $gift_card_number = sanitize_text_field($_POST['giftCardCode']); // Assuming 'giftCardCode' is the input field name
    $gift_card_value = WC()->session->get('gift_card_value');

    $value_redeemed = $gift_card_value; // Replace with the actual value redeemed
    $date_redeemed = date('Y-m-d H:i:s'); // Current date and time
    $ip_address = $_SERVER['REMOTE_ADDR']; // Get user's IP address
    $channel = 'woocommerce';
    $url = $current_page_url;
    $description = 'Redeem description';
    $email = $order->get_billing_email();
    $api_key = get_option('cardivo_authentication_code');
    $cartTotal = WC()->cart->total;
    $purchase_total = $cartTotal + $gift_card_value;
    $total_excl_gift_card = WC()->cart->total;
    $wc_currency = get_woocommerce_currency();

    // Prepare the request body
    $body_redeme = wp_json_encode(array(
        'value_redeemed' => $value_redeemed,
        'date_redeemed' => $date_redeemed,
        'ip_address' => $ip_address,
        'channel' => $channel,
        'url' => $url,
        'description' => $description,
        'email' => $email,
        'purchase_total' => $purchase_total,
        'total_excl_gift_card' => $total_excl_gift_card,
        'currency' => $wc_currency,
    ));

    // Prepare the request headers
    $header = array(
        'Authorization' => 'Bearer ' . $api_key,
        'Content-Type' => 'application/json',
        'X-Channel-Type' => 'woocommerce'
    );

    // API Endpoint old api http://demo.cardivo.com/api/v1/gift_cards/redeem
    $api_endpoint = 'https://app.cardivo.com/api/v1/gift_cards/'.$gift_card_number.'/redeem'; // Replace with the actual API endpoint

    error_log("API header : " . $header);

    // Send the POST request to the API
    $response = wp_remote_post($api_endpoint, array(
        'headers' => $header,
        'body' => $body_redeme,
    ));

    if (is_wp_error($response)) {
        error_log("API Error: " . $response->get_error_message());
    } else {
        $response_body = wp_remote_retrieve_body($response);
        error_log("API Response: " . $response_body);
    }

    // Check if the request was successful
    if (!is_wp_error($response)) {
        // Process the response data if needed
        $response_body = wp_remote_retrieve_body($response);
    } else {
        error_log('response body is here ' . $response_body);
        // Log an error or handle the error scenario
        error_log('Error sending data to redeem API: ' . $response->get_error_message());
    }

    $order = wc_get_order($order_id);

    // Check if the order amount is zero
    if ($order->get_total() == 0) {
        // Update the order status to 'processing' if the amount is zero
        $order->update_status('processing');
    }
}

add_action('wp_ajax_remove_cardivo_gift_card', 'remove_cardivo_gift_card');
add_action('wp_ajax_nopriv_remove_cardivo_gift_card', 'remove_cardivo_gift_card');

function remove_cardivo_gift_card() {
    // Unset the session
    WC()->session->__unset('gift_card_value');
    wp_die();
}


// Unset Cardivo gift card after order completion
add_action('woocommerce_checkout_order_processed', 'unset_cardivo_gift_card_after_order');
function unset_cardivo_gift_card_after_order($order_id) {
    WC()->session->__unset('gift_card_value');
}

// Unset session on user page visit
add_action('template_redirect', 'unset_session_on_page_visit');
function unset_session_on_page_visit() {
    if (is_user_logged_in()) {
        WC()->session->__unset('gift_card_value');
    }
}