<?php

namespace orderflow\Courier;

use orderflow\Core\Base;
if(!class_exists('Courier')){
    class Courier extends Base {

        private $api_key;

        public function __construct() {
            $this->api_key = '670c025b45f99d92b9fc23f6';
        }

       public static function check_fraudulent_courier($phone_number) {
            $phone_number = self::normalize_phone_number($phone_number);

            if(!$phone_number || strlen($phone_number) != 11){
                //return null;
            }

            $api_key = "670c025b45f99d92b9fc23f6";
            
            // ✅ Updated URL based on new API structure
            $url = "https://fraudchecker.ocs-api.top/api/v3?phone=" . urlencode($phone_number) . "&key=" . $api_key;

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            $response = curl_exec($ch);
            curl_close($ch);

            $result = json_decode($response, true);

            return $result;
        }


        public static function fetch_courier_history_from_apis($phone_number) {

            $phone_number = self::normalize_phone_number($phone_number);

            if(!$phone_number || strlen($phone_number) != 11){
                return null;
            }

            $courier_history = [];
            $steadfast_history = [];
            $pathao_history = [];
            $redx_history = [];

            $result = self::check_fraudulent_courier($phone_number);

            if($result && isset($result['error']) && $result['error'] === true){
                return $result;
            }

            return $result;
        }

        public static function fetch_courier_history_with_cache($phone_number) {

            $phone_number = self::normalize_phone_number($phone_number);

            if (!$phone_number || strlen($phone_number) != 11) {
                return null;
            }

            $cache_key   = 'customer_data_' . md5($phone_number);
            $cache_group = 'orderflow_customers_data';

            // ✅ MUST initialize
            $customer_data = null;

            /* =========================
            * 1️⃣ Try WP Object Cache
            * ========================= */
            $cached_data = get_transient($cache_key);

            if ($cached_data !== false) {
                $customer_data = (object) $cached_data;
                //error_log('Courier history fetched from CACHE for phone: ' . $phone_number);
            }

            /* =========================
            * 2️⃣ Fallback to DB
            * ========================= */
            if (!$customer_data) {
                $customer_data = self::fetch_customer_record('phone_number', $phone_number);
                //error_log('Courier history fetched from DB for phone: ' . $phone_number);

                // ✅ Cache immediately after DB fetch
                if ($customer_data) {
                    set_transient(
                        $cache_key,
                        (array) $customer_data,
                        48 * HOUR_IN_SECONDS
                    );
                    //error_log('Courier history cached after DB fetch for phone: ' . $phone_number);
                }
            }

            $courier_history = null;
            $courier_history_last_update_time = null;

            if ($customer_data) {
                $courier_history = json_decode($customer_data->data_courier_history, true);
                $courier_history_last_update_time = $customer_data->data_courier_history_last_update_time;
            }

            $update_courier_history = false;
            $update_courier_history_partially = false;

            /* =========================
            * 3️⃣ Insert if no record
            * ========================= */
            if (!$customer_data) {

                $courier_history = self::fetch_courier_history_from_apis($phone_number);
                //error_log('Courier history fetched from API for phone: ' . $phone_number);

                if ($courier_history) {
                    global $wpdb;
                    $table_name = $wpdb->prefix . 'ads_customers_data';

                    $wpdb->insert(
                        $table_name,
                        [
                            'data_type'  => 'phone_number',
                            'data_value' => $phone_number,
                            'data_courier_history' => json_encode($courier_history),
                            'data_courier_history_last_update_time' => current_time('mysql'),
                        ],
                        ['%s', '%s', '%s', '%s']
                    );

                    // cache new record
                    set_transient(
                        $cache_key,
                        [
                            'data_type'  => 'phone_number',
                            'data_value' => $phone_number,
                            'data_courier_history' => json_encode($courier_history),
                            'data_courier_history_last_update_time' => current_time('mysql'),
                        ],
                        48 * HOUR_IN_SECONDS
                    );
                }

                return $courier_history;
            }

            /* =========================
            * 4️⃣ Decide update logic
            * ========================= */
            if (!$courier_history) {
                $update_courier_history = true;
            } else {
                $last_update_timestamp = strtotime($courier_history_last_update_time);
                $current_timestamp = current_time('timestamp');

                if (($current_timestamp - $last_update_timestamp) < 48 * 60 * 60) {

                    if (
                        !isset($courier_history['response']['steadfast']['data']) ||
                        !isset($courier_history['response']['pathao']['data']) ||
                        !isset($courier_history['response']['redx']['data'])
                    ) {
                        if (($current_timestamp - $last_update_timestamp) > 5 * 60) {
                            $update_courier_history = true;
                            $update_courier_history_partially = true;
                        }
                    }

                } else {
                    $update_courier_history = true;
                }
            }

            /* =========================
            * 5️⃣ Update if required
            * ========================= */
            if ($update_courier_history) {

                if (!$update_courier_history_partially) {
                    $courier_history = self::fetch_courier_history_from_apis($phone_number);
                }

                if ($courier_history) {
                    global $wpdb;
                    $table_name = $wpdb->prefix . 'ads_customers_data';

                    $wpdb->update(
                        $table_name,
                        [
                            'data_courier_history' => json_encode($courier_history),
                            'data_courier_history_last_update_time' => current_time('mysql'),
                        ],
                        [
                            'data_type' => 'phone_number',
                            'data_value' => $phone_number,
                        ],
                        ['%s', '%s'],
                        ['%s', '%s']
                    );

                    // refresh cache
                    set_transient(
                        $cache_key,
                        [
                            'data_type'  => 'phone_number',
                            'data_value' => $phone_number,
                            'data_courier_history' => json_encode($courier_history),
                            'data_courier_history_last_update_time' => current_time('mysql'),
                        ],
                        48 * HOUR_IN_SECONDS
                    );

                    //error_log('Courier history updated & cached for phone: ' . $phone_number);
                }
            }

            return $courier_history;
        }

        public static function get_courier_history_from_cache($phone_number) {

            $phone_number = self::normalize_phone_number($phone_number);

            if(!$phone_number || strlen($phone_number) != 11){
                return null;
            }

            $cache_key   = 'customer_data_' . md5($phone_number);

            // ✅ MUST initialize
            $customer_data = null;

            /* =========================
            * 1️⃣ Try WP Object Cache
            * ========================= */
            $cached_data = get_transient($cache_key);

            if ($cached_data !== false) {
                $customer_data = (object) $cached_data;
                //error_log('Courier history fetched from direct cache for phone: ' . $phone_number);
            }else{
                // Fallback to DB
                global $wpdb;
                $customer_data = self::fetch_customer_record('phone_number', $phone_number);
                //error_log('Courier history fetched from DB for phone: ' . $phone_number);
            }

            if ($customer_data) {
                $courier_history = json_decode($customer_data->data_courier_history, true);
                
                // set cache for future requests
                set_transient(
                    $cache_key,
                    (array) $customer_data,
                    48 * HOUR_IN_SECONDS
                );
                return $courier_history;
            }

            return null;
        }

        public static function calculate_courier_history_statistics($phone_number, $only_from_cache = false) {

            $phone_number = self::normalize_phone_number($phone_number);

            if(!$phone_number || strlen($phone_number) != 11){
                return null;
            }

            if($only_from_cache){
                $courier_history = self::get_courier_history_from_cache($phone_number);
            } else {
                $courier_history = self::fetch_courier_history_with_cache($phone_number);
            }

            if(!$courier_history){
                return null;
            }

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


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

            return [
                'total_order' => $total_order,
                'total_success' => $total_success,
                'total_cancel' => $total_cancel,
                'success_percent' => $success_percent,
                'cancel_percent' => $cancel_percent,
            ];
        }
    }
}