<?php
/**
 * Plugin Name: Checkoutify Lite - Easy Checkout for WooCommerce
 * Plugin URI: https://checkoutify.net/
 * Description: Transform your WooCommerce checkout with modern, conversion-optimized templates. Features include customizable checkout designs, field manager, Skip cart option. Boost your sales with professional checkout experiences that convert visitors into customers.
 * Version: 1.1
 * Author: dominiio
 * Text Domain: checkoutify-lite
 * Domain Path: /languages
 * Requires at least: 6.0
 * Tested up to: 6.9
 * Requires PHP: 7.4
 * WC requires at least: 7.0
 * WC tested up to: 10.3.6
 * License: GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// Define plugin constants
define('CKFYLT25_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('CKFYLT25_PLUGIN_URL', plugin_dir_url(__FILE__));
define('CKFYLT25_PLUGIN_BASENAME', plugin_basename(__FILE__));

// Include necessary files
require_once CKFYLT25_PLUGIN_DIR . 'includes/admin-settings.php';
require_once CKFYLT25_PLUGIN_DIR . 'includes/checkout-override.php';
require_once CKFYLT25_PLUGIN_DIR . 'includes/class-ckfylt25-testimonial-display.php';
require_once CKFYLT25_PLUGIN_DIR . 'includes/class-ckfylt25-order-bump-display.php';

register_activation_hook(__FILE__, 'checkoutify_lite_on_activation');
function checkoutify_lite_on_activation() {
    if (!get_option('checkoutify_lite_activation_time')) {
        update_option('checkoutify_lite_activation_time', time());
    }
}

/**
 * Main plugin class
 * Handles plugin initialization, text domain loading, and core functionality
 */
class CKFYLT25_Checkoutify_Plugin {

    /**
     * Constructor - Initialize plugin hooks and actions
     */
    public function __construct() {
        add_action('init', array($this, 'ckfylt25_init_plugin'));
        add_action('plugins_loaded', array($this, 'ckfylt25_load_textdomain'));
        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);
            }
        });
        add_filter('plugin_action_links_' . CKFYLT25_PLUGIN_BASENAME, array($this, 'ckfylt25_add_plugin_action_links'));
        add_action('wp_enqueue_scripts', array($this, 'ckfylt25_enqueue_skip_cart_scripts'));
        add_filter('woocommerce_add_to_cart_redirect', array($this, 'ckfylt25_skip_cart_redirect'));
    }

    /**
     * Load plugin text domain for internationalization
     * Note: load_plugin_textdomain() is not needed for WordPress.org hosted plugins
     */
    public function ckfylt25_load_textdomain() {
        // Load plugin text domain for local/development environments and non-dotorg installs
        load_plugin_textdomain(
            'checkoutify-lite',
            false,
            dirname(plugin_basename(__FILE__)) . '/languages'
        );
    }

    /**
     * Initialize plugin components
     */
    public function ckfylt25_init_plugin() {
        if (!class_exists('WooCommerce')) {
            add_action('admin_notices', array($this, 'ckfylt25_woocommerce_missing_notice'));
            return;
        }
        new CKFYLT25_Admin_Settings();
        global $ckfylt25_checkout_override;
        $ckfylt25_checkout_override = new CKFYLT25_Checkout_Override();
        new CKFYLT25_Testimonial_Display();
        new CKFYLT25_Order_Bump_Display();
    }

    /**
     * Add action links to plugin list page
     * 
     * @param array $links Existing plugin action links
     * @return array Modified plugin action links
     */
    public function ckfylt25_add_plugin_action_links($links) {
        $settings_link = '<a href="' . esc_url(admin_url('admin.php?page=checkoutify-settings')) . '">' . esc_html__('Settings', 'checkoutify-lite') . '</a>';
        $upgrade_link = '<a href="https://checkoutify.net" target="_blank" style="color: #10b981; font-weight: 600;">' . esc_html__('Upgrade to Pro', 'checkoutify-lite') . '</a>';
        array_unshift($links, $settings_link);
        $links[] = $upgrade_link;
        return $links;
    }

    /**
     * Enqueue Skip Cart scripts and styles
     */
    public function ckfylt25_enqueue_skip_cart_scripts() {
        if (get_option('ckfylt25_skip_cart_enabled', false)) {
            wp_enqueue_script(
                'ckfylt25-skip-cart',
                CKFYLT25_PLUGIN_URL . 'assets/js/skip-cart.js',
                array('jquery'),
                '1.0.0',
                true
            );
            wp_localize_script('ckfylt25-skip-cart', 'ckfylt25SkipCartData', array(
                'enabled' => get_option('ckfylt25_skip_cart_enabled', false),
                'checkoutUrl' => wc_get_checkout_url(),
                'ajaxUrl' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('ckfylt25_skip_cart_nonce')
            ));
            wp_add_inline_script('ckfylt25-skip-cart', '
                window.ckfylt25SkipCartEnabled = ' . (get_option('ckfylt25_skip_cart_enabled', false) ? 'true' : 'false') . ';
                window.ckfylt25CheckoutUrl = "' . esc_js(wc_get_checkout_url()) . '";
            ');
        }
    }

    /**
     * Server-side redirect to checkout when Skip Cart is enabled
     * Ensures redirect works even when AJAX events are not fired
     */
    public function ckfylt25_skip_cart_redirect($url) {
        if (get_option('ckfylt25_skip_cart_enabled', false)) {
            return wc_get_checkout_url();
        }
        return $url;
    }

    /**
     * Display admin notice when WooCommerce is not active
     */
    public function ckfylt25_woocommerce_missing_notice() {
        ?>
        <div class="notice notice-error">
            <p><?php esc_html_e('Checkoutify - Easy Checkout for WooCommerce requires WooCommerce to be installed and active.', 'checkoutify-lite'); ?></p>
        </div>
        <?php
    }
}

// Initialize the plugin
new CKFYLT25_Checkoutify_Plugin();

/**
 * Add plugin meta links for WordPress.org compatibility
 * 
 * @param array $links Existing plugin meta links
 * @param string $file Plugin file path
 * @return array Modified plugin meta links
 */
function ckfylt25_checkoutify_plugin_meta($links, $file) {
    if (plugin_basename(__FILE__) === $file) {
        $links[] = '<a href="https://checkoutify.net" target="_blank">' . esc_html__('Documentation', 'checkoutify-lite') . '</a>';
        $links[] = '<a href="https://checkoutify.net" target="_blank">' . esc_html__('Changelog', 'checkoutify-lite') . '</a>';
    }
    return $links;
}
add_filter('plugin_row_meta', 'ckfylt25_checkoutify_plugin_meta', 10, 2);

// Add hook for testimonials
add_action('ckfylt25_after_order_summary', 'ckfylt25_display_default_testimonials');

/**
 * Display default testimonials section
 * This function is used as a fallback when testimonials are enabled but no custom testimonials are configured
 */
function ckfylt25_display_default_testimonials() {
    $testimonials_enabled = get_option('ckfylt25_enable_testimonials', false);
    if ($testimonials_enabled) {
        $testimonials = get_option('ckfylt25_testimonials', array());
        if (!empty($testimonials)) {
            echo '<div class="ckfylt25-testimonials-section">';
            echo '<h3>' . esc_html__('What Our Customers Say', 'checkoutify-lite') . '</h3>';
            echo '<div class="ckfylt25-testimonials-grid">';
            foreach ($testimonials as $testimonial) {
                echo '<div class="ckfylt25-testimonial">';
                if (!empty($testimonial['avatar'])) {
                    echo '<div class="ckfylt25-testimonial-avatar">';
                    echo '<img src="' . esc_url($testimonial['avatar']) . '" alt="' . esc_attr($testimonial['name']) . '">';
                    echo '</div>';
                }
                echo '<div class="ckfylt25-testimonial-content">';
                echo '<p class="ckfylt25-testimonial-text">"' . esc_html($testimonial['text']) . '"</p>';
                echo '<p class="ckfylt25-testimonial-name">- ' . esc_html($testimonial['name']) . '</p>';
                if (!empty($testimonial['title'])) {
                    echo '<p class="ckfylt25-testimonial-title">' . esc_html($testimonial['title']) . '</p>';
                }
                echo '</div>';
                echo '</div>';
            }
            echo '</div>';
            echo '</div>';
        }
    }
}

// Hook for before testimonials
add_action('ckfylt25_before_testimonials', 'ckfylt25_before_testimonials_section');

/**
 * Add content before testimonials section
 * This hook allows for additional content to be displayed before testimonials
 */
function ckfylt25_before_testimonials_section() {
    echo '<div class="ckfylt25-testimonials-intro" style="text-align: center;">';
    echo '</div>';
}

/**
 * Custom function to render shipping methods in Fluid template
 * This function provides a custom shipping methods display for specific templates
 */
function ckfylt25_render_shipping_methods() {
    if (!function_exists('WC')) {
        return;
    }
    $packages = WC()->shipping()->get_packages();
    if (empty($packages)) {
        WC()->cart->calculate_shipping();
        $packages = WC()->shipping()->get_packages();
    }
    $first = true;
    foreach ($packages as $i => $package) {
        $chosen_method = isset(WC()->session->chosen_shipping_methods[$i]) ? WC()->session->chosen_shipping_methods[$i] : '';
        $product_names = array();
        if (count($packages) > 1) {
            foreach ($package['contents'] as $item_id => $values) {
                $product_names[$item_id] = $values['data']->get_name() . ' &times;' . $values['quantity'];
            }
            $product_names = apply_filters('woocommerce_shipping_package_details_array', $product_names, $package);
        }
        $available_methods = $package['rates'];
        $show_package_details = count($packages) > 1;
        $package_details = implode(', ', $product_names);
        /* translators: %d: shipping package number */
        $package_name = apply_filters('woocommerce_shipping_package_name', ((($i + 1) > 1) ? sprintf(_x('Shipping %d', 'shipping packages', 'checkoutify-lite'), ($i + 1)) : _x('Shipping', 'shipping packages', 'checkoutify-lite')), $i, $package);
        $index = $i;
        $formatted_destination = WC()->countries->get_formatted_address($package['destination'], ', ');
        $has_calculated_shipping = WC()->customer->has_calculated_shipping();
        include CKFYLT25_PLUGIN_DIR . 'templates/Fluid/shipping-methods.php';
        do_action('woocommerce_review_order_after_shipping');
        $first = false;
    }
}

// AJAX function to get shipping methods
add_action('wp_ajax_ckfylt25_get_shipping_methods', 'ckfylt25_get_shipping_methods_ajax');
add_action('wp_ajax_nopriv_ckfylt25_get_shipping_methods', 'ckfylt25_get_shipping_methods_ajax');

/**
 * AJAX handler to get shipping methods
 * This function handles AJAX requests for shipping methods updates
 */
function ckfylt25_get_shipping_methods_ajax() {
    if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'woocommerce-update_order_review')) {
        wp_die( esc_html__( 'Invalid nonce', 'checkoutify-lite' ) );
    }
    if (!function_exists('WC')) {
        wp_send_json_error( __( 'WooCommerce is not available', 'checkoutify-lite' ) );
    }
    WC()->cart->calculate_shipping();
    $packages = WC()->shipping()->get_packages();
    if (empty($packages)) {
        wp_send_json_success(array(
            'html' => '<div class="shipping-no-methods">' . esc_html__('No shipping methods available for this address.', 'checkoutify-lite') . '</div>'
        ));
        return;
    }
    ob_start();
    do_action('woocommerce_review_order_before_shipping');
    ckfylt25_render_shipping_methods();
    do_action('woocommerce_review_order_after_shipping');
    $shipping_html = ob_get_clean();
    if (empty(trim($shipping_html))) {
        $shipping_html = '<div class="shipping-no-methods">' . esc_html__('No shipping methods available for this address.', 'checkoutify-lite') . '</div>';
    }
    wp_send_json_success(array(
        'html' => $shipping_html
    ));
}

// AJAX function to get sidebar totals
add_action('wp_ajax_ckfylt25_get_sidebar_totals', 'ckfylt25_get_sidebar_totals_ajax');
add_action('wp_ajax_nopriv_ckfylt25_get_sidebar_totals', 'ckfylt25_get_sidebar_totals_ajax');
add_action('wp_ajax_ckfylt25_get_sidebar_totals_simple', 'ckfylt25_get_sidebar_totals_simple_ajax');
add_action('wp_ajax_nopriv_ckfylt25_get_sidebar_totals_simple', 'ckfylt25_get_sidebar_totals_simple_ajax');

/**
 * AJAX handler to get sidebar totals
 * This function handles AJAX requests for sidebar totals updates
 */
function ckfylt25_get_sidebar_totals_ajax() {
    $nonce_valid = false;
    if (isset($_POST['nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'woocommerce-process_checkout')) {
        $nonce_valid = true;
    } elseif (isset($_POST['nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'woocommerce-update_order_review')) {
        $nonce_valid = true;
    } elseif (isset($_POST['nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'woocommerce-process_checkout')) {
        $nonce_valid = true;
    }
    if (!$nonce_valid) {
        wp_send_json_error( __( 'Invalid nonce', 'checkoutify-lite' ) );
        return;
    }
    if (!function_exists('WC')) {
        wp_send_json_error( __( 'WooCommerce is not available', 'checkoutify-lite' ) );
    }
    WC()->cart->calculate_totals();
    $sidebar_html = ckfylt25_generate_sidebar_totals();
    wp_send_json_success(array(
        'html' => $sidebar_html
    ));
}

/**
 * Alternative AJAX function without nonce for cases where nonce is not available
 * This function handles AJAX requests for sidebar totals without nonce verification
 */
function ckfylt25_get_sidebar_totals_simple_ajax() {
    if (!function_exists('WC')) {
        wp_send_json_error( __( 'WooCommerce is not available', 'checkoutify-lite' ) );
    }
    WC()->cart->calculate_totals();
    $sidebar_html = ckfylt25_generate_sidebar_totals_native();
    wp_send_json_success(array(
        'html' => $sidebar_html
    ));
}

/**
 * Function to generate sidebar totals with shipping included
 * This function creates HTML for the sidebar totals display
 * 
 * @return string HTML content for sidebar totals
 */
function ckfylt25_generate_sidebar_totals() {
    WC()->cart->calculate_shipping();
    WC()->cart->calculate_totals();
    ob_start();
    echo '<tr class="cart-subtotal">';
    echo '<th>' . esc_html__('Subtotal', 'checkoutify-lite') . '</th>';
    echo '<td>' . wp_kses_post(WC()->cart->get_cart_subtotal()) . '</td>';
    echo '</tr>';
    foreach (WC()->cart->get_coupons() as $code => $coupon) {
        echo '<tr class="cart-discount coupon-' . esc_attr(sanitize_title($code)) . '">';
        echo '<th>' . wp_kses_post(wc_cart_totals_coupon_label($coupon)) . '</th>';
        echo '<td>' . wp_kses_post(wc_cart_totals_coupon_html($coupon)) . '</td>';
        echo '</tr>';
    }
    if (WC()->cart->needs_shipping() && WC()->cart->show_shipping()) {
        $packages = WC()->shipping()->get_packages();
        $chosen_methods = WC()->session->get('chosen_shipping_methods');
        foreach ($packages as $i => $package) {
            $chosen_method = isset($chosen_methods[$i]) ? $chosen_methods[$i] : '';
            if ($chosen_method && isset($package['rates'][$chosen_method])) {
                $method = $package['rates'][$chosen_method];
                echo '<tr class="shipping">';
                echo '<th>' . esc_html__('Shipping', 'checkoutify-lite') . '</th>';
                echo '<td>' . wp_kses_post(wc_cart_totals_shipping_method_label($method)) . '</td>';
                echo '</tr>';
            } elseif (!empty($package['rates'])) {
                $first_method = reset($package['rates']);
                echo '<tr class="shipping">';
                echo '<th>' . esc_html__('Shipping', 'checkoutify-lite') . '</th>';
                echo '<td>' . wp_kses_post(wc_cart_totals_shipping_method_label($first_method)) . '</td>';
                echo '</tr>';
            }
        }
    }
    foreach (WC()->cart->get_fees() as $fee) {
        echo '<tr class="fee">';
        echo '<th>' . esc_html($fee->name) . '</th>';
        echo '<td>' . wp_kses_post(wc_cart_totals_fee_html($fee)) . '</td>';
        echo '</tr>';
    }
    if (wc_tax_enabled() && !WC()->cart->display_prices_including_tax()) {
        if ('itemized' === get_option('woocommerce_tax_total_display')) {
            foreach (WC()->cart->get_tax_totals() as $code => $tax) {
                echo '<tr class="tax-rate tax-rate-' . esc_attr(sanitize_title($code)) . '">';
                echo '<th>' . esc_html($tax->label) . '</th>';
                echo '<td>' . wp_kses_post($tax->formatted_amount) . '</td>';
                echo '</tr>';
            }
        } else {
            echo '<tr class="tax-total">';
            echo '<th>' . esc_html(WC()->countries->tax_or_vat()) . '</th>';
            echo '<td>' . wp_kses_post(wc_cart_totals_taxes_total_html()) . '</td>';
            echo '</tr>';
        }
    }
    $total = WC()->cart->get_total();
    $formatted_total = WC()->cart->get_cart_total();
    echo '<tr class="order-total">';
    echo '<th>' . esc_html__('TOTAL - Including Shipping', 'checkoutify-lite') . '</th>';
    echo '<td>' . wp_kses_post($formatted_total) . '</td>';
    echo '</tr>';
    $html = ob_get_clean();
    return $html;
}

/**
 * Alternative function that uses native WooCommerce template
 * This function generates sidebar totals using WooCommerce's native template
 * 
 * @return string HTML content for sidebar totals using native template
 */
function ckfylt25_generate_sidebar_totals_native() {
    WC()->cart->calculate_shipping();
    WC()->cart->calculate_totals();
    ob_start();
    wc_get_template('checkout/review-order.php', array('checkout' => WC()->checkout()));
    $order_summary_html = ob_get_clean();
    $order_summary_html = preg_replace('/<tr[^>]*class="[^"]*shipping[^"]*"[^>]*>.*?<\/tr>/is', '', $order_summary_html);
    return $order_summary_html;
}

