<?php
namespace orderflow\Admin;
use orderflow\Core\Base;
use orderflow\Courier\Courier;
use orderflow\Traits\Core;

class Courier_Details_Meta_Box extends Base {
    use Core;
    public function __construct() {
        if ( ! self::is_license_active()  ) {
            return;
        }
        // Add meta boxes for both HPOS and classic order edit screens
        add_action('add_meta_boxes', [$this, 'add_courier_details_meta_box'],99999999999999999);
        // Handle AJAX request for refreshing courier data
        add_action('wp_ajax_ads_refresh_courier_details', [$this, 'refresh_courier_details']);
        add_action('wp_ajax_nopriv_ads_refresh_courier_details', [$this, 'refresh_courier_details']);
        // Output inline CSS and JS on admin pages
        add_action('admin_head', [$this, 'output_inline_css']);
        add_action('admin_footer', [$this, 'output_inline_js']);
    }

    /**
     * Add meta boxes for both HPOS and classic order edit screens
     */
    public function add_courier_details_meta_box() {

        $fraud_checker_enabled = get_option('ads_enable_fraud_checker', false);
        if ( ! $fraud_checker_enabled ) {
            return;
        }
        // For HPOS order edit screen
        add_meta_box(
            'ads_courier_details_meta_box',
            __('Courier Details', 'orderflow'),
            [$this, 'render_courier_details_meta_box'],
            'woocommerce_page_wc-orders', // HPOS orders page hook
            'side',
            'high'
        );

        // For classic order edit screen
        add_meta_box(
            'ads_courier_details_meta_box',
            __('Courier Details', 'orderflow'),
            [$this, 'render_courier_details_meta_box'],
            'shop_order', // Classic order post type
            'side',
            'high'
        );
    }

    /**
     * Render the courier details meta box content
     */
    public function render_courier_details_meta_box($post_or_order_object) {
        // Get order object depending on context
        if (is_a($post_or_order_object, 'WP_Post')) {
            $order = wc_get_order($post_or_order_object->ID);
        } else {
            $order = $post_or_order_object;
        }

        if (!$order) {
            return;
        }

        $order_id = $order->get_id();
        $phone_number = $this->normalize_phone_number($order->get_billing_phone());

        // Get courier history from cache or DB (no API calls here)
        $courier_history = Courier::get_courier_history_from_cache($phone_number);

        // Get courier history data
        if(!$courier_history){
            $courier_history = $phone_number ? Courier::fetch_courier_history_with_cache($phone_number) : [];
        }

        // Calculate totals
        $totals = $this->calculate_courier_totals($courier_history);

        // Get courier logos
        $logos = $this->get_courier_logos();

        ?>
        <div id="ads-courier-details-wrapper" data-order-id="<?php echo esc_attr($order_id); ?>">
            <div class="ads-meta-box-inside">
                <button class="ads-refresh-courier-data">
                    <span class="dashicons dashicons-update"></span>
                    <span class="ads-button-text">রিফ্রেশ কুরিয়ার ডেটা</span>
                </button>

                <div class="ads-courier-table-container">
                    <table class="ads-courier-table">
                        <thead>
                        <tr>
                            <th>কুরিয়ার</th>
                            <th>মোট</th>
                            <th>সফল</th>
                            <th>রিটান</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($logos as $courier => $logo) : ?>
                            <tr>
                                <td>
                                    <div class="ads-courier-logo">
                                        <img src="<?php echo esc_url($logo); ?>" alt="<?php echo esc_attr($courier); ?>">
                                    </div>
                                </td>
                                <td><?php echo esc_html($courier_history['response'][$courier]['data']['total'] ?? 0); ?></td>
                                <td class="ads-success-col"><?php echo esc_html($courier_history['response'][$courier]['data']['success'] ?? 0); ?></td>
                                <td class="ads-cancel-col"><?php echo esc_html($courier_history['response'][$courier]['data']['cancel'] ?? 0); ?></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                        <tfoot>
                        <tr>
                            <td>মোট</td>
                            <td><?php echo esc_html($totals['total']); ?></td>
                            <td class="ads-success-col"><?php echo esc_html($totals['success']); ?></td>
                            <td class="ads-cancel-col"><?php echo esc_html($totals['cancel']); ?></td>
                        </tr>
                        </tfoot>
                    </table>
                </div>

                <div class="ads-courier-stats">
                    <div class="ads-stat-item ads-stat-total">
                        <span class="ads-stat-label">মোট অর্ডার</span>
                        <span class="ads-stat-value"><?php echo esc_html($totals['total']); ?></span>
                    </div>
                    <div class="ads-stat-item ads-stat-success">
                        <span class="ads-stat-label">সফল</span>
                        <span class="ads-stat-value"><?php echo esc_html($totals['success']); ?></span>
                    </div>
                    <div class="ads-stat-item ads-stat-cancel">
                        <span class="ads-stat-label">রিটান</span>
                        <span class="ads-stat-value"><?php echo esc_html($totals['cancel']); ?></span>
                    </div>
                    <div class="ads-stat-item ads-stat-percent">
                        <span class="ads-stat-label">সফলতার হার</span>
                        <span class="ads-stat-value"><?php echo esc_html($totals['success_percent']); ?>%</span>
                    </div>
                </div>

                <div class="ads-courier-progress-bar">
                    <div class="ads-progress-track">
                        <div class="ads-progress-segment ads-success-segment" style="width: <?php echo esc_attr($totals['success_percent']); ?>%;"></div>
                        <div class="ads-progress-segment ads-cancel-segment" style="width: <?php echo esc_attr(100 - $totals['success_percent']); ?>%;"></div>
                    </div>
                    <div class="ads-progress-labels">
                        <span class="ads-success-label">সফল: <?php echo esc_html($totals['success_percent']); ?>%</span>
                        <span class="ads-cancel-label">রিটান: <?php echo esc_attr(100 - $totals['success_percent']); ?>%</span>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }

    /**
     * Calculate totals from courier history
     */
    private function calculate_courier_totals($courier_history) {
        $total_orders = isset($courier_history['total_parcel']) ? $courier_history['total_parcel'] : 0;
        $total_success = isset($courier_history['success_parcel']) ? $courier_history['success_parcel'] : 0;
        $total_cancel = isset($courier_history['cancel_parcel']) ? $courier_history['cancel_parcel'] : 0;

        $success_percent = ($total_orders > 0) ? round(($total_success / $total_orders) * 100, 1) : 0;

        return [
            'total' => $total_orders,
            'success' => $total_success,
            'cancel' => $total_cancel,
            'success_percent' => $success_percent
        ];
    }

    /**
     * Get courier logos
     */
    private function get_courier_logos() {
        $plugin_url = plugin_dir_url(dirname(__FILE__));

        return [
            'pathao' => ADS_PLUGIN_URL . 'assets/img/pathao-logo.png',
            'steadfast' => ADS_PLUGIN_URL . 'assets/img/steadfast-logo.png',
            'redx' => ADS_PLUGIN_URL . 'assets/img/redx-logo.png',
        ];
    }

    /**
     * Handle AJAX request for refreshing courier data
     */
    public function refresh_courier_details() {
        check_ajax_referer('ads_refresh_courier_details_nonce', 'nonce');

        $order_id = isset($_POST['order_id']) ? intval($_POST['order_id']) : 0;

        if (!$order_id) {
            wp_send_json_error(['message' => 'Invalid order ID']);
        }

        $order = wc_get_order($order_id);
        if (!$order) {
            wp_send_json_error(['message' => 'Order not found']);
        }

        $phone_number = $this->normalize_phone_number($order->get_billing_phone());

        if (!$phone_number || strlen($phone_number) != 11) {
            wp_send_json_error(['message' => 'Invalid phone number']);
        }

        // Force refresh courier history
        $courier_history = Courier::fetch_courier_history_from_apis($phone_number);

        if (empty($courier_history)) {
            wp_send_json_error(['message' => 'Failed to fetch courier data']);
        }

        // Update database
        global $wpdb;
        $table_name = $wpdb->prefix . 'ads_customers_data';

        // Check if record exists
        $existing_data = $wpdb->get_row(
            $wpdb->prepare(
                "SELECT * FROM {$table_name} WHERE data_type = %s AND data_value = %s",
                'phone_number',
                $phone_number
            )
        );

        if ($existing_data) {
            // Update existing record
            $wpdb->update(
                $table_name,
                [
                    'data_courier_history' => json_encode($courier_history),
                    'data_courier_history_last_update_time' => current_time('mysql'),
                ],
                [
                    'data_type' => 'phone_number',
                    'data_value' => $phone_number,
                ],
                [
                    '%s',
                    '%s',
                ],
                [
                    '%s',
                    '%s',
                ]
            );

            // set transient cache
            set_transient(
                'ads_courier_history_' . md5($phone_number),
                [
                    'data_type'  => 'phone_number',
                    'data_value' => $phone_number,
                    'data_courier_history' => json_encode($courier_history),
                    'data_courier_history_last_update_time' => current_time('mysql'),
                ],
                48 * HOUR_IN_SECONDS
            );
        } else {
            // Insert new record
            $wpdb->insert(
                $table_name,
                [
                    'data_type' => 'phone_number',
                    'data_value' => $phone_number,
                    'data_courier_history' => json_encode($courier_history),
                    'data_courier_history_last_update_time' => current_time('mysql'),
                ],
                [
                    '%s',
                    '%s',
                    '%s',
                    '%s',
                ]
            );

            // set transient cache
            set_transient(
                'ads_courier_history_' . md5($phone_number),
                [
                    'data_type'  => 'phone_number',
                    'data_value' => $phone_number,
                    'data_courier_history' => json_encode($courier_history),
                    'data_courier_history_last_update_time' => current_time('mysql'),
                ],
                48 * HOUR_IN_SECONDS
            );
        }

        // Calculate totals
        $totals = $this->calculate_courier_totals($courier_history);

        // Get courier logos
        $logos = $this->get_courier_logos();

        // Generate HTML for the table
        ob_start();
        ?>
        <div class="ads-courier-table-container">
            <table class="ads-courier-table">
                <thead>
                <tr>
                    <th>কুরিয়ার</th>
                    <th>মোট</th>
                    <th>সফল</th>
                    <th>রিটান</th>
                </tr>
                </thead>
                <tbody>
                <?php foreach ($logos as $courier => $logo) : ?>
                    <tr>
                        <td>
                            <div class="ads-courier-logo">
                                <img src="<?php echo esc_url($logo); ?>" alt="<?php echo esc_attr($courier); ?>">
                            </div>
                        </td>
                        <td><?php echo esc_html($courier_history['response'][$courier]['data']['total'] ?? 0); ?></td>
                        <td class="ads-success-col"><?php echo esc_html($courier_history['response'][$courier]['data']['success'] ?? 0); ?></td>
                        <td class="ads-cancel-col"><?php echo esc_html($courier_history['response'][$courier]['data']['cancel'] ?? 0); ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
                <tfoot>
                <tr>
                    <td>মোট</td>
                    <td><?php echo esc_html($totals['total']); ?></td>
                    <td class="ads-success-col"><?php echo esc_html($totals['success']); ?></td>
                    <td class="ads-cancel-col"><?php echo esc_html($totals['cancel']); ?></td>
                </tr>
                </tfoot>
            </table>
        </div>

        <div class="ads-courier-stats">
            <div class="ads-stat-item ads-stat-total">
                <span class="ads-stat-label">মোট অর্ডার</span>
                <span class="ads-stat-value"><?php echo esc_html($totals['total']); ?></span>
            </div>
            <div class="ads-stat-item ads-stat-success">
                <span class="ads-stat-label">সফল</span>
                <span class="ads-stat-value"><?php echo esc_html($totals['success']); ?></span>
            </div>
            <div class="ads-stat-item ads-stat-cancel">
                <span class="ads-stat-label">রিটান</span>
                <span class="ads-stat-value"><?php echo esc_html($totals['cancel']); ?></span>
            </div>
            <div class="ads-stat-item ads-stat-percent">
                <span class="ads-stat-label">সফলতার হার</span>
                <span class="ads-stat-value"><?php echo esc_html($totals['success_percent']); ?>%</span>
            </div>
        </div>

        <div class="ads-courier-progress-bar">
            <div class="ads-progress-track">
                <div class="ads-progress-segment ads-success-segment" style="width: <?php echo esc_attr($totals['success_percent']); ?>%;"></div>
                <div class="ads-progress-segment ads-cancel-segment" style="width: <?php echo esc_attr(100 - $totals['success_percent']); ?>%;"></div>
            </div>
            <div class="ads-progress-labels">
                <span class="ads-success-label">সফল: <?php echo esc_html($totals['success_percent']); ?>%</span>
                <span class="ads-cancel-label">রিটান: <?php echo esc_attr(100 - $totals['success_percent']); ?>%</span>
            </div>
        </div>
        <?php
        $table_html = ob_get_clean();

        wp_send_json_success([
            'html' => $table_html,
            'totals' => $totals
        ]);
    }

    /**
     * Output inline CSS for the meta box
     */
    public function output_inline_css() {
        // Only load on order edit pages
        $screen = get_current_screen();
        if (
            !$screen ||
            ($screen->id !== 'shop_order' && $screen->id !== 'woocommerce_page_wc-orders')
        ) {
            return;
        }
        ?>
        <style>
            /* Main container */
            #ads-courier-details-wrapper {
                font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
            }

            /* Enhanced Refresh Button */
            .ads-refresh-courier-data {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                border: none;
                border-radius: 50px;
                padding: 12px 24px;
                font-weight: 600;
                font-size: 14px;
                display: inline-flex;
                align-items: center;
                gap: 10px;
                box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
                transition: all 0.3s ease;
                margin-bottom: 20px;
                cursor: pointer;
                position: relative;
                overflow: hidden;
                outline: none;
                width: 100%;
                justify-content: center;
            }

            /* Button shine effect */
            .ads-refresh-courier-data::before {
                content: '';
                position: absolute;
                top: 0;
                left: -100%;
                width: 100%;
                height: 100%;
                background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
                transition: left 0.5s;
            }

            .ads-refresh-courier-data:hover::before {
                left: 100%;
            }

            .ads-refresh-courier-data:hover {
                background: linear-gradient(135deg, #5a67d8 0%, #6b46c1 100%);
                transform: translateY(-3px);
                box-shadow: 0 7px 20px rgba(102, 126, 234, 0.5);
            }

            .ads-refresh-courier-data:active {
                transform: translateY(1px);
                box-shadow: 0 2px 10px rgba(102, 126, 234, 0.3);
            }

            .ads-refresh-courier-data:disabled {
                background: linear-gradient(135deg, #a0aec0 0%, #718096 100%);
                cursor: not-allowed;
                transform: none;
                box-shadow: none;
            }

            .ads-refresh-courier-data .dashicons {
                font-size: 20px;
                height: 20px;
                width: 20px;
                line-height: 20px;
            }

            .ads-button-text {
                letter-spacing: 0.5px;
            }

            /* Table container */
            .ads-courier-table-container {
                border-radius: 12px;
                overflow: hidden;
                box-shadow: 0 10px 25px rgba(0, 0, 0, 0.08);
                margin-bottom: 20px;
                border: 1px solid rgba(0, 0, 0, 0.05);
            }

            /* Table */
            .ads-courier-table {
                width: 100%;
                border-collapse: collapse;
                background: white;
            }

            .ads-courier-table th,
            .ads-courier-table td {
                padding: 16px;
                text-align: center;
                border: none;
            }

            .ads-courier-table th {
                background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
                color: white;
                font-weight: 700;
                text-transform: uppercase;
                font-size: 13px;
                letter-spacing: 0.7px;
                text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
            }

            .ads-courier-table tbody tr {
                border-bottom: 1px solid #e2e8f0;
                transition: all 0.3s ease;
            }

            .ads-courier-table tbody tr:hover {
                background-color: #f7fafc;
                transform: scale(1.01);
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
            }

            .ads-courier-table tbody tr:last-child {
                border-bottom: none;
            }

            .ads-courier-table tfoot td {
                background: linear-gradient(135deg, #a1c4fd 0%, #c2e9fb 100%);
                color: #2d3748;
                font-weight: 700;
                font-size: 14px;
            }

            /* Courier logo */
            .ads-courier-logo {
                display: flex;
                justify-content: center;
                align-items: center;
                height: 50px;
            }

            .ads-courier-logo img {
                max-height: 36px;
                max-width: 90px;
                filter: grayscale(20%);
                transition: all 0.3s ease;
            }

            .ads-courier-logo img:hover {
                filter: grayscale(0%);
                transform: scale(1.1);
            }

            /* Success and cancel columns */
            .ads-success-col {
                color: #38a169;
                font-weight: 700;
            }

            .ads-cancel-col {
                color: #e53e3e;
                font-weight: 700;
            }

            /* Stats cards */
            .ads-courier-stats {
                display: grid;
                grid-template-columns: repeat(2, 1fr);
                gap: 15px;
                margin-bottom: 20px;
            }

            .ads-stat-item {
                background: white;
                border-radius: 12px;
                padding: 16px;
                box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                transition: all 0.3s ease;
                border: 1px solid rgba(0, 0, 0, 0.05);
            }

            .ads-stat-item:hover {
                transform: translateY(-5px);
                box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
            }

            .ads-stat-label {
                font-size: 13px;
                color: #718096;
                margin-bottom: 6px;
                font-weight: 500;
            }

            .ads-stat-value {
                font-size: 22px;
                font-weight: 800;
            }

            .ads-stat-total .ads-stat-value {
                color: #4299e1;
            }

            .ads-stat-success .ads-stat-value {
                color: #38a169;
            }

            .ads-stat-cancel .ads-stat-value {
                color: #e53e3e;
            }

            .ads-stat-percent .ads-stat-value {
                color: #805ad5;
            }

            /* Progress bar */
            .ads-courier-progress-bar {
                background: white;
                border-radius: 12px;
                padding: 20px;
                box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
                border: 1px solid rgba(0, 0, 0, 0.05);
            }

            .ads-progress-track {
                height: 20px;
                background: #edf2f7;
                border-radius: 10px;
                overflow: hidden;
                display: flex;
                margin-bottom: 12px;
                box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.1);
            }

            .ads-progress-segment {
                height: 100%;
                transition: width 1.5s ease-in-out;
            }

            .ads-success-segment {
                background: linear-gradient(90deg, #38a169, #68d391);
                box-shadow: 0 0 10px rgba(56, 161, 105, 0.5);
            }

            .ads-cancel-segment {
                background: linear-gradient(90deg, #e53e3e, #fc8181);
                box-shadow: 0 0 10px rgba(229, 62, 62, 0.5);
            }

            .ads-progress-labels {
                display: flex;
                justify-content: space-between;
                font-size: 13px;
            }

            .ads-success-label {
                color: #38a169;
                font-weight: 700;
            }

            .ads-cancel-label {
                color: #e53e3e;
                font-weight: 700;
            }

            /* Notices */
            .ads-courier-notice {
                margin: 15px 0;
                padding: 16px 20px;
                border-radius: 10px;
                font-weight: 600;
                display: flex;
                align-items: center;
                gap: 12px;
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
            }

            .ads-courier-notice.success {
                background: linear-gradient(135deg, #d4edda, #c3e6cb);
                color: #155724;
                border-left: 5px solid #28a745;
            }

            .ads-courier-notice.error {
                background: linear-gradient(135deg, #f8d7da, #f5c6cb);
                color: #721c24;
                border-left: 5px solid #dc3545;
            }

            .ads-courier-notice .dashicons {
                font-size: 20px;
            }

            /* Spinning animation */
            .dashicons.spinning {
                animation: rotation 2s infinite linear;
                display: inline-block;
            }

            @keyframes rotation {
                from { transform: rotate(0deg); }
                to { transform: rotate(359deg); }
            }
        </style>
        <?php
    }

    /**
     * Output inline JavaScript for the meta box
     */
    public function output_inline_js() {
        // Only load on order edit pages
        $screen = get_current_screen();
        if (
            !$screen ||
            ($screen->id !== 'shop_order' && $screen->id !== 'woocommerce_page_wc-orders')
        ) {
            return;
        }
        ?>
        <script>
            jQuery(document).ready(function($) {
                $('.ads-refresh-courier-data').on('click', function(e) {
                    e.preventDefault();

                    var $button = $(this);
                    var $wrapper = $('#ads-courier-details-wrapper');
                    var orderId = $wrapper.data('order-id');

                    // Show loading state
                    $button.prop('disabled', true);
                    $button.find('.dashicons').addClass('spinning');

                    // Remove any existing notices
                    $('.ads-courier-notice').remove();

                    $.ajax({
                        url: '<?php echo admin_url('admin-ajax.php'); ?>',
                        type: 'POST',
                        data: {
                            action: 'ads_refresh_courier_details',
                            nonce: '<?php echo wp_create_nonce('ads_refresh_courier_details_nonce'); ?>',
                            order_id: orderId
                        },
                        success: function(response) {
                            console.log('response', response);
                            
                            if (response.success) {
                                // Update the content
                                $wrapper.find('.ads-courier-table-container, .ads-courier-stats, .ads-courier-progress-bar').remove();
                                $wrapper.find('.ads-meta-box-inside').append(response.data.html);

                                // Show success message
                                var $message = $('<div class="ads-courier-notice success"><span class="dashicons dashicons-yes"></span> Courier data refreshed successfully!</div>');
                                $wrapper.before($message);

                                // Auto dismiss after 3 seconds
                                setTimeout(function() {
                                    $message.fadeOut(function() {
                                        $(this).remove();
                                    });
                                }, 3000);
                            } else {
                                // Show error message
                                var $message = $('<div class="ads-courier-notice error"><span class="dashicons dashicons-no"></span> Error: ' + response.data.message + '</div>');
                                $wrapper.before($message);
                            }
                        },
                        error: function() {
                            // Show error message
                            var $message = $('<div class="ads-courier-notice error"><span class="dashicons dashicons-no"></span> An error occurred while refreshing courier data.</div>');
                            $wrapper.before($message);
                        },
                        complete: function() {
                            // Reset button state
                            $button.prop('disabled', false);
                            $button.find('.dashicons').removeClass('spinning');
                        }
                    });
                });
            });
        </script>
        <?php
    }
}