<?php
/**
 * CargoHub Free Orders Class
 * 
 * Handles WooCommerce order integration for FREE version
 */

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

class CargoHub_Free_Orders {
    
    /**
     * 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('wp_enqueue_scripts', array($this, 'enqueue_frontend_scripts'));
        add_action('init', array($this, 'register_custom_order_status'));
        
        // WooCommerce hooks - only if WooCommerce is active
        if (class_exists('WooCommerce')) {
            add_action('woocommerce_order_status_changed', array($this, 'order_status_changed'), 10, 4);
            add_action('woocommerce_order_details_after_order_table', array($this, 'display_tracking_info'));
            add_action('woocommerce_email_order_details', array($this, 'email_tracking_info'), 10, 4);
            add_filter('wc_order_statuses', array($this, 'add_custom_order_status'));
            
        }
    }
    
    /**
     * Handle order status changes
     */
    public function order_status_changed($order_id, $old_status, $new_status, $order) {
        // Log status change for tracking purposes
        CargoHub_Free_Logger::info("Order status changed: {$order_id} from {$old_status} to {$new_status}");
        
        // If order status changed to "shipped", trigger email if tracking data exists and email not sent
        if ($new_status === 'shipped') {
            // Check if tracking data exists
            $tracking_data = $this->database->get_tracking_by_order_id($order_id);
            
            if ($tracking_data && !empty($tracking_data->tracking_number)) {
                CargoHub_Free_Logger::info("Order {$order_id} status changed to 'shipped' with tracking data. Triggering email...");
                
                // Always trigger the tracking_added action - email class will handle duplicates with hash
                do_action('cargohub_free_tracking_added', $order_id, $tracking_data->carrier, $tracking_data->tracking_number);
                
                // Add success notice
                add_action('admin_notices', function() use ($order_id) {
                    echo '<div class="notice notice-success is-dismissible">';
                    echo '<p><strong>CargoHub:</strong> Sipariş durumu "Kargoya Verildi" olarak değiştirildi ve müşteriye kargo takip e-postası gönderildi.</p>';
                    echo '</div>';
                });
            } else {
                // No tracking data, show notice to admin
                CargoHub_Free_Logger::info("Order {$order_id} status changed to 'shipped' but no tracking data found");
                
                // Add admin notice to remind adding tracking data
                add_action('admin_notices', function() use ($order_id) {
                    $order_edit_url = function_exists('wc_get_order') && ($order_obj = wc_get_order($order_id)) ? $order_obj->get_edit_order_url() : admin_url('post.php?post=' . $order_id . '&action=edit');
                    echo '<div class="notice notice-warning is-dismissible">';
                    echo '<p><strong>CargoHub:</strong> Sipariş durumu "Kargoya Verildi" olarak değiştirildi ancak kargo bilgileri eksik! ';
                    echo '<a href="' . esc_url($order_edit_url) . '">Kargo bilgilerini eklemek için siparişi düzenleyin</a>.</p>';
                    echo '</div>';
                });
            }
        }
    }
    
    /**
     * Display tracking information on order details page
     */
    public function display_tracking_info($order) {
        $order_id = $order->get_id();
        $tracking_data = $this->database->get_tracking_by_order_id($order_id);
        
        if (!$tracking_data) {
            return;
        }
        
        $carrier_info = CargoHub_Free_Carriers::get_carrier($tracking_data->carrier);
        $tracking_url = CargoHub_Free_Carriers::get_tracking_url($tracking_data->carrier, $tracking_data->tracking_number);
        ?>
        <section class="cargohub-free-order-tracking">
            <h2><?php esc_html_e('Kargo Detay Bilgileri', 'cargohub-kargo-takip'); ?></h2>
            
            <div class="cargohub-free-tracking-info">
                <div class="cargohub-free-carrier-info">
                    <div class="cargohub-free-carrier-logo">
                        <img src="<?php echo esc_url(CargoHub_Free_Carriers::get_carrier_logo($tracking_data->carrier)); ?>" 
                             alt="<?php echo esc_attr($carrier_info['name']); ?> Logo"
                             class="carrier-logo-display">
                    </div>
                    <div class="cargohub-free-carrier-details">
                        <h3><?php echo esc_html($carrier_info['name']) . ' ' . esc_html__('Firması ile Gönderilmiştir.', 'cargohub-kargo-takip'); ?></h3>
                        <p><strong><?php echo esc_html__('Takip Numarası:', 'cargohub-kargo-takip'); ?></strong> 
                           <span class="cargohub-free-tracking-number"><?php echo esc_html(CargoHub_Free_Carriers::format_tracking_number($tracking_data->tracking_number, $tracking_data->carrier)); ?></span></p>
                        
                        <?php if ($tracking_url): ?>
                            <p>
                                <a href="<?php echo esc_url($tracking_url); ?>" 
                                   target="_blank" 
                                   class="button cargohub-free-track-button"
                                   style="background-color: <?php echo esc_attr(CargoHub_Free_Carriers::get_carrier_color($tracking_data->carrier)); ?>; color: white;">
                                    <?php esc_html_e('Kargonuzu Takip Edin', 'cargohub-kargo-takip'); ?>
                                </a>
                            </p>
                        <?php endif; ?>
                        
                        <p class="cargohub-free-tracking-date">
                            <small><?php echo esc_html__('Kargoya Verilme Tarihi:', 'cargohub-kargo-takip'); ?> <?php echo esc_html(mysql2date(get_option('date_format'), $tracking_data->created_at)); ?></small>
                        </p>
                        <br>

                        <p class="cargohub-free-tracking-date">
                            <small><?php echo wp_kses_post(__('&lt;b&gt;Küçük Bir Hatırlatma,&lt;/b&gt; Kargo Firmaları Sorgulama Panellerini Zaman Zaman Değiştirdiklerinden Dolayı, Takip Kodunuz  ile Kendi Web Sitelerinden Sorgulayabilirsiniz.', 'cargohub-kargo-takip')); ?></small>
                        </p>
                    </div>
                </div>
            </div>
        </section>
        <?php
    }
    
    /**
     * Add tracking info to email
     */
    public function email_tracking_info($order, $sent_to_admin, $plain_text, $email) {
        // Only show in customer emails, not admin
        if ($sent_to_admin) {
            return;
        }
        
        $order_id = $order->get_id();
        $tracking_data = $this->database->get_tracking_by_order_id($order_id);
        
        if (!$tracking_data) {
            return;
        }
        
        $carrier_info = CargoHub_Free_Carriers::get_carrier($tracking_data->carrier);
        $tracking_url = CargoHub_Free_Carriers::get_tracking_url($tracking_data->carrier, $tracking_data->tracking_number);
        $formatted_tracking = CargoHub_Free_Carriers::format_tracking_number($tracking_data->tracking_number, $tracking_data->carrier);
        
        if ($plain_text) {
            echo "\n" . esc_html__('KARGO BİLGİLERİ', 'cargohub-kargo-takip') . "\n";
            echo esc_html( str_repeat('-', 50) ) . "\n";
            echo esc_html__('Kargo Firması:', 'cargohub-kargo-takip') . ' ' . esc_html($carrier_info['name']) . "\n";
            echo esc_html__('Takip Numarası:', 'cargohub-kargo-takip') . ' ' . esc_html($formatted_tracking) . "\n";
            if ($tracking_url) {
                echo esc_html__('Takip Linki:', 'cargohub-kargo-takip') . ' ' . esc_url($tracking_url) . "\n";
            }
            echo "\n";
        } else {
            ?>
            <div style="background: #f8f9fa; border: 1px solid #dee2e6; border-radius: 8px; padding: 20px; margin: 20px 0;">
                 <h3 style="color: #333; margin-top: 0;"><?php esc_html_e('📦 Kargo Bilgileri', 'cargohub-kargo-takip'); ?></h3>
                 <p><strong><?php esc_html_e('Kargo Firması:', 'cargohub-kargo-takip'); ?></strong> <?php echo esc_html($carrier_info['name']); ?></p>
                 <p><strong><?php esc_html_e('Takip Numarası:', 'cargohub-kargo-takip'); ?></strong> <?php echo esc_html($formatted_tracking); ?></p>
                <?php if ($tracking_url): ?>
                    <p>
                        <a href="<?php echo esc_url($tracking_url); ?>" target="_blank" 
                           style="background: #0073aa; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; display: inline-block;">
                            <?php esc_html_e('Kargonuzu Takip Edin', 'cargohub-kargo-takip'); ?>
                        </a>
                    </p>
                <?php endif; ?>
            </div>
            <?php
        }
    }
    
    /**
     * Register custom order status
     */
    public function register_custom_order_status() {
        register_post_status('wc-shipped', array(
            'label'                     => __('Kargoya Verildi', 'cargohub-kargo-takip'),
            'public'                    => true,
            'exclude_from_search'       => false,
            'show_in_admin_all_list'    => true,
            'show_in_admin_status_list' => true,
            /* translators: %s: sipariş sayısı. */
            'label_count'               => _n_noop('Kargoya Verildi <span class="count">(%s)</span>', 'Kargoya Verildi <span class="count">(%s)</span>', 'cargohub-kargo-takip')
        ));
    }
    
    /**
     * Add custom order status to list
     */
    public function add_custom_order_status($order_statuses) {
        $order_statuses['wc-shipped'] = __('Kargoya Verildi', 'cargohub-kargo-takip');
        return $order_statuses;
    }
    
    /**
     * Enqueue frontend scripts
     */
    public function enqueue_frontend_scripts() {
        if (is_wc_endpoint_url('view-order') || is_wc_endpoint_url('orders')) {
            wp_enqueue_style(
                'cargohub-free-frontend',
                CARGOHUB_FREE_PLUGIN_URL . 'assets/css/frontend.css',
                array(),
                CARGOHUB_FREE_VERSION
            );
        }
    }
}
