<?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'));
            // Show persisted admin notices on order edit screen
            add_action('admin_notices', array($this, 'show_persisted_notice'));
        }
    }
    
    /**
     * 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}");
        
        // Hard guard: If no carriers are defined at all, disallow switching to shipped
        if ($new_status === 'shipped') {
            $has_carriers = ! empty( get_option( 'cargohub_free_custom_carriers', array() ) );
            if (! $has_carriers) {
                CargoHub_Free_Logger::warning("Order {$order_id} cannot be set to shipped: no carriers defined");
                // Persist notice across redirect
                $user_id = get_current_user_id();
                $notice = __('Sipariş durumu "Kargoya Verildi" olarak değiştirilemedi. Önce en az bir kargo firması ekleyin.', 'cargohub-kargo-takip');
                set_transient('cargohub_free_notice_' . $order_id . '_' . $user_id, $notice, MINUTE_IN_SECONDS);
                // Revert status back to previous without causing recursion
                remove_action('woocommerce_order_status_changed', array($this, 'order_status_changed'), 10);
                try {
                    $order->set_status($old_status);
                    $order->save();
                } catch (Exception $e) {
                    CargoHub_Free_Logger::error('Failed to revert order status when no carriers present: ' . $e->getMessage());
                }
                add_action('woocommerce_order_status_changed', array($this, 'order_status_changed'), 10, 4);
                return;
            }
        }

        // 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) {
                    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( admin_url('post.php?post=' . $order_id . '&action=edit') ) . '">Kargo bilgilerini eklemek için siparişi düzenleyin</a>.</p>';
                    echo '</div>';
                });
            }
        }
    }

    /**
     * Show persisted admin notice after redirect
     */
    public function show_persisted_notice() {
        if (!is_admin()) {
            return;
        }
        // Only show to users who can edit shop orders
        if (!current_user_can('edit_shop_orders')) {
            return;
        }
        // Support both classic and HPOS order editors
        $order_id = 0;
        // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only usage; values sanitized via absint; no state change
        if (isset($_GET['post'])) {
            $order_id = absint($_GET['post']);
        } elseif (isset($_GET['order_id'])) {
            $order_id = absint($_GET['order_id']);
        } elseif (isset($_GET['id'])) {
            $order_id = absint($_GET['id']);
        }
        // phpcs:enable WordPress.Security.NonceVerification.Recommended
        if (!$order_id) {
            return;
        }
        $user_id = get_current_user_id();
        $key = 'cargohub_free_notice_' . $order_id . '_' . $user_id;
        $message = get_transient($key);
        if ($message) {
            delete_transient($key);
            $carriers_url = admin_url('admin.php?page=cargohub-kargo-takip-carriers');
            echo '<div class="notice notice-error is-dismissible">';
            echo '<p><strong>CargoHub:</strong> ' . esc_html($message) . ' ';
            echo '<a href="' . esc_url( $carriers_url ) . '" class="button button-secondary" style="margin-left:8px;">' . esc_html__('Kargo Firması Ekle', 'cargohub-kargo-takip') . '</a></p>';
            echo '</div>';
        }
    }
    
    /**
     * Show admin notice when order is shipped but no tracking added
     */
    private function maybe_show_tracking_notice($order_id) {
        $tracking_data = $this->database->get_tracking_by_order_id($order_id);
        
        if (!$tracking_data && is_admin()) {
            // Store notice in transient to show on next admin page load
            set_transient('cargohub_free_tracking_notice_' . $order_id, true, HOUR_IN_SECONDS);
        }
    }
    
    /**
     * 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>
                           <button type="button" class="button cargohub-copy-btn" data-track="<?php echo esc_attr($tracking_data->tracking_number); ?>" style="margin-left:8px;">
                               <?php esc_html_e('Kopyala', 'cargohub-kargo-takip'); ?>
                           </button>
                        </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(__('Küçük Bir Hatırlatma,; Kargo Firmaları Sorgulama Panellerini Zaman Zaman Değiştirdiklerinden Dolayı, Takip Kodunuz  ile Kendi Web Sitelerinden Sorgulayabilirsiniz.', 'cargohub-kargo-takip')); ?></small>
                        </p>
                        
                        <!-- FREE version notice -->
                        
                    </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
            );

            wp_enqueue_script(
                'cargohub-free-frontend',
                CARGOHUB_FREE_PLUGIN_URL . 'assets/js/frontend.js',
                array('jquery'),
                CARGOHUB_FREE_VERSION,
                true
            );
        }
    }
}
