<?php
namespace orderflow\Courier;

use orderflow\Core\Base;

class bckup_Pathao_Api extends Base {
    // API endpoints
    private const LOGIN_ENDPOINT = 'https://merchant.pathao.com/api/v1/login';
    private const CUSTOMER_HISTORY_ENDPOINT = 'https://merchant.pathao.com/api/v1/user/success';

    // Token expiration time in seconds (6 hours)
    private const TOKEN_EXPIRY_TIME = 21600;

    // Request timeout in seconds
    private const REQUEST_TIMEOUT = 15;

    /**
     * Get customer delivery history from Pathao
     *
     * @param string $phone_number Customer phone number
     * @return array Customer delivery data with success, cancel and total counts
     */
    public static function pathao_get_customer_history($phone_number) {
        // Normalize and validate phone number
        $phone_number = self::normalize_phone_number($phone_number);
        if (!$phone_number || strlen($phone_number) != 11) {
            return ['error' => 'Invalid phone number'];
        }

        // Get access token
        $access_token = self::get_valid_access_token();
        if (isset($access_token['error'])) {
            return ['error' => 'Failed to get access token: ' . $access_token['error']];
        }

        // Get customer delivery data
        $response = self::make_api_request(self::CUSTOMER_HISTORY_ENDPOINT, [
            'phone' => $phone_number,
        ], $access_token);


        // Extract and return customer data
        return self::extract_customer_data($response);
    }

    /**
     * Get a valid access token, refreshing if necessary
     *
     * @return string|array Access token or error array
     */
    private static function get_valid_access_token() {
        $session = get_option('ads_pathao_session');
        $access_token = $session['access_token'] ?? null;
        $token_time = $session['last_login'] ?? 0;

        // Check if token is valid
        if (!$access_token || (time() - $token_time > self::TOKEN_EXPIRY_TIME)) {
            $login_result = self::pathao_login_and_store_session();
            if (isset($login_result['error'])) {
                return ['error' => $login_result['error']];
            }

            $session = get_option('ads_pathao_session');
            $access_token = $session['access_token'] ?? null;
        }

        if (!$access_token) {
            return ['error' => 'Access token missing after login'];
        }

        return $access_token;
    }

    /**
     * Make an API request to Pathao
     *
     * @param string $endpoint API endpoint
     * @param array $data Request data
     * @param string $access_token Access token
     * @return array Response data or error
     */
    private static function make_api_request($endpoint, $data, $access_token = null) {
        $headers = [
            'Content-Type' => 'application/json',
        ];

        if ($access_token) {
            $headers['Authorization'] = 'Bearer ' . $access_token;
        }

        $response = wp_remote_post($endpoint, [
            'headers' => $headers,
            'body' => json_encode($data),
            'timeout' => self::REQUEST_TIMEOUT,
        ]);

        if (is_wp_error($response)) {
            return ['error' => 'Request failed: ' . $response->get_error_message()];
        }

        $body = wp_remote_retrieve_body($response);
        return json_decode($body, true);
    }

    /**
     * Extract customer data from API response
     *
     * @param array $response API response
     * @return array Customer delivery data
     */
    private static function extract_customer_data($response) {
        if (!$response || !isset($response['data']) || !isset($response['data']['customer'])) {
            return ['success' => 0, 'cancel' => 0, 'total' => 0];
        }
        $customer = $response['data']['customer'];
        $success = $customer['successful_delivery'] ?? 0;
        $total = $customer['total_delivery'] ?? 0;
        $cancel = $total - $success;

        return [
            'success' => $success,
            'cancel' => $cancel,
            'total' => $total,
        ];
    }

    /**
     * Login to Pathao and store session
     *
     * @return array Result of login operation
     */
    public static function pathao_login_and_store_session() {
        $email_address = get_option('ads_pathao_email_address');
        $password = get_option('ads_pathao_password');

        if (!$email_address || !$password) {
            return ['error' => 'Pathao email address or password not set in options'];
        }

        $response = self::make_api_request(self::LOGIN_ENDPOINT, [
            'username' => $email_address,
            'password' => $password,
        ]);

        if (isset($response['error'])) {
            return ['error' => $response['error']];
        }

        if (!isset($response['access_token'])) {
            return ['error' => 'Access token not received from Pathao'];
        }

        // Save token and timestamp in options
        update_option('ads_pathao_session', [
            'access_token' => trim($response['access_token']),
            'last_login' => time(),
        ]);

        return ['success' => 'Login successful and session saved'];
    }
}