<?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
            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);
            
            // 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 (multiple ways to ensure 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
            $screen = get_current_screen();
            if ($screen && ($screen->post_type === 'shop_order' || $screen->id === 'shop_order')) {
                $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'),
                'has_carriers' => ! empty( get_option( 'cargohub_free_custom_carriers', array() ) ),
                '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'),
                    'no_carriers' => __('Önce kargo firması ekleyin.', 'cargohub-kargo-takip')
                )
            ));

            // Add extra spacing for Select2 when Divine plugin is active
            include_once ABSPATH . 'wp-admin/includes/plugin.php';
            if (function_exists('is_plugin_active') && is_plugin_active('divine/divine.php')) {
                wp_add_inline_style(
                    'cargohub-kargo-takip-admin',
                    '.wc-wp-version-gte-53 .select2-container .select2-selection--single{margin-bottom:10px;}'
                );
            }
        }
    }

    /**
     * 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><br>
                <p><?php esc_html_e('Bir hatırlatma; e-mail sisteminin sorunsuz çalışması için web sitenizde SMTP mail sisteminin hazır ve çalışır durumda olması önemlidir.', '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>
       
<?php
$hero_rel = 'assets/img/cargo-hub-hero.png';
$hero_path = CARGOHUB_FREE_PLUGIN_DIR . $hero_rel;
$img_url = ( file_exists( $hero_path )
    ? CARGOHUB_FREE_PLUGIN_URL . $hero_rel
    : CARGOHUB_FREE_PLUGIN_URL . 'assets/screenshots/icon-256x256.png'
);
$img_url .= '?ver=' . CARGOHUB_FREE_VERSION;
?>
<div class="wrap" style="position: relative; text-align: center;">
    <img src="<?php echo esc_url( $img_url ); ?>" alt="CargoHub Kargo Takip Eklentisi" 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();
            }
        }

        // Handle logo update
        $nonce_logo_upd = isset($_POST['carrier_logo_nonce']) ? sanitize_text_field( wp_unslash($_POST['carrier_logo_nonce']) ) : '';
        if (isset($_POST['update_carrier_logo'])) {
            if (wp_verify_nonce($nonce_logo_upd, 'update_carrier_logo_nonce')) {
                $this->handle_update_carrier_logo();
            }
        }

        // Handle logo removal
        $nonce_logo_del = isset($_POST['carrier_logo_nonce']) ? sanitize_text_field( wp_unslash($_POST['carrier_logo_nonce']) ) : '';
        if (isset($_POST['remove_carrier_logo'])) {
            if (wp_verify_nonce($nonce_logo_del, 'remove_carrier_logo_nonce')) {
                $this->handle_delete_carrier_logo();
            }
        }
        
        $carriers = get_option('cargohub_free_custom_carriers', array());
        $can_add_more = true;
        
        ?>
        <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 -->
            <?php if ($can_add_more): ?>
            <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="" enctype="multipart/form-data">
                    <?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>
                        <tr>
                             <th><label for="carrier_logo_file"><?php esc_html_e('Kargo Firma Logosu (PNG/JPEG, max 2MB)', 'cargohub-kargo-takip'); ?></label></th>
                            <td>
                                <input type="file" id="carrier_logo_file" name="carrier_logo_file" accept=".png,.jpg,.jpeg,image/png,image/jpeg" />
                                <p class="description"><?php esc_html_e('Logo yüklemek isteğe bağlıdır. Yüklendiğinde otomatik olarak en fazla 160x60 boyutlarına ölçeklenir.', 'cargohub-kargo-takip'); ?></p>
                            </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>
            <?php endif; ?>
            
            <!-- 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;">
                            <?php 
                            $logo_url = CargoHub_Free_Carriers::get_carrier_logo($code);
                            ?>
                            <div style="width: 60px; height: 44px; border-radius: 6px; display: flex; align-items: center; justify-content: center; background:#fff; border:1px solid #e1e5e9;">
                                <?php if ($logo_url): ?>
                                    <img src="<?php echo esc_url($logo_url); ?>" alt="<?php echo esc_attr($carrier['name']); ?>" style="max-width: 60px; max-height: 40px; object-fit: contain;" />
                                <?php else: ?>
                                    <div style="width: 40px; height: 30px; background: <?php echo esc_attr($carrier['color']); ?>; border-radius: 4px; 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>
                                <?php endif; ?>
                            </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" enctype="multipart/form-data" style="display:inline-block; margin-right:8px;">
                                <?php wp_nonce_field('update_carrier_logo_nonce', 'carrier_logo_nonce'); ?>
                                <input type="hidden" name="carrier_code" value="<?php echo esc_attr($code); ?>" />
                                <input type="file" name="carrier_logo_file" accept=".png,.jpg,.jpeg,image/png,image/jpeg" style="margin-right:6px;" />
                                <button type="submit" name="update_carrier_logo" class="button"><?php echo esc_html__('Logoyu Güncelle', 'cargohub-kargo-takip'); ?></button>
                            </form>
                            <?php if (!empty($carrier['logo'])): ?>
                            <form method="post" style="display: inline;" onsubmit="return confirm('<?php echo esc_attr__('Logoyu silmek istiyor musunuz?', 'cargohub-kargo-takip'); ?>')">
                                <?php wp_nonce_field('remove_carrier_logo_nonce', 'carrier_logo_nonce'); ?>
                                <input type="hidden" name="carrier_code" value="<?php echo esc_attr($code); ?>" />
                                <button type="submit" name="remove_carrier_logo" class="button button-link-delete">&nbsp;<?php echo esc_html__('Logoyu Sil', 'cargohub-kargo-takip'); ?></button>
                            </form>
                            <?php endif; ?>
                            <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 if we can add more carriers
        if (!CargoHub_Free_Carriers::can_add_more_carriers()) {
            add_action('admin_notices', function() {
                echo '';
            });
            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;
        }
        
        // Prepare logo (optional upload)
        $saved_logo_filename = '';
        if (!empty($_FILES['carrier_logo_file']) && isset($_FILES['carrier_logo_file']['tmp_name']) && is_uploaded_file($_FILES['carrier_logo_file']['tmp_name'])) {
            $upload_result = $this->process_logo_upload($_FILES['carrier_logo_file']);
            if (is_wp_error($upload_result)) {
                add_action('admin_notices', function() use ($upload_result) {
                    echo '<div class="notice notice-error"><p>' . esc_html($upload_result->get_error_message()) . '</p></div>';
                });
            } else {
                $saved_logo_filename = $upload_result; // only filename stored
            }
        }

        // Add new carrier
        $carriers[$carrier_code] = array(
            'name' => $carrier_name,
            'tracking_url' => $tracking_url,
            'color' => $carrier_color ?: '#0073aa',
            'logo' => $saved_logo_filename,
            '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 update carrier logo
     */
    private function handle_update_carrier_logo() {
        if (!current_user_can('manage_woocommerce')) { return; }
        $carrier_code = isset($_POST['carrier_code']) ? sanitize_key( wp_unslash($_POST['carrier_code']) ) : '';
        if (!$carrier_code) { return; }
        $carriers = get_option('cargohub_free_custom_carriers', array());
        if (empty($carriers[$carrier_code])) { return; }

        // Upload new logo
        if (!empty($_FILES['carrier_logo_file']) && isset($_FILES['carrier_logo_file']['tmp_name']) && is_uploaded_file($_FILES['carrier_logo_file']['tmp_name'])) {
            $upload_result = $this->process_logo_upload($_FILES['carrier_logo_file']);
            if (is_wp_error($upload_result)) {
                add_action('admin_notices', function() use ($upload_result) {
                    echo '<div class="notice notice-error"><p>' . esc_html($upload_result->get_error_message()) . '</p></div>';
                });
                return;
            }

            // Remove old logo file if exists
            if (!empty($carriers[$carrier_code]['logo'])) {
                $this->delete_logo_file($carriers[$carrier_code]['logo']);
            }

            // Save new filename
            $carriers[$carrier_code]['logo'] = $upload_result;
            update_option('cargohub_free_custom_carriers', $carriers);
            wp_cache_delete("carrier_{$carrier_code}", 'cargohub_free_carriers');

            add_action('admin_notices', function() {
                echo '<div class="notice notice-success"><p>' . esc_html__('Logo updated successfully.', 'cargohub-kargo-takip') . '</p></div>';
            });
        }
    }

    /**
     * Handle delete carrier logo
     */
    private function handle_delete_carrier_logo() {
        if (!current_user_can('manage_woocommerce')) { return; }
        $carrier_code = isset($_POST['carrier_code']) ? sanitize_key( wp_unslash($_POST['carrier_code']) ) : '';
        if (!$carrier_code) { return; }
        $carriers = get_option('cargohub_free_custom_carriers', array());
        if (empty($carriers[$carrier_code])) { return; }

        if (!empty($carriers[$carrier_code]['logo'])) {
            $this->delete_logo_file($carriers[$carrier_code]['logo']);
            $carriers[$carrier_code]['logo'] = '';
            update_option('cargohub_free_custom_carriers', $carriers);
            wp_cache_delete("carrier_{$carrier_code}", 'cargohub_free_carriers');
        }

        add_action('admin_notices', function() {
            echo '<div class="notice notice-success"><p>' . esc_html__('Logo removed successfully.', 'cargohub-kargo-takip') . '</p></div>';
        });
    }

    /**
     * Process logo upload: validate size/MIME, move file, resize to max 160x60, return saved filename
     */
    private function process_logo_upload($file) {
        // Size check ≤ 2MB
        if (!empty($file['size']) && intval($file['size']) > 2 * 1024 * 1024) {
            return new WP_Error('cargohub_logo_size', __('Logo size must be 2MB or less.', 'cargohub-kargo-takip'));
        }

        // Allow only PNG/JPEG (extension => mime)
        $allowed_mimes = array('png' => 'image/png', 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg');
        $check = wp_check_filetype_and_ext($file['tmp_name'], $file['name'], $allowed_mimes);
        if (empty($check['ext']) || empty($check['type'])) {
            return new WP_Error('cargohub_logo_type', __('Only PNG and JPEG images are allowed.', 'cargohub-kargo-takip'));
        }

        require_once ABSPATH . 'wp-admin/includes/file.php';
        add_filter('upload_mimes', function($mimes) use ($allowed_mimes){
            foreach ($allowed_mimes as $ext => $mime) { $mimes[$ext] = $mime; }
            return $mimes;
        });
        $overrides = array('test_form' => false, 'mimes' => $allowed_mimes);
        $uploaded = wp_handle_upload($file, $overrides);
        if (isset($uploaded['error'])) {
            return new WP_Error('cargohub_logo_upload', $uploaded['error']);
        }

        // Resize to max 160x60
        $image_path = $uploaded['file'];
        $editor = wp_get_image_editor($image_path);
        if (is_wp_error($editor)) {
            // If cannot edit, still accept but move to logos folder with sanitized name
            return $this->move_to_logos_dir($image_path, $check['ext']);
        }
        $editor->resize(160, 60, false);
        $editor->set_quality(85);
        $resized = $editor->save();
        if (is_wp_error($resized)) {
            return new WP_Error('cargohub_logo_resize', __('Failed to resize logo.', 'cargohub-kargo-takip'));
        }

        return $this->move_to_logos_dir($resized['path'], $check['ext']);
    }

    private function move_to_logos_dir($source_path, $ext) {
        $upload_dir = wp_upload_dir();
        $logos_dir = trailingslashit($upload_dir['basedir']) . 'cargohub-free-logos/';
        if (!file_exists($logos_dir)) { wp_mkdir_p($logos_dir); }
        $filename = 'logo_' . wp_generate_password(10, false, false) . '.' . strtolower($ext);
        $dest_path = $logos_dir . $filename;
        if (!@copy($source_path, $dest_path)) {
            return new WP_Error('cargohub_logo_move', __('Failed to move logo file.', 'cargohub-kargo-takip'));
        }
        @unlink($source_path);
        return $filename;
    }

    private function delete_logo_file($filename) {
        $upload_dir = wp_upload_dir();
        $logos_dir = trailingslashit($upload_dir['basedir']) . 'cargohub-free-logos/';
        $path = $logos_dir . ltrim($filename, '/');
        if (file_exists($path)) { @unlink($path); }
    }
    
    /**
     * Handle delete carrier form submission
     */
    private function handle_delete_carrier() {
        // 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; ?>

                    <?php wp_nonce_field('cargohub_free_nonce', 'cargohub_free_nonce'); ?>
                </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 (empty($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']);
            $tn = $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($tn);
                echo '</a>';
            } else {
                echo esc_html($tn);
            }
            echo ' <button type="button" class="cargohub-copy-btn" data-track="' . esc_attr($tn) . '" style="margin-left:6px; padding:2px 6px; font-size:11px;">' . esc_html__('Kopyala', 'cargohub-kargo-takip') . '</button>';
        } 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
            );
        }
    }
}
