<?php
/**
 * Plugin Name: CargoHub – Kargo Takip Sistemi
 * Description: WooCommerce mağazaları için kargo takip eklentisi. Siparişlere kargo firması ve takip numarası ekleyin, müşterilerinize e-posta bildirimi gönderin ve Hesabım sayfasında takip bilgilerini gösterin.
 * Version: 1.1.3
 * Author: RomiTeT Creative
 * Author URI: https://www.romitetcreative.us
 * License: GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: cargohub-kargo-takip
 * Domain Path: /languages
 * Requires at least: 5.0
 * Tested up to: 6.8
 * Requires PHP: 7.3
 * WC requires at least: 5.0
 * WC tested up to: 9.0
 * Requires Plugins: woocommerce
 * 
 * CargoHub is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * any later version.
 * 
 * CargoHub is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * @package CargoHub
 * @author RomiTeT Creative
 * @copyright 2025 RomiTeT Creative
 * @license GPL-2.0-or-later
 */

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

// Declare WooCommerce HPOS compatibility
add_action('before_woocommerce_init', function() {
    if (class_exists('\Automattic\WooCommerce\Utilities\FeaturesUtil')) {
        \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility('custom_order_tables', __FILE__, true);
    }
});

// Check if WooCommerce is active
add_action('plugins_loaded', 'cargohub_free_check_woocommerce');

function cargohub_free_check_woocommerce() {
    if (!class_exists('WooCommerce')) {
        add_action('admin_notices', function() {
            echo '<div class="notice notice-error"><p>' . esc_html__(
                'CargoHub requires WooCommerce to be installed and active.',
                'cargohub-kargo-takip'
            ) . '</p></div>';
        });
        return;
    }
    
    // Check WooCommerce version compatibility
    if (defined('WC_VERSION') && version_compare(WC_VERSION, '5.0', '<')) {
        add_action('admin_notices', function() {
            echo '<div class="notice notice-error"><p>' .
                esc_html(
                    sprintf(
                        /* translators: %s: WooCommerce version number. */
                        __('CargoHub requires WooCommerce version 5.0 or higher. You are running version %s.', 'cargohub-kargo-takip'),
                        WC_VERSION
                    )
                ) .
                '</p></div>';
        });
        return;
    }
}

// Define plugin constants
define('CARGOHUB_FREE_VERSION', '1.1.3');
define('CARGOHUB_FREE_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('CARGOHUB_FREE_PLUGIN_URL', plugin_dir_url(__FILE__));
define('CARGOHUB_FREE_PLUGIN_BASENAME', plugin_basename(__FILE__));

// Centralized PRO/upgrade URL
if (!defined('CARGOHUB_PRO_URL')) {
    define('CARGOHUB_PRO_URL', 'https://www.shopier.com/37980148');
}

// Removed version-limitation constants to comply with WP.org guidelines

// Define production mode (set to true for production)
if (!defined('CARGOHUB_FREE_PRODUCTION')) {
    define('CARGOHUB_FREE_PRODUCTION', true);
}

// Define default performance constants if not already defined
if (!defined('CARGOHUB_FREE_CACHE_TIMEOUT')) {
    define('CARGOHUB_FREE_CACHE_TIMEOUT', 600); // 10 minutes
}

if (!defined('CARGOHUB_FREE_MEMORY_THRESHOLD')) {
    define('CARGOHUB_FREE_MEMORY_THRESHOLD', 64); // 64MB
}

if (!defined('CARGOHUB_FREE_BATCH_SIZE')) {
    define('CARGOHUB_FREE_BATCH_SIZE', 50); // Max 50 items at once
}

/**
 * Main CargoHub Free Class
 */
class CargoHub_Free {
    
    /**
     * Instance of this class
     */
    private static $instance = null;
    
    /**
     * Get singleton instance
     */
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * Constructor
     */
    private function __construct() {
        $this->init_hooks();
        $this->include_files();
        $this->init_classes();
    }
    
    /**
     * Initialize hooks
     */
    private function init_hooks() {
        add_action('plugins_loaded', array($this, 'load_textdomain'));
        register_activation_hook(__FILE__, array($this, 'activate'));
        register_deactivation_hook(__FILE__, array($this, 'deactivate'));
        add_action('init', array($this, 'init'));
        
        // Add plugin action links (Upgrade to PRO link)
        add_filter('plugin_action_links_' . CARGOHUB_FREE_PLUGIN_BASENAME, array($this, 'add_plugin_action_links'));
    }

  
        
    /**
     * Include required files
     */
    private function include_files() {
        // Include logger first
        require_once CARGOHUB_FREE_PLUGIN_DIR . 'includes/class-cargohub-free-logger.php';
        
        // Initialize logger
        CargoHub_Free_Logger::init();
        
        $files = array(
            'includes/class-cargohub-free-security.php',
            'includes/class-cargohub-free-carriers.php',
            'includes/class-cargohub-free-database.php',
            'includes/class-cargohub-free-email.php',
            'includes/class-cargohub-free-orders.php',
            'includes/class-cargohub-free-admin.php'
        );
        
        foreach ($files as $file) {
            $file_path = CARGOHUB_FREE_PLUGIN_DIR . $file;
            if (file_exists($file_path)) {
                require_once $file_path;
            } else {
                CargoHub_Free_Logger::critical("Missing critical file: $file_path");
            }
        }
    }
    
    /**
     * Initialize classes
     */
    private function init_classes() {
        // Only initialize if classes exist
        if (class_exists('CargoHub_Free_Database')) {
            new CargoHub_Free_Database();
        }
        
        if (class_exists('CargoHub_Free_Email')) {
            new CargoHub_Free_Email();
        }
        
        if (class_exists('CargoHub_Free_Orders')) {
            new CargoHub_Free_Orders();
        }
        
        // Initialize admin class last (depends on others)
        if (class_exists('CargoHub_Free_Admin') && is_admin()) {
            new CargoHub_Free_Admin();
        }
    }
    
       
    /**
     * Plugin activation
     */
    public function activate() {
        try {
            // Include logger first for activation logging
            if (!class_exists('CargoHub_Free_Logger')) {
                require_once CARGOHUB_FREE_PLUGIN_DIR . 'includes/class-cargohub-free-logger.php';
                CargoHub_Free_Logger::init();
            }
            
            CargoHub_Free_Logger::info('CargoHub plugin activation started', array(
                'version' => CARGOHUB_FREE_VERSION,
                'wp_version' => get_bloginfo('version')
            ));
            
            // Check WooCommerce before database operations
            if (!class_exists('WooCommerce')) {
                CargoHub_Free_Logger::warning('WooCommerce not active during activation');
            }
            
            // Include database class if not already included
            if (!class_exists('CargoHub_Free_Database')) {
                require_once CARGOHUB_FREE_PLUGIN_DIR . 'includes/class-cargohub-free-database.php';
            }
            
            // Create database instance and tables
            $database = new CargoHub_Free_Database();
            
            // Create logos directory structure only
            $this->setup_logo_directory();
            
            // Set activation date for PRO notice timing
            update_option('cargohub_free_activation_date', current_time('mysql'));
            
            // Clear any cached data
            $this->cleanup_memory();
            
            CargoHub_Free_Logger::info('CargoHub plugin activation completed successfully');
            
        } catch (Exception $e) {
            CargoHub_Free_Logger::critical('Plugin activation failed: ' . $e->getMessage());
        }
    }
    
    /**
     * Setup logo directory structure
     */
    private function setup_logo_directory() {
        // Create uploads directory
        $upload_dir = wp_upload_dir();
        $cargohub_logos_dir = $upload_dir['basedir'] . '/cargohub-free-logos';
        
        if (!file_exists($cargohub_logos_dir)) {
            wp_mkdir_p($cargohub_logos_dir);
            
            // Create .htaccess for security
            $htaccess_content = "Options -Indexes\n";
            $htaccess_content .= "<Files *.php>\nDeny from all\n</Files>\n";
            file_put_contents($cargohub_logos_dir . '/.htaccess', $htaccess_content);
            
            // Only copy default-logo.png as fallback
            $source_dir = CARGOHUB_FREE_PLUGIN_DIR . 'assets/img/kargofirmalogo/';
            $default_logo_source = $source_dir . 'default-logo.png';
            $default_logo_dest = $cargohub_logos_dir . '/default-logo.png';
            
            if (file_exists($default_logo_source) && !file_exists($default_logo_dest)) {
                copy($default_logo_source, $default_logo_dest);
                CargoHub_Free_Logger::info("Copied fallback logo: default-logo.png");
            }
        }
    }

    /**
     * Memory cleanup and optimization
     */
    private function cleanup_memory() {
        // Clear WordPress object cache
        if (function_exists('wp_cache_flush')) {
            wp_cache_flush();
        }
        
        // Clear any transients
        delete_transient('cargohub_free_logger_initialized');
        
        // Force garbage collection
        if (function_exists('gc_collect_cycles')) {
            gc_collect_cycles();
        }
        
        // Clear any global variables that might be holding references
        global $wpdb;
        if (isset($wpdb->queries)) {
            $wpdb->queries = array();
        }
    }
    
    /**
     * Plugin deactivation
     */
    public function deactivate() {
        // Before shutting down, migrate custom status to a core status so orders remain visible
        $this->migrate_shipped_orders_to_processing();
        
        // Clear any scheduled hooks
        wp_clear_scheduled_hook('cargohub_free_cleanup');
        
        // Clear memory
        $this->cleanup_memory();
    }
    
    /**
     * Initialize plugin
     */
    public function init() {
        // Schedule cleanup task
        if (!wp_next_scheduled('cargohub_free_cleanup')) {
            wp_schedule_event(time(), 'daily', 'cargohub_free_cleanup');
        }
        
        // Memory monitoring hook
        add_action('wp_loaded', array($this, 'check_memory_usage'));
    }
    
    /**
     * Check memory usage and cleanup if needed
     */
    public function check_memory_usage() {
        $memory_usage = memory_get_usage(true) / 1024 / 1024; // Convert to MB
        
        // Use configurable memory threshold
        $memory_threshold = defined('CARGOHUB_FREE_MEMORY_THRESHOLD') ? CARGOHUB_FREE_MEMORY_THRESHOLD : 64;
        
        // If memory usage is high, perform cleanup
        if ($memory_usage > $memory_threshold) {
            $this->cleanup_memory();
            
            // Log only if memory is critically high
            if ($memory_usage > ($memory_threshold * 1.5) && class_exists('CargoHub_Free_Logger')) {
                CargoHub_Free_Logger::warning('High memory usage detected: ' . round($memory_usage, 2) . 'MB');
            }
        }
    }

    /**
     * Migrate custom order status 'wc-shipped' to 'wc-processing' to preserve visibility after deactivation
     */
    private function migrate_shipped_orders_to_processing() {
        global $wpdb;
        // Update classic orders table
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $wpdb->query($wpdb->prepare(
            "UPDATE {$wpdb->posts} SET post_status=%s WHERE post_type=%s AND post_status=%s",
            'wc-completed', 'shop_order', 'wc-shipped'
        ));

        // Update HPOS orders table if exists
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $orders_table = $wpdb->prefix . 'wc_orders';
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        if ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $orders_table)) === $orders_table) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            $wpdb->query($wpdb->prepare(
                "UPDATE {$orders_table} SET status=%s WHERE status=%s",
                'wc-completed', 'wc-shipped'
            ));
        }
    }
    
    /**
     * Check if PRO upgrade notice should be shown
     */
    // Removed promotional notice logic to comply with WP.org guidelines

    /**
     * Add plugin action links (PRO Upgrade)
     */
    public function add_plugin_action_links($links) {
        $pro_link = '<a href="' . esc_url(CARGOHUB_PRO_URL) . '" target="_blank" style="color: #008000; font-weight: bold;">' . esc_html__('Pro Versiyona Geçin', 'cargohub-kargo-takip') . '</a>';
        array_unshift($links, $pro_link);
        return $links;
    }
    
    // Removed carrier limit helpers to comply with WP.org guidelines
}

/**
 * Initialize the plugin
 */
function cargohub_free_init() {
    try {
        return CargoHub_Free::get_instance();
    } catch (Exception $e) {
        add_action('admin_notices', function() use ($e) {
            echo '<div class="notice notice-error"><p>' . esc_html__('CargoHub Error:', 'cargohub-kargo-takip') . ' ' . esc_html($e->getMessage()) . '</p></div>';
        });
        return false;
    }
}

// Start the plugin
add_action('plugins_loaded', 'cargohub_free_init');

/**
 * Plugin cleanup on uninstall
 */
function cargohub_free_cleanup() {
    // Clean up old tracking data (older than 1 year)
    global $wpdb;
    $table_name = $wpdb->prefix . 'cargohub_free_tracking';
    
    // Only run if table exists
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table_name)) === $table_name) {
        $cutoff = gmdate('Y-m-d H:i:s', strtotime('-1 year'));
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->query(
            $wpdb->prepare(
                "DELETE FROM {$wpdb->prefix}cargohub_free_tracking WHERE created_at < %s",
                $cutoff
            )
        );
    }
    
    // Force garbage collection after cleanup
    if (function_exists('gc_collect_cycles')) {
        gc_collect_cycles();
    }
}
add_action('cargohub_free_cleanup', 'cargohub_free_cleanup');


