<?php
namespace orderflow\Courier;

use orderflow\Core\Base;

class 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, and error details
     */
    public static function pathao_get_customer_history($phone_number) {
        // Initialize default response structure
        $response = [
            'success' => 0,
            'cancel' => 0,
            'total' => 0,
            'error' => false,
            'error_message' => '',
            'error_type' => ''
        ];

        // Normalize and validate phone number
        $phone_number = self::normalize_phone_number($phone_number);
        if (!$phone_number || strlen($phone_number) != 11) {
            $response['error'] = true;
            $response['error_message'] = 'Invalid phone number';
            $response['error_type'] = 'validation';
            return $response;
        }

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

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

        // Check if API response contains an error
        if (isset($api_response['error'])) {
            $response['error'] = true;
            $response['error_message'] = 'API request failed: ' . $api_response['error'];
            $response['error_type'] = 'api_request';
            return $response;
        }

        // Extract and return customer data
        return self::extract_customer_data($api_response, $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 $api_response API response
     * @param array $response Base response structure
     * @return array Customer delivery data with error details if any
     */
    private static function extract_customer_data($api_response, $response) {
        if (!$api_response || !isset($api_response['data']) || !isset($api_response['data']['customer'])) {
            $response['error'] = true;
            $response['error_message'] = 'Invalid API response: required data not found';
            $response['error_type'] = 'api_response';
            return $response;
        }

        $customer = $api_response['data']['customer'];
        $success = $customer['successful_delivery'] ?? 0;
        $total = $customer['total_delivery'] ?? 0;
        $cancel = $total - $success;

        $response['success'] = $success;
        $response['cancel'] = $cancel;
        $response['total'] = $total;

        return $response;
    }

    /**
     * Login to Pathao and store session
     *
     * @return array Result of login operation with consistent error structure
     */
    public static function pathao_login_and_store_session() {
        // Initialize response structure
        $response = [
        ];

        $email_address = get_option('ads_pathao_email_address');
        $password = get_option('ads_pathao_password');

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

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

        if (isset($api_response['error'])) {
            $response['error'] = true;
            $response['error_message'] = $api_response['error'];
            $response['error_type'] = 'api_request';
            return $response;
        }

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

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

        // Return success response
        return $response;
    }
}