<?php
namespace orderflow;

use orderflow\Courier\Courier;

class Courier_Rate_Partial_Payment {
    use \orderflow\Traits\Courier;
    private $threshold;
    private $partial_payment_amount;
    private $enabled;
    private $enabled_zero_rate;

    public function __construct() {
        $this->enabled = get_option('ads_enable_partial_payment', false);
        $this->enabled_zero_rate = get_option('ads_enable_partial_payment_zero_rate', false);
        $this->threshold = get_option('ads_courier_rate_threshold', 70);
        $this->partial_payment_amount = get_option('ads_partial_payment_amount', 100);

        $this->threshold = apply_filters('courier_rate_threshold', $this->threshold);
        $this->partial_payment_amount = apply_filters('courier_partial_payment_amount', $this->partial_payment_amount);

        if ($this->enabled) {
            add_action('wp_ajax_orderflow_check_courier_rate', array($this, 'check_courier_rate_ajax'));
            add_action('wp_ajax_nopriv_orderflow_check_courier_rate', array($this, 'check_courier_rate_ajax'));
            add_filter('woocommerce_available_payment_gateways', array($this, 'filter_payment_gateways'));
            add_action('woocommerce_cart_totals_after_order_total', array($this, 'display_partial_payment_breakdown'));
            add_action('woocommerce_review_order_after_order_total', array($this, 'display_partial_payment_breakdown'));
            add_action('woocommerce_checkout_order_processed', array($this, 'save_partial_payment_details'), 1, 1);
            add_action('woocommerce_admin_order_data_after_billing_address', array($this, 'display_admin_payment_details'));
            add_action('woocommerce_email_after_order_table', array($this, 'add_email_payment_details'), 10, 3);
            add_action('wp_footer', array($this, 'output_inline_script'));


            add_filter('woocommerce_cart_get_total', array($this, 'modify_cart_total_for_checkout'), 10, 1);
        }
    }
    public function modify_cart_total_for_checkout($total) {
        if (is_checkout() && !is_wc_endpoint_url()) {
            if (!WC()->session->has_session()) {
                WC()->session->set_customer_session_cookie(true);
            }
            $rate = WC()->session->get('courier_rate');
            // Updated condition: rate must be between 1 and threshold
            if ($rate !== null && $rate <= $this->threshold && $rate != 0) {
                $details = WC()->session->get('partial_payment_details');
                if ($details) {
                    return $details['partial_amount'];
                }
            }
        }
        return $total;
    }


    // 2. Output JavaScript directly in footer
    public function output_inline_script() {
        if (!function_exists('is_checkout') || !is_checkout()) {
            return;
        }
        ?>
        <script type="text/javascript">
            jQuery(document).ready(function($) {
                var phoneField = $('#billing_phone, #billing-phone');
                var typingTimer;
                var typingDelay = 800; // Wait 800ms after user stops typing before sending request

                function checkCourierRate() {
                    var phone = phoneField.val().trim();
                    if (phone.length >= 10) {
                        $.ajax({
                            type: 'POST',
                            url: '<?php echo admin_url('admin-ajax.php'); ?>',
                            data: {
                                action: 'orderflow_check_courier_rate',
                                phone: phone,
                                security: '<?php echo wp_create_nonce('courier_rate_nonce'); ?>'
                            },
                            success: function(response) {
                                console.log('res', response);
                                
                                if (response.success) {
                                    $('body').trigger('update_checkout');
                                }
                            }
                        });
                    }
                }

                // Detect typing in real-time
                // Every time the user types, reset the timer.
                // If the user stops typing for "typingDelay" ms, send the AJAX request.
                phoneField.on('input', function(e) {
                    clearTimeout(typingTimer);
                    typingTimer = setTimeout(checkCourierRate, typingDelay);
                });

                if (phoneField.val()) { checkCourierRate(); }
                
            });
        </script>
        <?php
    }

    // 3. AJAX Handler - Courier Rate Check
    public function check_courier_rate_ajax() {
        check_ajax_referer('courier_rate_nonce', 'security');
        if (!WC()->session->has_session()) {
            WC()->session->set_customer_session_cookie(true);
        }
        $phone = sanitize_text_field($_POST['phone']);
        $rate = $this->get_courier_rate_by_phone($phone);
        if ($rate === false) {
            wp_send_json_error('API call failed');
        }
        WC()->session->set('courier_rate', $rate);
        $cart_total = WC()->cart->total;
        $partial_payment = $this->partial_payment_amount;
        if ($cart_total < $partial_payment) $partial_payment = $cart_total;
        $remaining_payment = $cart_total - $partial_payment;

        // Updated condition: rate must be between 1 and threshold
        if ($rate !== null && $rate <= $this->threshold) {
            // Allowed for partial payment, so set details
            WC()->session->set('partial_payment_details', array(
                'partial_amount' => $partial_payment,
                'remaining_amount' => $remaining_payment
            ));
        } else {
            // Not allowed, so unset details
            WC()->session->__unset('partial_payment_details');
        }

        // Updated COD availability logic
        $can_cod = ($rate === null || $rate > $this->threshold);
        if ($rate == 0 && $this->enabled_zero_rate) {
            $can_cod = false;
        }


        // error_log("AJAX Courier rate for phone {$phone}: {$rate}%");
        // error_log("AJAX Courier rate for phone {$phone}: {$this->threshold}%");

        wp_send_json_success(array(
            'rate' => $rate,
            'can_cod' => $can_cod,
            'cart_total' => wc_price($cart_total),
            'partial_payment' => wc_price($partial_payment),
            'remaining_payment' => wc_price($remaining_payment)
        ));
    }

    // 4. Payment Gateway Filter - COD Control
    public function filter_payment_gateways($available_gateways) {
        if (function_exists('is_checkout') && is_checkout() && !is_wc_endpoint_url()) {
            if (!WC()->session->has_session()) {
                WC()->session->set_customer_session_cookie(true);
            }
            $rate = WC()->session->get('courier_rate');
            // Updated condition: rate must be between 1 and threshold
            if ($rate !== null && $rate <= $this->threshold && $rate != 0) {
                unset($available_gateways['cod']);
            }

            // Zero rate handling
            if ($rate == 0 && $this->enabled_zero_rate) {
                unset($available_gateways['cod']);
            }
        }
        return $available_gateways;
    }

    // 5. Show partial payment breakdown in totals section
    public function display_partial_payment_breakdown() {
        if (!WC()->session->has_session()) {
            WC()->session->set_customer_session_cookie(true);
        }
        $rate = WC()->session->get('courier_rate');
        // Updated condition: rate must be between 1 and threshold
        if ($rate === null || $rate > $this->threshold ) return;

        // Zero rate handling
        if ($rate == 0 && !$this->enabled_zero_rate) {
            return;
        }

        $details = WC()->session->get('partial_payment_details');
        if (!$details) {
            // Fallback calculation if not present
            $cart_total = WC()->cart->total;
            $partial_payment = $this->partial_payment_amount;
            if ($cart_total < $partial_payment) $partial_payment = $cart_total;
            $remaining_payment = $cart_total - $partial_payment;
        } else {
            $partial_payment = $details['partial_amount'];
            $remaining_payment = $details['remaining_amount'];
        }

        // Display breakdown in totals table
        ?>
        <tr class="order-partial-payment">
            <th><?php echo get_option('ads_partial_label_one', 'এখন পরিশোধ করুন'); ?></th>
            <td><?php echo wc_price($partial_payment); ?></td>
        </tr>
        <tr class="order-remaining-payment">
            <th><?php echo get_option('ads_partial_label_two', 'ডেলিভারিতে পরিশোধ করুন'); ?></th>
            <td><?php echo wc_price($remaining_payment); ?></td>
        </tr>
        <style>
            tr.order-total {
                display: none;
            }
        </style>
        <?php
    }

    // 6. Save payment details to order meta
    public function save_partial_payment_details($order_id) {
        $order = wc_get_order($order_id);
        $partial_details = WC()->session->get('partial_payment_details');
        $rate = WC()->session->get('courier_rate');
        // Updated condition: rate must be between 1 and threshold
        if ($partial_details && $rate !== null && $rate <= $this->threshold && $rate != 0) {
            $order->update_meta_data('_partial_payment_amount', $partial_details['partial_amount']);
            $order->update_meta_data('_remaining_payment_amount', $partial_details['remaining_amount']);
            $order->update_meta_data('_has_partial_payment', 'yes');
            $remaining_amount = $order->get_meta('_remaining_payment_amount');
            $order->set_total($remaining_amount);
            $order->save();
            WC()->session->__unset('partial_payment_details');
        }
    }

    // 7. Display payment details in admin panel
    public function display_admin_payment_details($order) {
        $partial_amount = $order->get_meta('_partial_payment_amount');
        $remaining_amount = $order->get_meta('_remaining_payment_amount');
        $has_partial = $order->get_meta('_has_partial_payment');
        if ($has_partial === 'yes') {
            echo '<h3>আংশিক পেমেন্ট বিবরণী</h3>';
            echo '<div class="partial-payment-info" style="background: #f8f9fa; padding: 15px; border-left: 4px solid #0073aa; margin-top: 15px;">';
            echo '<p><strong>এখন পরিশোধিত:</strong> ' . wc_price($partial_amount) . '</p>';
            if ($remaining_amount > 0) {
                echo '<p><strong>ডেলিভারিতে বাকি:</strong> ' . wc_price($remaining_amount) . '</p>';
                echo '<div class="notice notice-info" style="margin-top: 10px;"><p>কাস্টমার ডেলিভারির সময় বাকি পরিমাণ (' . wc_price($remaining_amount) . ') পরিশোধ করবে।</p></div>';
            } else {
                echo '<p><strong>সম্পূর্ণ পেমেন্ট সংগৃহীত:</strong> ডেলিভারিতে কোনো বাকি পেমেন্ট নেই।</p>';
            }
            echo '</div>';
        }
    }

    // 8. Display payment details in customer order emails
    public function add_email_payment_details($order, $sent_to_admin, $plain_text) {
        $partial_amount = $order->get_meta('_partial_payment_amount');
        $remaining_amount = $order->get_meta('_remaining_payment_amount');
        $has_partial = $order->get_meta('_has_partial_payment');
        if ($has_partial === 'yes') {
            echo '<h2 style="color: #0073aa; border-bottom: 1px solid #eee; padding-bottom: 10px;">পেমেন্ট তথ্য</h2>';
            echo '<div style="background: #f8f9fa; padding: 15px; border-radius: 4px; margin-bottom: 20px;">';
            echo '<p style="margin: 0 0 10px;"><strong>এখন পরিশোধিত:</strong> ' . wc_price($partial_amount) . '</p>';
            if ($remaining_amount > 0) {
                echo '<p style="margin: 0;"><strong>ডেলিভারিতে বাকি:</strong> ' . wc_price($remaining_amount) . '</p>';
                echo '<p style="margin: 15px 0 0; font-style: italic; color: #666;">অনুগ্রহ করে ডেলিভারির সময় বাকি পরিমাণটি প্রস্তুত রাখুন।</p>';
            } else {
                echo '<p style="margin: 0;"><strong>সম্পূর্ণ পেমেন্ট সংগৃহীত:</strong> ডেলিভারিতে কোনো বাকি পেমেন্ট নেই।</p>';
            }
            echo '</div>';
        }
    }
}