<?php
/**
 * CargoHub Free Admin Class
 * 
 * Handles admin panel interface and functionality for FREE version
 */

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

class CargoHub_Free_Admin {
    
    /**
     * Database instance
     */
    private $database;
    
    /**
     * Constructor
     */
    public function __construct() {
        $this->database = new CargoHub_Free_Database();
        $this->init_hooks();
    }
    
    /**
     * Initialize hooks
     */
    private function init_hooks() {
        add_action('admin_menu', array($this, 'add_admin_menu'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
        
        
        // WooCommerce hooks - only if WooCommerce is active
        if (class_exists('WooCommerce')) {
            // Admin hooks (CPT and HPOS)
            add_action('woocommerce_admin_order_data_after_order_details', array($this, 'add_tracking_box'));
            add_action('woocommerce_process_shop_order_meta', array($this, 'save_tracking_data'), 10, 2);
            add_action('woocommerce_admin_process_shop_order_meta', array($this, 'save_tracking_data'), 10, 2);
            
            // Frontend my-account hooks
            add_filter('woocommerce_my_account_my_orders_columns', array($this, 'add_orders_columns'));
            add_action('woocommerce_my_account_my_orders_column_carrier', array($this, 'orders_column_carrier'));
            add_action('woocommerce_my_account_my_orders_column_tracking', array($this, 'orders_column_tracking'));
            add_filter('woocommerce_my_account_my_orders_actions', array($this, 'add_tracking_action'), 10, 2);
            
            // Frontend CSS for my-account
            add_action('wp_enqueue_scripts', array($this, 'enqueue_frontend_scripts'));
        }
    }


    /**
     * Add admin menu
     */
    public function add_admin_menu() {
        add_menu_page(
            __('CargoHub', 'cargohub-kargo-takip'),
            __('CargoHub', 'cargohub-kargo-takip'),
            'manage_woocommerce',
            'cargohub-kargo-takip',
            array($this, 'admin_page'),
            'dashicons-networking',
            56
        );
        
        // Removed SMS submenu to comply with WP.org guidelines (no locked local features)
        
        add_submenu_page(
            'cargohub-kargo-takip',
            __('Kargo Firmalarını Yönet', 'cargohub-kargo-takip'),
            __('Kargo Firmaları', 'cargohub-kargo-takip'),
            'manage_woocommerce',
            'cargohub-kargo-takip-carriers',
            array($this, 'carriers_page')
        );
    }
    
    /**
     * Enqueue admin scripts and styles
     */
    public function enqueue_admin_scripts($hook) {
        $load_scripts = false;
        
        // Check if we're on CargoHub pages
        if (strpos($hook, 'cargohub-kargo-takip') !== false) {
            $load_scripts = true;
        }
        
        // Check if we're on shop order pages (legacy CPT and HPOS compatibility)
        if (is_admin()) {
            // Check post type if available
            if (function_exists('get_post_type')) {
                $post_type = get_post_type();
                if ($post_type === 'shop_order') {
                    $load_scripts = true;
                }
            }
            
            // Also check if we're on order edit page via hook
            if (strpos($hook, 'post.php') !== false || strpos($hook, 'post-new.php') !== false) {
                global $post;
                if (isset($post) && $post->post_type === 'shop_order') {
                    $load_scripts = true;
                }
            }
            
            // Check for WooCommerce order pages by screen (including HPOS wc-orders)
            $screen = get_current_screen();
            if ($screen && ($screen->post_type === 'shop_order' || $screen->id === 'shop_order' || strpos($screen->id, 'wc-orders') !== false || strpos($screen->id, 'shop_order') !== false)) {
                $load_scripts = true;
            }
        }
        
        if ($load_scripts) {
            wp_enqueue_style(
                'cargohub-kargo-takip-admin',
                CARGOHUB_FREE_PLUGIN_URL . 'assets/css/admin.css',
                array(),
                CARGOHUB_FREE_VERSION
            );
            
            wp_enqueue_script(
                'cargohub-kargo-takip-admin',
                CARGOHUB_FREE_PLUGIN_URL . 'assets/js/admin.js',
                array('jquery'),
                CARGOHUB_FREE_VERSION,
                true
            );
            
            wp_localize_script('cargohub-kargo-takip-admin', 'cargohub_ajax', array(
                'ajax_url' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('cargohub_free_nonce'),
                'messages' => array(
                    'saved' => __('Tracking information saved successfully!', 'cargohub-kargo-takip'),
                    'deleted' => __('Tracking information deleted successfully!', 'cargohub-kargo-takip'),
                    'error' => __('An error occurred. Please try again.', 'cargohub-kargo-takip'),
                    'confirm_delete' => __('Are you sure you want to delete this tracking information?', 'cargohub-kargo-takip'),
                    'email_sending' => __('E-posta gönderiliyor...', 'cargohub-kargo-takip'),
                    'email_sent' => __('Takip e-postası başarıyla gönderildi!', 'cargohub-kargo-takip'),
                    'email_error' => __('E-posta gönderilirken hata oluştu.', 'cargohub-kargo-takip')
                )
            ));
        }
    }

    /**
     * Display admin page
     */
    public function admin_page() {
        ?>
        <div class="wrap" style="position: relative;">

            <h1><?php esc_html_e('🛠 CargoHub Yönetim Paneli', 'cargohub-kargo-takip'); ?></h1>
            <div class="cargohub-free-welcome">
                <p><?php esc_html_e('🇹🇷 Eklenti yönetim paneline hoşgeldiniz. Türk geliştiriciler tarafından kodlanan bu eklentiyi beğeneceğinizi umud ediyoruz.🔖', 'cargohub-kargo-takip'); ?></p>
                <div class="pro-notice" style="background: #f0f6fc; border: 1px solid #0073aa; border-radius: 8px; padding: 20px; margin: 20px 0;">
                    <p><strong><?php echo esc_html__('🚀 PRO satın alarak sms gönderimini ve bazı özelliklerin kilidini açabilirsiniz.', 'cargohub-kargo-takip'); ?></strong></p>
                    <p> <a href="<?php echo esc_url(CARGOHUB_PRO_URL); ?>" target="_blank" style="background: #0073aa; color: white; padding: 8px 16px; text-decoration: none; border-radius: 4px;">&nbsp;<?php esc_html_e('PRO Versiyona Geçin', 'cargohub-kargo-takip'); ?></a></p>
                </div>
            </div>
           
        </div>

        
<div class="wrap" style="position: relative; text-align: center;">
    <img src="<?php echo esc_url( CARGOHUB_FREE_PLUGIN_URL . 'assets/img/cargo-hub-plugin-banner.png' ); ?>" alt="CargoHub logo" style="max-height: 190px; display: block; margin: 0 auto;" />
</div>


        <?php
    }

    /**
     * Display SMS settings page (with promotion)
     */
    public function sms_settings_page() {
        ?>
        <div class="wrap">
            <h1><?php esc_html_e('SMS Ayarları', 'cargohub-kargo-takip'); ?></h1>
            <p><?php echo esc_html__('SMS bildirimleri PRO bir özelliktir. Bu özelliğin kilidini açmak için lütfen versiyonu yükseltin.', 'cargohub-kargo-takip'); ?></p>
            
                <div style="display: flex; align-items: center; justify-content: space-around; padding: 30px; background: #f9f9f9; border: 2px dashed #ddd; border-radius: 12px; margin-top: 20px; position: relative;">
                    <div style="text-align: center; opacity: 0.5; filter: grayscale(100%);">
<img src="<?php echo esc_url( CARGOHUB_FREE_PLUGIN_URL . 'assets/img/vatansms-logo.svg' ); ?>" alt="Vatan SMS" style="width: 120px; height: 60px; object-fit: contain; margin: 0 auto 10px;" />
                        <p style="margin: 0; color: #666;">&nbsp;<?php esc_html_e('Vatan SMS Entegrasyonu', 'cargohub-kargo-takip'); ?></p>
                    </div>
                    
                    <div style="text-align: center; opacity: 0.5; filter: grayscale(100%);">
<img src="<?php echo esc_url( CARGOHUB_FREE_PLUGIN_URL . 'assets/img/netgsm-logo.svg' ); ?>" alt="Netgsm" style="width: 120px; height: 60px; object-fit: contain; margin: 0 auto 10px;" />
                        <p style="margin: 0; color: #666;">&nbsp;<?php esc_html_e('Netgsm SMS Entegrasyonu', 'cargohub-kargo-takip'); ?></p>
                    </div>
                
                <div style="text-align: center;">
                    <div style="background: linear-gradient(135deg, #0073aa, #005a87); color: white; padding: 15px 25px; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.2);">
                        <h3 style="margin: 0 0 10px 0; color:white; font-size: 18px;">&nbsp;<?php esc_html_e('🚀 SMS\'in Gücünü Açın!', 'cargohub-kargo-takip'); ?></h3>
                        <p style="margin: 0 0 15px 0; font-size: 14px; opacity: 0.9;">&nbsp;<?php esc_html_e('Müşterilerinize Ürünün Kargoya Verildiğine Dair Anlık Sms Gitsin', 'cargohub-kargo-takip'); ?></p>
                        <a href="<?php echo esc_url(CARGOHUB_PRO_URL); ?>" target="_blank" style="background: white; color: #0073aa; padding: 10px 20px; border-radius: 5px; text-decoration: none; font-weight: bold; display: inline-block;">
                            <?php esc_html_e('PRO Satın Alın', 'cargohub-kargo-takip'); ?>
                        </a>
                    </div>
                </div>
            </div>
            
            <div style="margin-top: 20px; padding: 15px; background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px;">
                <h4 style="margin: 0 0 10px 0; color: #856404;">&nbsp;<?php esc_html_e('💡 PRO Özelliklerden Bazıları:', 'cargohub-kargo-takip'); ?></h4>
                <ul style="margin: 0; color: #856404;">
                    <li><?php esc_html_e('✅ Vatan SMS & Netgsm SMS Entegrasyonu', 'cargohub-kargo-takip'); ?></li>
                    <li><?php esc_html_e('✅ Kargoya Verildiğinde Otomatik SMS Mesajı', 'cargohub-kargo-takip'); ?></li>
                    <li><?php esc_html_e('✅ Özelleştirilebilir SMS Mesaj Alanı', 'cargohub-kargo-takip'); ?></li>
                    <li><?php esc_html_e('✅ Limitsiz Kargo Firması Ekleme ve Düzenleme', 'cargohub-kargo-takip'); ?></li>
                    <li><?php esc_html_e('✅ Girilen Kargo Bilgilerini Panelden Kolayca Düzenleme', 'cargohub-kargo-takip'); ?></li>
                    <li><?php esc_html_e('✅ Geliştirici Desteği, Güncellemeler', 'cargohub-kargo-takip'); ?></li>
                    <li><?php esc_html_e('✅ Kargo Bildirim E-Postasında Reklamsız Bildiri', 'cargohub-kargo-takip'); ?></li>
                </ul>
            </div>
        </div>
        <?php
    }

    /**
     * Display carriers page
     */
    public function carriers_page() {
        // Handle form submissions
        $nonce_add = isset($_POST['carrier_nonce']) ? sanitize_text_field( wp_unslash($_POST['carrier_nonce']) ) : '';
        if (isset($_POST['add_carrier'])) {
            if (wp_verify_nonce($nonce_add, 'add_carrier_nonce')) {
            $this->handle_add_carrier();
            }
        }
        
        $nonce_del = isset($_POST['carrier_nonce']) ? sanitize_text_field( wp_unslash($_POST['carrier_nonce']) ) : '';
        if (isset($_POST['delete_carrier'])) {
            if (wp_verify_nonce($nonce_del, 'delete_carrier_nonce')) {
            $this->handle_delete_carrier();
            }
        }
        
        $carriers = get_option('cargohub_free_custom_carriers', array());
        
        ?>
        <div class="wrap">
            <h1><?php esc_html_e('Kargoları Yönetin', 'cargohub-kargo-takip'); ?> <span style="color: #666; font-size: 14px;">(<?php echo esc_html(count($carriers)); ?>)</span></h1>
            
            <!-- Add New Carrier Form -->
            <div style="background: #f9f9f9; border: 1px solid #ddd; border-radius: 8px; padding: 20px; margin: 20px 0;">
                <h3><?php esc_html_e('Kargo Firması Ekle', 'cargohub-kargo-takip'); ?></h3>
                <form method="post" action="">
                    <?php wp_nonce_field('add_carrier_nonce', 'carrier_nonce'); ?>
                    <table class="form-table">
                        <tr>
                             <th><label for="carrier_name"><?php esc_html_e('Kargo Firma Adı', 'cargohub-kargo-takip'); ?></label></th>
                            <td><input type="text" id="carrier_name" name="carrier_name" class="regular-text" required /></td>
                        </tr>
                        <tr>
                             <th><label for="carrier_code"><?php esc_html_e('Kargo Kısa Kodu', 'cargohub-kargo-takip'); ?></label></th>
                            <td><input type="text" id="carrier_code" name="carrier_code" class="regular-text" placeholder="<?php esc_attr_e('yurtici, aras gibi boşluksuz ve TR kullanmadan', 'cargohub-kargo-takip'); ?>" required /></td>
                        </tr>
                        <tr>
                             <th><label for="tracking_url"><?php esc_html_e('Kargo Takip URL', 'cargohub-kargo-takip'); ?></label></th>
                            <td><input type="url" id="tracking_url" name="tracking_url" class="regular-text" placeholder="<?php esc_attr_e('https://example.com/track?code=', 'cargohub-kargo-takip'); ?>" required /></td>
                        </tr>
                        <tr>
                             <th><label for="carrier_color"><?php esc_html_e('Kargo Renk Teması', 'cargohub-kargo-takip'); ?></label></th>
                            <td><input type="color" id="carrier_color" name="carrier_color" value="#0073aa" /></td>
                        </tr>
                    </table>
                    <p class="submit">
                        <input type="submit" name="add_carrier" class="button-primary" value="<?php echo esc_attr__('Kargo Firması Ekle', 'cargohub-kargo-takip'); ?>" />
                    </p>
                </form>
            </div>
            
            <!-- Current Carriers List -->
            <?php if (!empty($carriers)): ?>
            <div style="background: white; border: 1px solid #ddd; border-radius: 8px; margin: 20px 0;">
                <h3 style="padding: 15px 20px; margin: 0; border-bottom: 1px solid #eee;">&nbsp;<?php esc_html_e('Kargo Firmalarınız', 'cargohub-kargo-takip'); ?></h3>
                <div style="padding: 20px;">
                    <?php foreach ($carriers as $code => $carrier): ?>
                    <div style="display: flex; align-items: center; justify-content: space-between; padding: 15px; border: 1px solid #eee; border-radius: 6px; margin-bottom: 10px;">
                        <div style="display: flex; align-items: center; gap: 15px;">
                            <div style="width: 40px; height: 40px; background: <?php echo esc_attr($carrier['color']); ?>; border-radius: 6px; display: flex; align-items: center; justify-content: center; color: white; font-weight: bold; font-size: 12px;">
                                <?php echo esc_html(strtoupper(substr($carrier['name'], 0, 3))); ?>
                            </div>
                            <div>
                                <strong><?php echo esc_html($carrier['name']); ?></strong>
                                <br><small style="color: #666; "><?php esc_html_e('Kod:', 'cargohub-kargo-takip'); ?> <?php echo esc_html($code); ?></small>
                            </div>
                        </div>
                        <div>
                            <form method="post" style="display: inline;" onsubmit="return confirm('<?php echo esc_attr__('Kargo firmasını silmek istiyor musunuz?', 'cargohub-kargo-takip'); ?>')">
                                <?php wp_nonce_field('delete_carrier_nonce', 'carrier_nonce'); ?>
                                <input type="hidden" name="carrier_code" value="<?php echo esc_attr($code); ?>" />
                                <button type="submit" name="delete_carrier" style="background: #dc3545; color: white; border: none; padding: 8px 12px; border-radius: 4px; cursor: pointer; font-size: 12px;">&nbsp;<?php echo esc_html__('Sil', 'cargohub-kargo-takip'); ?></button>
                            </form>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php else: ?>
            <div style="text-align: center; padding: 40px; color: #666;">
                <p><?php esc_html_e('Hiç kargo firması eklenmemiş. Haydi bir tane ekleyin ve başlayın.', 'cargohub-kargo-takip'); ?></p>
            </div>
            <?php endif; ?>
        </div>
        <?php
    }
    
    /**
     * Handle add carrier form submission
     */
    private function handle_add_carrier() {
        // Check user capability
        if (!current_user_can('manage_woocommerce')) {
            return;
        }

        // Verify nonce
        $nonce = isset($_POST['carrier_nonce']) ? sanitize_text_field( wp_unslash($_POST['carrier_nonce']) ) : '';
        if (! wp_verify_nonce($nonce, 'add_carrier_nonce')) {
            return;
        }

        // Sanitize and validate input
        $carrier_name = isset($_POST['carrier_name']) ? sanitize_text_field( wp_unslash($_POST['carrier_name']) ) : '';
        $carrier_code = isset($_POST['carrier_code']) ? sanitize_key( wp_unslash($_POST['carrier_code']) ) : '';
        $tracking_url = isset($_POST['tracking_url']) ? esc_url_raw( wp_unslash($_POST['tracking_url']) ) : '';
        $carrier_color = isset($_POST['carrier_color']) ? sanitize_hex_color( wp_unslash($_POST['carrier_color']) ) : '';
        
        if (empty($carrier_name) || empty($carrier_code) || empty($tracking_url)) {
            add_action('admin_notices', function() {
                echo '<div class="notice notice-error"><p>' . esc_html__('Lütfen gerekli alanları doldurun.', 'cargohub-kargo-takip') . '</p></div>';
            });
            return;
        }
        
        // Get existing carriers
        $carriers = get_option('cargohub_free_custom_carriers', array());
        
        // Check if carrier code already exists
        if (isset($carriers[$carrier_code])) {
            add_action('admin_notices', function() {
                echo '<div class="notice notice-error"><p>' . esc_html__('A carrier with this code already exists.', 'cargohub-kargo-takip') . '</p></div>';
            });
            return;
        }
        
        // Add new carrier
        $carriers[$carrier_code] = array(
            'name' => $carrier_name,
            'tracking_url' => $tracking_url,
            'color' => $carrier_color ?: '#0073aa',
            'logo' => '', // No logo in FREE version
            'created_at' => current_time('mysql')
        );
        
        // Save carriers
        update_option('cargohub_free_custom_carriers', $carriers);
        
        // Clear cache
        wp_cache_delete("carrier_{$carrier_code}", 'cargohub_free_carriers');
        
        // Success message
        add_action('admin_notices', function() use ($carrier_name) {
            echo '<div class="notice notice-success"><p>' . sprintf(
                /* translators: %s: eklenen kargo firma adı. */
                esc_html__('Carrier "%s" added successfully!', 'cargohub-kargo-takip'),
                esc_html($carrier_name)
            ) . '</p></div>';
        });
    }
    
    /**
     * Handle delete carrier form submission
     */
    private function handle_delete_carrier() {
        // Check user capability
        if (!current_user_can('manage_woocommerce')) {
            return;
        }

        // Verify nonce
        $nonce = isset($_POST['carrier_nonce']) ? sanitize_text_field( wp_unslash($_POST['carrier_nonce']) ) : '';
        if (! wp_verify_nonce($nonce, 'delete_carrier_nonce')) {
            return;
        }

        $carrier_code = isset($_POST['carrier_code']) ? sanitize_key( wp_unslash($_POST['carrier_code']) ) : '';
        
        if (empty($carrier_code)) {
            add_action('admin_notices', function() {
            echo '<div class="notice notice-error"><p>' . esc_html__('Invalid carrier code.', 'cargohub-kargo-takip') . '</p></div>';
            });
            return;
        }
        
        // Get existing carriers
        $carriers = get_option('cargohub_free_custom_carriers', array());
        
        if (!isset($carriers[$carrier_code])) {
            add_action('admin_notices', function() {
            echo '<div class="notice notice-error"><p>' . esc_html__('Carrier not found.', 'cargohub-kargo-takip') . '</p></div>';
            });
            return;
        }
        
        $carrier_name = $carriers[$carrier_code]['name'];
        
        // Remove carrier
        unset($carriers[$carrier_code]);
        
        // Save carriers
        update_option('cargohub_free_custom_carriers', $carriers);
        
        // Clear cache
        wp_cache_delete("carrier_{$carrier_code}", 'cargohub_free_carriers');
        
        // Success message
        add_action('admin_notices', function() use ($carrier_name) {
            echo '<div class="notice notice-success"><p>' . sprintf(
                /* translators: %s: silinen kargo firma adı. */
                esc_html__('Carrier "%s" deleted successfully!', 'cargohub-kargo-takip'),
                esc_html($carrier_name)
            ) . '</p></div>';
        });
    }
    
    /**
     * Add tracking box to WooCommerce order edit page
     */
    public function add_tracking_box($order) {
        // Check if order is valid
        if (!$order || !is_object($order)) {
            return;
        }
        
        // Get order ID
        $order_id = method_exists($order, 'get_id') ? $order->get_id() : $order->id;
        
        // Get existing tracking data
        $tracking_data = $this->database->get_tracking_data($order_id);
        $carriers = CargoHub_Free_Carriers::get_carrier_options();
        
        // Don't show if no carriers available
        if (empty($carriers)) {
            ?>
            <div class="cargohub-free-tracking-box"><br>
                <h3><?php esc_html_e('📦 Kargo Takip', 'cargohub-kargo-takip'); ?></h3>
                <p><?php esc_html_e('Hiç kargo firması eklenmemiş. Hemen bir tane ekleyin.', 'cargohub-kargo-takip'); ?></p>
                <a href="<?php echo esc_url( admin_url('admin.php?page=cargohub-kargo-takip-carriers') ); ?>" class="button">&nbsp;<?php esc_html_e('Ekle', 'cargohub-kargo-takip'); ?></a>
            </div>
            <?php
            return;
        }
        
        ?>
        <div class="cargohub-free-tracking-container">
            <div class="cargohub-free-tracking-box">
                <div class="cargohub-tracking-header"><br>
                    <h3 class="cargohub-tracking-title">&nbsp;<?php esc_html_e('📦 Kargo Takibi', 'cargohub-kargo-takip'); ?></h3>
                    <div class="cargohub-tracking-subtitle">&nbsp;<?php esc_html_e('Siparişinize ait kargo bilgilerini buradan yönetebilirsiniz', 'cargohub-kargo-takip'); ?></div>
                </div>
                
                <div class="cargohub-tracking-form">
                    <div class="cargohub-form-row">
                        <div class="cargohub-form-group">
                            <label for="cargohub_carrier" class="cargohub-label"><?php esc_html_e('Kargo Firması', 'cargohub-kargo-takip'); ?></label>
                            <select name="cargohub_carrier" id="cargohub_carrier" class="cargohub-select">
                                <option value=""><?php esc_html_e('Kargo Firması Seç', 'cargohub-kargo-takip'); ?></option>
                                <?php foreach ($carriers as $code => $name): ?>
                                    <option value="<?php echo esc_attr($code); ?>" <?php selected($tracking_data['carrier'] ?? '', $code); ?>>
                                        <?php echo esc_html($name); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    
                    <div class="cargohub-form-row">
                        <div class="cargohub-form-group">
                            <label for="cargohub_tracking_number" class="cargohub-label"><?php esc_html_e('Takip Numarası', 'cargohub-kargo-takip'); ?></label>
                            <input type="text" name="cargohub_tracking_number" id="cargohub_tracking_number" 
                                   value="<?php echo esc_attr($tracking_data['tracking_number'] ?? ''); ?>" 
                                   class="cargohub-input" 
                                    placeholder="<?php echo esc_attr__('Örn: 123456789', 'cargohub-kargo-takip'); ?>" />
                        </div>
                    </div>
                    
                    <?php if (!empty($tracking_data['tracking_number'])): ?>
                    <div class="cargohub-tracking-info">
                        <div class="cargohub-info-item">
                            <strong class="cargohub-info-label"><?php esc_html_e('Kargo Takip Sayfası:', 'cargohub-kargo-takip'); ?></strong>
                            <div class="cargohub-info-content">
                                <?php 
                                $tracking_url = CargoHub_Free_Carriers::get_tracking_url($tracking_data['carrier'], $tracking_data['tracking_number']);
                                if ($tracking_url): 
                                ?>
                                    <a href="<?php echo esc_url($tracking_url); ?>" target="_blank" class="cargohub-tracking-link">
                                        <?php echo esc_html($tracking_url); ?>
                                        <span class="dashicons dashicons-external"></span>
                                    </a>
                                <?php else: ?>
                                    <span class="cargohub-no-tracking"><?php esc_html_e('Takip sayfası bulunamadı', 'cargohub-kargo-takip'); ?></span>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
                
                <div class="cargohub-tracking-footer">
                    <small class="cargohub-footer-note">
                        <?php esc_html_e(' Kargo bilgilerini kaydettikten sonra müşteriye otomatik email gönderilecektir.', 'cargohub-kargo-takip'); ?>
                    </small>
                </div>
            </div>
        </div>
        <?php
    }
    
    /**
     * Save tracking data when order is updated
     */
    public function save_tracking_data($order_id, $order = null) {
        try {
            // Check if our fields are set
            if (!isset($_POST['cargohub_carrier'])) {
                return;
            }

            // Verify nonce for tracking save if provided in form
            $nonce = isset($_POST['cargohub_free_nonce']) ? sanitize_text_field( wp_unslash($_POST['cargohub_free_nonce']) ) : '';
            if ($nonce && ! wp_verify_nonce($nonce, 'cargohub_free_nonce')) {
                return;
            }
            
            // Additional security checks for HPOS compatibility
            if (!current_user_can('edit_shop_orders')) {
                if (class_exists('CargoHub_Free_Logger')) {
                    CargoHub_Free_Logger::warning('User lacks permission to save tracking data', array(
                        'user_id' => get_current_user_id(),
                        'order_id' => $order_id
                    ));
                }
                return;
            }
            
            // Validate order ID
            $order_id = absint($order_id);
            if (empty($order_id)) {
                if (class_exists('CargoHub_Free_Logger')) {
                    CargoHub_Free_Logger::warning('Invalid order ID in save_tracking_data');
                }
                return;
            }
            
            $carrier = isset($_POST['cargohub_carrier']) ? sanitize_text_field( wp_unslash($_POST['cargohub_carrier']) ) : '';
            $tracking_number = isset($_POST['cargohub_tracking_number']) ? sanitize_text_field( wp_unslash($_POST['cargohub_tracking_number']) ) : '';
            $shipped_date = isset($_POST['cargohub_shipped_date']) ? sanitize_text_field( wp_unslash($_POST['cargohub_shipped_date']) ) : '';
            
            // If carrier is empty, delete tracking data
            if (empty($carrier)) {
                $this->database->delete_tracking_data($order_id);
                return;
            }
            
            // Validate carrier exists
            if (!CargoHub_Free_Carriers::is_valid_carrier($carrier)) {
                if (class_exists('CargoHub_Free_Logger')) {
                    CargoHub_Free_Logger::warning('Invalid carrier code', array(
                        'carrier' => $carrier,
                        'order_id' => $order_id
                    ));
                }
                return;
            }
            
            // Prepare tracking data
            $tracking_data = array(
                'order_id' => $order_id,
                'carrier' => $carrier,
                'tracking_number' => $tracking_number,
                'shipped_date' => $shipped_date,
                'status' => !empty($tracking_number) ? 'kargoya_verildi' : 'pending'
            );
            
            // Save tracking data first
            $result = $this->database->save_tracking_data($tracking_data);
            
            if (!$result && class_exists('CargoHub_Free_Logger')) {
                CargoHub_Free_Logger::error('Failed to save tracking data in admin', $tracking_data);
            }
            
            // Always trigger email action if we have a tracking number - email class will handle duplicates with hash
            if ($result && !empty($tracking_number)) {
                if (class_exists('CargoHub_Free_Logger')) {
                    CargoHub_Free_Logger::info("Admin triggered email for order {$order_id} with tracking: {$tracking_number}");
                }
                do_action('cargohub_free_tracking_added', $order_id, $carrier, $tracking_number);
            }
            
        } catch (Exception $e) {
            if (class_exists('CargoHub_Free_Logger')) {
                CargoHub_Free_Logger::critical('Exception in admin save_tracking_data: ' . $e->getMessage(), array(
                    'order_id' => $order_id,
                    'trace' => $e->getTraceAsString()
                ));
            }
            // Intentionally not using error_log in production
        }
    }
    
    /**
     * Add carrier and tracking columns to my account orders
     */
    public function add_orders_columns($columns) {
        // Insert after order status
        $new_columns = array();
        foreach ($columns as $key => $column) {
            $new_columns[$key] = $column;
            if ($key === 'order-status') {
                $new_columns['carrier'] = __('Carrier', 'cargohub-kargo-takip');
                $new_columns['tracking'] = __('Tracking', 'cargohub-kargo-takip');
            }
        }
        return $new_columns;
    }
    
    /**
     * Display carrier column content
     */
    public function orders_column_carrier($order) {
        $order_id = method_exists($order, 'get_id') ? $order->get_id() : $order->id;
        $tracking_data = $this->database->get_tracking_data($order_id);
        
        if (!empty($tracking_data['carrier'])) {
            $carrier_name = CargoHub_Free_Carriers::get_carrier_name($tracking_data['carrier']);
            $carrier_color = CargoHub_Free_Carriers::get_carrier_color($tracking_data['carrier']);
            
            echo '<span style="background: ' . esc_attr($carrier_color) . '; color: white; padding: 2px 8px; border-radius: 3px; font-size: 12px;">';
            echo esc_html($carrier_name);
            echo '</span>';
        } else {
            echo '<span style="color: #999;">' . esc_html__('Kargoya Verilmedi', 'cargohub-kargo-takip') . '</span>';
        }
    }
    
    /**
     * Display tracking column content
     */
    public function orders_column_tracking($order) {
        $order_id = method_exists($order, 'get_id') ? $order->get_id() : $order->id;
        $tracking_data = $this->database->get_tracking_data($order_id);
        
        if (!empty($tracking_data['tracking_number'])) {
            $tracking_url = CargoHub_Free_Carriers::get_tracking_url($tracking_data['carrier'], $tracking_data['tracking_number']);
            
            if ($tracking_url) {
                echo '<a href="' . esc_url($tracking_url) . '" target="_blank" style="color: #0073aa; text-decoration: none;">';
                echo esc_html($tracking_data['tracking_number']);
                echo '</a>';
            } else {
                echo esc_html($tracking_data['tracking_number']);
            }
        } else {
            echo '<span style="color: #999;">' . esc_html__('No tracking', 'cargohub-kargo-takip') . '</span>';
        }
    }
    
    /**
     * Add tracking action to my account orders
     */
    public function add_tracking_action($actions, $order) {
        $order_id = method_exists($order, 'get_id') ? $order->get_id() : $order->id;
        $tracking_data = $this->database->get_tracking_data($order_id);
        
        if (!empty($tracking_data['tracking_number'])) {
            $tracking_url = CargoHub_Free_Carriers::get_tracking_url($tracking_data['carrier'], $tracking_data['tracking_number']);
            
            if ($tracking_url) {
                $actions['track'] = array(
                    'url' => $tracking_url,
                    'name' => __('Track Package', 'cargohub-kargo-takip')
                );
            }
        }
        
        return $actions;
    }
    
    /**
     * Enqueue frontend scripts
     */
    public function enqueue_frontend_scripts() {
        if (is_account_page()) {
            wp_enqueue_style(
                'cargohub-free-frontend',
                CARGOHUB_FREE_PLUGIN_URL . 'assets/css/frontend.css',
                array(),
                CARGOHUB_FREE_VERSION
            );
        }
    }
}
