<?php
/**
 * CargoHub Free Carriers Class
 * 
 * Handles carrier information and tracking URLs for FREE version
 */

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

class CargoHub_Free_Carriers {
    
    /**
     * Get all supported carriers
     * 
     * @return array
     */
    public static function get_carriers() {
        // Informative warning if trying to add more than the limit
        // No built-in carriers; all are custom; no limits

        // Return empty array initially
        return array();
    }

    /**
     * Get carrier information by code (cached)
     * 
     * @param string $carrier_code
     * @return array|null
     */
    public static function get_carrier($carrier_code) {
        // Try cache first
        $cache_key = "carrier_{$carrier_code}";
        $cached_result = wp_cache_get($cache_key, 'cargohub_free_carriers');
        
        if ($cached_result !== false) {
            return $cached_result;
        }
        
        // Get from database (restricted)
        $custom_carriers = get_option('cargohub_free_custom_carriers', array());
        
        $result = null;
        if (isset($custom_carriers[$carrier_code])) {
            $result = $custom_carriers[$carrier_code];
        }
        
        // Cache the result (even if null) - use configurable timeout
        $cache_timeout = defined('CARGOHUB_FREE_CACHE_TIMEOUT') ? CARGOHUB_FREE_CACHE_TIMEOUT : 600; // default fallback
        wp_cache_set($cache_key, $result, 'cargohub_free_carriers', $cache_timeout);
        
        return $result;
    }

    /**
     * Check if the carrier limit has been reached
     * 
     * @return bool
     */
    public static function has_reached_carrier_limit() {
        return false;
    }
    
    /**
     * Check if more carriers can be added
     * 
     * @return bool
     */
    public static function can_add_more_carriers() {
        return true;
    }

    /**
     * Get carrier name by code
     * 
     * @param string $carrier_code
     * @return string
     */
    public static function get_carrier_name($carrier_code) {
        $carrier = self::get_carrier($carrier_code);
        return ($carrier && isset($carrier['name'])) ? $carrier['name'] : ucfirst($carrier_code);
    }
    
    /**
     * Get tracking URL for a carrier and tracking number
     * 
     * @param string $carrier_code
     * @param string $tracking_number
     * @return string|null
     */
    public static function get_tracking_url($carrier_code, $tracking_number) {
        $carrier = self::get_carrier($carrier_code);
        
        if (!$carrier || empty($tracking_number) || !isset($carrier['tracking_url'])) {
            return null;
        }
        
        // Return only the base URL without tracking number
        return $carrier['tracking_url'];
    }
    
    /**
     * Get carrier logo URL
     * 
     * @param string $carrier_code
     * @return string
     */
    public static function get_carrier_logo($carrier_code) {
        $custom_carriers = get_option('cargohub_free_custom_carriers', array());

        $upload_dir = wp_upload_dir();
        $base_dir = trailingslashit($upload_dir['basedir']) . 'cargohub-free-logos/';
        $base_url = trailingslashit($upload_dir['baseurl']) . 'cargohub-free-logos/';

        // If logo defined for this carrier
        if (isset($custom_carriers[$carrier_code])) {
            $carrier = $custom_carriers[$carrier_code];

            if (!empty($carrier['logo'])) {
                // If it's an absolute URL use as-is (sanity will be via esc_url on output)
                if (filter_var($carrier['logo'], FILTER_VALIDATE_URL)) {
                    return $carrier['logo'];
                }

                $filename = ltrim($carrier['logo'], '/');
                $path = $base_dir . $filename;
                if (file_exists($path)) {
                    return $base_url . $filename;
                }
            }
        }

        // Fallback to default logo in uploads if present, else plugin asset
        $default_upload_path = $base_dir . 'default-logo.png';
        if (file_exists($default_upload_path)) {
            return $base_url . 'default-logo.png';
        }

        if (defined('CARGOHUB_FREE_PLUGIN_URL')) {
            return trailingslashit(CARGOHUB_FREE_PLUGIN_URL) . 'assets/img/kargofirmalogo/default-logo.png';
        }

        return '';
    }
    
    /**
     * Get carrier color
     * 
     * @param string $carrier_code
     * @return string
     */
    public static function get_carrier_color($carrier_code) {
        $carrier = self::get_carrier($carrier_code);
        return ($carrier && isset($carrier['color'])) ? $carrier['color'] : '#333333';
    }
    
    /**
     * Validate carrier code
     * 
     * @param string $carrier_code
     * @return bool
     */
    public static function is_valid_carrier($carrier_code) {
        $custom_carriers = get_option('cargohub_free_custom_carriers', array());
        return isset($custom_carriers[$carrier_code]);
    }
    
    /**
     * Get carriers as options for select field (with limitation check)
     * 
     * @return array
     */
    public static function get_carrier_options() {
        $custom_carriers = get_option('cargohub_free_custom_carriers', array());
        
        $options = array();
        foreach ($custom_carriers as $code => $carrier) {
            $options[$code] = $carrier['name'];
        }
        
        // No upgrade option injected into select
        
        return $options;
    }
    
    /**
     * Format tracking number for display
     * 
     * @param string $tracking_number
     * @param string $carrier_code
     * @return string
     */
    public static function format_tracking_number($tracking_number, $carrier_code = '') {
        // Remove any spaces and convert to uppercase for consistency
        $formatted = strtoupper(str_replace(' ', '', $tracking_number));
        
        // Carrier-specific formatting rules
        switch ($carrier_code) {
            case 'yurtici':
               
                if (preg_match('/^(\d{4})(\d{4})(\d{4})$/', $formatted, $matches)) {
                    return $matches[1] . ' ' . $matches[2] . ' ' . $matches[3];
                }
                break;
                
            case 'aras':
               
                if (preg_match('/^(AR)(\d+)(TR)$/', $formatted, $matches)) {
                    return $matches[1] . ' ' . $matches[2] . ' ' . $matches[3];
                }
                break;
                
            case 'dhl':
             
                if (preg_match('/^(\d{4})(\d{3})(\d{3,4})$/', $formatted, $matches)) {
                    return $matches[1] . ' ' . $matches[2] . ' ' . $matches[3];
                }
                break;
        }
        
        // Return original if no specific formatting applies
        return $tracking_number;
    }
    
    /**
     * Get remaining carrier slots for FREE version
     * 
     * @return int
     */
    public static function get_remaining_carrier_slots() {
        $carriers = get_option('cargohub_free_custom_carriers', array());
        $max_free_carriers = 50; // hidden soft cap for FREE version
        return max(0, $max_free_carriers - count($carriers));
    }
    
    /**
     * Get PRO upgrade message for carriers
     * 
     * @return string
     */
    public static function get_upgrade_message() {
        return '';
    }
}
