<?php
/**
* Plugin Name: Cardivo Digital Gift Cards
* License: GPLv2 or later
* Plugin URI: https://cardivo.com/woocommerce-plugin/visit-plugin-site/
* Version: 0.6
* Description: Let your customers redeem gift cards easily on your WooCommerce store. Works with a Cardivo account. 
* Author: Cardivo
* Author URI: https://cardivo.co/woocommerce-plugin/author-link/ 
* Requires at least: 6.0
* Tested up to: 6.4.2
* WC tested up to: 8.4.0
* WC requires at least: 5.0
*/

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

define('CARDIVO_PATH', untrailingslashit(plugin_dir_path( __FILE__ )) );
define('CARDIVO_PATH_INNER', plugin_dir_path( __FILE__ ));

// Ensure WooCommerce is active
if (!in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {
    return;
}

// make sure woocommerce exists
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
    add_action('plugins_loaded', 'woocommerce_cardivo_init');
}

add_action( 'before_woocommerce_init', function() {
  if ( class_exists( \Automattic\WooCommerce\Utilities\FeaturesUtil::class ) ) {
    \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'custom_order_tables', __FILE__, true );
  }
} );

function woocommerce_cardivo_init() {
    // Classic editor checkout flow 
    include_once CARDIVO_PATH . "/classes/cardivo/cardivo-gateway.php";
}

//setting link on plugin listing
function cardivo_settings_link($links) {
  $settings_link = '<a href="options-general.php?page=cardivo-settings">Settings</a>'; 
  array_unshift($links, $settings_link); 
  return $links; 
}
$plugin = plugin_basename(__FILE__); 
add_filter("plugin_action_links_$plugin", 'cardivo_settings_link' );


// Enqueue assets for the WooCommerce Blocks Editor
add_action( 'wp_enqueue_scripts', 'custom_coupon_block_frontend_assets' );
function custom_coupon_block_frontend_assets() {
    if ( function_exists( 'is_checkout' ) && is_checkout() ) {
        wp_enqueue_script(
            'custom-coupon-blocks-script',
            plugin_dir_url( __FILE__ ) . 'assets/js/custom-coupon-blocks.js',
            array( 'wp-element', 'wp-i18n', 'wp-plugins', 'wc-blocks-checkout', 'jquery' ),
            '1.0',
            true
        );

        wp_localize_script( 'custom-coupon-blocks-script', 'ajax_object', array(
            'ajax_url' => admin_url( 'admin-ajax.php' ),
        ) );

        wp_enqueue_style(
            'custom-coupon-block-style',
            plugin_dir_url( __FILE__ ) . 'assets/css/style.css',
            array(),
            '1.2.0'
        );
    }
}

add_action('wp_ajax_apply_gift_card', 'apply_gift_card_handler');
add_action('wp_ajax_nopriv_apply_gift_card', 'apply_gift_card_handler');

function apply_gift_card_handler() {
    // Sanitize and validate input
    $gift_card_code = isset($_POST['giftCardCode']) ? sanitize_text_field($_POST['giftCardCode']) : null;
    $api_key = get_option('cardivo_authentication_code');

    if (!$gift_card_code) {
        wp_send_json_error(array(
            'message' => __('Gift card code is missing.', 'custom-coupon-plugin'),
        ));
    }

    WC()->session->set('gift_card_number', $gift_card_code);

    // API Request old api http://demo.cardivo.com/api/v1/gift_cards/status
    $response = wp_remote_get('https://app.cardivo.com/api/v1/gift_cards/'.$gift_card_code.'/status', array(
        'headers' => array(
            'Authorization' => 'Bearer ' . $api_key,
            'X-Channel-Type'  => 'woocommerce',
        ),
    ));

    // Handle API errors
    if (is_wp_error($response)) {
        error_log('API Error: ' . $response->get_error_message());
        wp_send_json_error(array(
            'message' => __('Error connecting to gift card API.', 'custom-coupon-plugin'),
        ));
    }

    // Parse response
    $response_data = json_decode(wp_remote_retrieve_body($response), true);

    if (!$response_data || ($response_data['status'] ?? '') !== 'valid') {
        wp_send_json_error(array(
            'message' => __('Invalid or expired gift card.', 'custom-coupon-plugin'),
        ));
    }

    // Validate currencies
    $wc_currency = get_woocommerce_currency();
    $gift_card_currency = html_entity_decode($response_data['currency'] ?? '');
    if ($wc_currency !== $gift_card_currency) {
        wp_send_json_error(array(
            'message' => sprintf(
                __('Gift card currency (%s) does not match store currency (%s).', 'custom-coupon-plugin'),
                $gift_card_currency,
                $wc_currency
            ),
        ));
    }

    // Calculate discount
    $cart_total = floatval(WC()->cart->get_subtotal());
    $gift_card_value = (float) ($response_data['value_balance'] ?? 0);
    $discount_amount = min($gift_card_value, $cart_total); // Critical fix here
    
    // Apply discount
    if ($discount_amount > 0) {
        //WC()->session->set('gift_card_value', $discount_amount);
        //WC()->cart->add_fee(__('Gift Card Discount', 'custom-coupon-plugin'), -$discount_amount, true);
        //WC()->cart->calculate_totals();
        WC()->session->set('gift_card_value', $discount_amount);
        WC()->session->set('gift_card_applied', true); // New session flag to track application

        // Recalculate totals after applying the gift card
        WC()->cart->calculate_totals();

        $updated_total = max(0, $cart_total - $discount_amount);

        wp_send_json_success(array(
            'message' => $response_data['checkout_description'] ?? __('Gift card applied successfully!', 'custom-coupon-plugin'),
            'gift_card_value' => number_format($discount_amount, 2),
            'gift_currency' => $gift_card_currency,
            'updated_total' => number_format($updated_total, 2),
            'raw_total' => $updated_total
        ));
    }

    wp_send_json_error(array(
        'message' => __('Gift card value is invalid or zero.', 'custom-coupon-plugin'),
    ));
}

// Apply discount only when session has a valid gift card value
add_action('woocommerce_cart_calculate_fees', function () {
    $discount_amount = WC()->session->get('gift_card_value', 0);
    $gift_card_applied = WC()->session->get('gift_card_applied', false);

    // Apply discount only if a valid gift card exists
    if (!empty($discount_amount) && $discount_amount > 0 && $gift_card_applied) {
        WC()->cart->add_fee(__('Cardivo gift card:', 'custom-coupon-plugin'), -$discount_amount, true);
    } else {
        // If no valid gift card exists, clear session
        WC()->session->__unset('gift_card_value');
        WC()->session->__unset('gift_card_applied');
    }
});

add_action('template_redirect', function () {
    if (is_checkout() && !is_wc_endpoint_url('order-received')) { 
        WC()->session->__unset('gift_card_value');
        WC()->session->__unset('gift_card_applied');
    }
});

// Reset session when the cart is emptied
add_action('woocommerce_cart_emptied', function () {
    WC()->session->__unset('gift_card_value');
    WC()->session->__unset('gift_card_applied');
});

add_filter('woocommerce_store_api_cart_totals', function ($totals) {
    $discount_amount = WC()->session->get('gift_card_value', 0);
    if ($discount_amount > 0) {
        $totals['total_price'] -= $discount_amount * 100; // Convert to cents
        $totals['total_price'] = max(0, $totals['total_price']); // Ensure non-negative total
    }
    return $totals;
});


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

function remove_cardivo_gift_card_handler() {
    $wc_currency = get_woocommerce_currency();
    // Clear the session value
    WC()->session->__unset('gift_card_value');
    WC()->session->__unset('gift_card_applied');
    WC()->cart->calculate_totals();

    // Restore the original cart total
    $cart_total = WC()->cart->get_total('edit');

    wp_send_json_success(array(
        'message'       => __('Gift card removed successfully.', 'custom-coupon-plugin'),
        'original_total'=> number_format($cart_total, 2),
        'gift_currency' => $wc_currency,
    ));
}


// Send data to redeem API after order processing
//add_action('woocommerce_checkout_order_processed', 'send_data_to_redeem_api', 10, 2);
add_action('woocommerce_store_api_checkout_order_processed', 'send_data_to_redeem_api', 10, 2);
function send_data_to_redeem_api($order, $request = []) {
    error_log("send_data_to_redeem_api_classic triggered for Order ID: " . $order);

    if (!$order instanceof WC_Order) {
        return;
    }

    // Ensure we don't process the same order multiple times
    static $already_processed = false;
    if ($already_processed) {
        return;
    }
    $already_processed = true;

    // Get order details
    global $wp;
    $current_page_url = home_url(add_query_arg(array(), $wp->request));
    // Get the necessary data from the order
    $gift_card_number = WC()->session->get('gift_card_number');
    $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();
    $cartTotal = WC()->cart->total;
    $purchase_total = $cartTotal + $gift_card_value;
    $total_excl_gift_card = WC()->cart->total;
    $wc_currency = get_woocommerce_currency();

    // Ensure there's a valid gift card
    if (empty($gift_card_number) || $gift_card_value <= 0) {
        return;
    }

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

    // API request old api http://demo.cardivo.com/api/v1/gift_cards/redeem
    $api_key = get_option('cardivo_authentication_code');
    $response = wp_remote_post('https://app.cardivo.com/api/v1/gift_cards/'.$gift_card_number.'/redeem', array(
        'headers' => array(
            'Authorization' => 'Bearer ' . $api_key,
            'Content-Type'  => 'application/json',
            'X-Channel-Type' => 'woocommerce'
        ),
        'body' => $body_redeme,
    ));
    // Log errors
    if (is_wp_error($response)) {
        error_log('Error sending gift card data: ' . $response->get_error_message());
    }

    // Clear gift card session after redeeming
    WC()->session->__unset('gift_card_value');
    WC()->session->__unset('gift_card_number');

    // Mark order as processing if total is zero
    //if ($order->get_total() == 0) {
        //$order->update_status('processing');
    //}
}
