<?php
namespace LivraisonAPI;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class API {
    private $api_url;
    private $api_key;

    public function __construct() {
        $this->api_url = rtrim( get_option( 'livraison_api_url', 'https://api.sendi-api.com' ), '/' );
        $this->api_key = get_option( 'livraison_api_key', '' );
        
        if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
            livraison_api_log( 'API URL: ' . $this->api_url, 'info' );
            livraison_api_log( 'API Key: ' . ( $this->api_key ? 'Configured (length: ' . strlen($this->api_key) . ')' : 'Missing' ), 'info' );
        }
    }

    public function get_api_url() {
        return $this->api_url;
    }
    
    public function get_api_key() {
        return $this->api_key;
    }
    
    public function request( $endpoint, $method = 'GET', $data = null ) {
        try {
            $url = $this->api_url . '/' . ltrim( $endpoint, '/' );
            
            livraison_api_log( '📡 API Request: ' . $method . ' ' . $url, 'info' );
            
            $args = array(
                'method' => $method,
                'headers' => array(
                    'Content-Type' => 'application/json',
                    'x-api-key' => $this->api_key
                ),
                'timeout' => 30
            );

            if ( $data && ( $method === 'POST' || $method === 'PUT' ) ) {
                $args['body'] = json_encode( $data );
                if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
                    livraison_api_log( '📦 Request body: ' . substr( json_encode( $data ), 0, 500 ), 'info' );
                }
            }

            $response = wp_remote_request( $url, $args );

            if ( is_wp_error( $response ) ) {
                livraison_api_log( '❌ Request error: ' . $response->get_error_message(), 'error' );
                return array(
                    'success' => false,
                    'error' => $response->get_error_message()
                );
            }

            $body = wp_remote_retrieve_body( $response );
            $status_code = wp_remote_retrieve_response_code( $response );
            $result = json_decode( $body, true );
            
            livraison_api_log( '📡 Response status: ' . $status_code, 'info' );
            
            if ( $status_code >= 400 ) {
                livraison_api_log( '❌ Response error: ' . substr( $body, 0, 500 ), 'error' );
            } else {
                livraison_api_log( '✅ Response success: ' . substr( $body, 0, 200 ), 'info' );
            }

            return array(
                'success' => $status_code >= 200 && $status_code < 300,
                'data' => $result,
                'status_code' => $status_code,
                'raw_response' => $body
            );
            
        } catch ( Exception $e ) {
            livraison_api_log( '❌ Exception in request: ' . $e->getMessage(), 'error' );
            return array(
                'success' => false,
                'error' => $e->getMessage()
            );
        }
    }

    // ============================================
    // ✅ get_available_agences
    // ============================================
    
    public function get_available_agences( $commune, $pickupCommune = null, $clientCommune = null ) {
        $pickup = $pickupCommune ?: $commune;
        $client = $clientCommune ?: $commune;
        
        $cache_key = 'livraison_agences_' . md5( $commune . $pickup . $client );
        $cached = wp_cache_get( $cache_key, 'livraison_api' );
        
        if ( false !== $cached ) {
            livraison_api_log( "📦 Cache hit for agences: $commune", 'info' );
            return $cached;
        }
        
        if ( empty( $this->api_key ) ) {
            livraison_api_log( '❌ API key missing in get_available_agences', 'error' );
            return array(
                'success' => false,
                'error' => 'API key not configured'
            );
        }
        
        $url = '/api/v1/agences/available?commune=' . urlencode( $commune ) . 
               '&pickupCommune=' . urlencode( $pickup ) . 
               '&clientCommune=' . urlencode( $client );
        
        livraison_api_log( '🔍 Calling get_available_agences: ' . $url, 'info' );
        
        $result = $this->request( $url, 'GET' );
        
        livraison_api_log( '📡 get_available_agences response: ' . json_encode( $result ), 'info' );
        
        if ( $result['success'] ) {
            wp_cache_set( $cache_key, $result, 'livraison_api', 300 );
        }
        
        return $result;
    }

    // ============================================
    // ✅ create_order
    // ============================================
    
    public function create_order( $order_data ) {
        livraison_api_log( '📤 Creating order with data: ' . json_encode( $order_data, JSON_PRETTY_PRINT ), 'info' );
        return $this->request( '/api/v1/order', 'POST', $order_data );
    }

    // ============================================
    // get_communes
    // ============================================
    
    public function get_communes() {
        try {
            $cache_key = 'livraison_communes';
            $cached = wp_cache_get( $cache_key, 'livraison_api' );
            
            if ( false !== $cached ) {
                livraison_api_log( "📦 Cache hit for communes", 'info' );
                return $cached;
            }
            
            if ( empty( $this->api_url ) ) {
                livraison_api_log( '❌ API URL is empty', 'error' );
                $fallback = $this->get_fallback_communes();
                wp_cache_set( $cache_key, $fallback, 'livraison_api', 3600 );
                return $fallback;
            }
            
            $result = $this->request( '/api/v1/communes', 'GET' );
            
            if ( $result['success'] && isset( $result['data'] ) ) {
                $communes = array();
                
                if ( isset( $result['data']['communes'] ) && is_array( $result['data']['communes'] ) ) {
                    $communes = $result['data']['communes'];
                } elseif ( is_array( $result['data'] ) ) {
                    $communes = $result['data'];
                }
                
                if ( ! empty( $communes ) ) {
                    $communes = array_map( function( $commune ) {
                        if ( is_array( $commune ) ) {
                            return array(
                                'id' => isset( $commune['id'] ) ? $commune['id'] : uniqid(),
                                'name' => isset( $commune['name'] ) ? $commune['name'] : ( isset( $commune['nom'] ) ? $commune['nom'] : '' ),
                                'city' => isset( $commune['city'] ) ? $commune['city'] : ( isset( $commune['ville'] ) ? $commune['ville'] : '' ),
                                'countryCode' => isset( $commune['countryCode'] ) ? $commune['countryCode'] : ( isset( $commune['country'] ) ? $commune['country'] : 'CI' )
                            );
                        }
                        return $commune;
                    }, $communes );
                    
                    $communes = array_filter( $communes, function( $c ) {
                        return ! empty( $c['name'] );
                    } );
                    
                    $result['data'] = array_values( $communes );
                    wp_cache_set( $cache_key, $result, 'livraison_api', 3600 );
                    livraison_api_log( "✅ " . count( $communes ) . " communes récupérées", 'info' );
                    return $result;
                }
            }
            
            livraison_api_log( '⚠️ Aucune commune trouvée, utilisation fallback', 'warning' );
            $fallback = $this->get_fallback_communes();
            wp_cache_set( $cache_key, $fallback, 'livraison_api', 3600 );
            return $fallback;
            
        } catch ( Exception $e ) {
            livraison_api_log( '❌ Exception dans get_communes: ' . $e->getMessage(), 'error' );
            return $this->get_fallback_communes();
        }
    }

    private function get_fallback_communes() {
        $communes = array(
            array( 'id' => '1', 'name' => 'Cocody', 'city' => 'Abidjan', 'countryCode' => 'CI' ),
            array( 'id' => '2', 'name' => 'Plateau', 'city' => 'Abidjan', 'countryCode' => 'CI' ),
            array( 'id' => '3', 'name' => 'Yopougon', 'city' => 'Abidjan', 'countryCode' => 'CI' ),
            array( 'id' => '4', 'name' => 'Marcory', 'city' => 'Abidjan', 'countryCode' => 'CI' ),
            array( 'id' => '5', 'name' => 'Treichville', 'city' => 'Abidjan', 'countryCode' => 'CI' ),
            array( 'id' => '6', 'name' => 'Koumassi', 'city' => 'Abidjan', 'countryCode' => 'CI' ),
            array( 'id' => '7', 'name' => 'Adjamé', 'city' => 'Abidjan', 'countryCode' => 'CI' ),
            array( 'id' => '8', 'name' => 'Abobo', 'city' => 'Abidjan', 'countryCode' => 'CI' ),
            array( 'id' => '9', 'name' => 'Port-Bouët', 'city' => 'Abidjan', 'countryCode' => 'CI' ),
            array( 'id' => '10', 'name' => 'Attécoubé', 'city' => 'Abidjan', 'countryCode' => 'CI' ),
        );
        
        return array(
            'success' => true,
            'data' => $communes,
            'from_fallback' => true
        );
    }

    // ============================================
    // CRÉDITS
    // ============================================
    
    public function get_credits() {
        return $this->request( '/api/v1/commercant/credits', 'GET' );
    }

    // ============================================
    // COMMANDES
    // ============================================
    
    public function cancel_order( $order_id ) {
        return $this->request( '/api/v1/order/' . $order_id . '/cancel', 'POST' );
    }
    
    /**
     * Récupérer le statut d'une commande via son course_id
     */
    public function get_order_status( $course_id ) {
        if ( empty( $course_id ) ) {
            return array(
                'success' => false,
                'error' => 'Course ID is required'
            );
        }
        
        $cache_key = 'livraison_order_status_' . md5( $course_id );
        $cached = wp_cache_get( $cache_key, 'livraison_api' );
        
        if ( false !== $cached ) {
            livraison_api_log( "📦 Cache hit for order status: $course_id", 'info' );
            return $cached;
        }
        
        $result = $this->request( '/api/v1/order/' . $course_id, 'GET' );
        
        if ( $result['success'] ) {
            wp_cache_set( $cache_key, $result, 'livraison_api', 60 );
        }
        
        return $result;
    }

    /**
     * Tracking d'une commande (alias de get_order_status)
     */
    public function track_order( $course_id ) {
        return $this->get_order_status( $course_id );
    }

    // ============================================
    // TEST CONNEXION
    // ============================================
    
    public function test_connection() {
        $url = $this->api_url . '/health';
        
        livraison_api_log( '🔍 Testing connection to: ' . $url, 'info' );
        
        $response = wp_remote_get( $url, array(
            'timeout' => 30,
            'headers' => array(
                'Content-Type' => 'application/json'
            )
        ) );
        
        if ( is_wp_error( $response ) ) {
            livraison_api_log( '❌ Health check failed: ' . $response->get_error_message(), 'error' );
            livraison_api_log( '🔄 Trying /api/v1/communes...', 'info' );
            return $this->get_communes();
        }
        
        $status_code = wp_remote_retrieve_response_code( $response );
        $body = wp_remote_retrieve_body( $response );
        $data = json_decode( $body, true );
        
        livraison_api_log( '📡 Health check response: ' . $status_code, 'info' );
        
        if ( $status_code === 200 ) {
            return array(
                'success' => true,
                'status' => $status_code,
                'data' => $data
            );
        }
        
        livraison_api_log( '🔄 Health check returned ' . $status_code . ', trying /communes...', 'warning' );
        return $this->get_communes();
    }
}