<?php
namespace orderflow\Traits;

trait  Courier {

    public function get_courier_rate_by_phone($phone) {
        // Normalize phone number for cache key
        $phone_normalized = preg_replace('/[^0-9]/', '', $phone);
        $cache_key = 'courier_rate_' . md5($phone_normalized);
        
        // Try to get from cache first
        $cached_result = get_transient($cache_key);
        if ($cached_result !== false) {
            return (float) $cached_result;
        }
        
        // If not in cache, fetch from API
        $courier_history = \orderflow\Courier\Courier::fetch_courier_history_from_apis($phone);

        $total_order = isset($courier_history['total_parcel']) ? $courier_history['total_parcel'] : 0;
        $total_success = isset($courier_history['success_parcel']) ? $courier_history['success_parcel'] : 0;
        $total_cancel = isset($courier_history['cancel_parcel']) ? $courier_history['cancel_parcel'] : 0;

        $success_percent = ($total_order > 0) ? ($total_success / $total_order) * 100 : 0;

        error_log("Courier rate for phone {$phone}: {$success_percent}%");
        error_log("Courier history for phone {$phone}: " . print_r($courier_history, true));
        
        // Cache the result for 5 minutes (300 seconds)
        set_transient($cache_key, $success_percent, 5 * MINUTE_IN_SECONDS);
        
        return $success_percent;
    }
}