<?php
namespace LivraisonAPI;

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

class ShippingMethod extends \WC_Shipping_Method {
    
    public $id;
    public $instance_id;
    public $method_title;
    public $method_description;
    public $supports;
    public $title;
    public $description;
    public $enabled;
    
    public function __construct( $instance_id = 0 ) {
        $this->id = 'livraison_api';
        $this->instance_id = absint( $instance_id );
        $this->method_title = __( 'SendiAPI Delivery - Cash on Delivery', 'sendi-api' );
        $this->method_description = __( 'Delivery with cash on delivery via SendiAPI.', 'sendi-api' );
        $this->supports = array(
            'shipping-zones',
            'instance-settings',
            'instance-settings-modal',
        );
        
        $this->init();
    }

    public function init() {
        $this->init_form_fields();
        $this->init_settings();
        
        $this->title = $this->get_option( 'title', __( 'SendiAPI Delivery', 'sendi-api' ) );
        $this->description = $this->get_option( 'description', '' );
        $this->enabled = $this->get_option( 'enabled', 'yes' );
        
        add_action( 'woocommerce_update_options_shipping_' . $this->id, array( $this, 'process_admin_options' ) );
    }

    public function init_form_fields() {
        $this->form_fields = array(
            'enabled' => array(
                'title' => __( 'Enable', 'sendi-api' ),
                'type' => 'checkbox',
                'description' => __( 'Enable this shipping method.', 'sendi-api' ),
                'default' => 'yes'
            ),
            'title' => array(
                'title' => __( 'Title', 'sendi-api' ),
                'type' => 'text',
                'description' => __( 'Title displayed to the customer.', 'sendi-api' ),
                'default' => __( 'SendiAPI Delivery', 'sendi-api' ),
                'desc_tip' => true,
            ),
            'description' => array(
                'title' => __( 'Description', 'sendi-api' ),
                'type' => 'textarea',
                'description' => __( 'Description displayed to the customer.', 'sendi-api' ),
                'default' => __( 'Delivery with cash on delivery via SendiAPI.', 'sendi-api' ),
            ),
            'info' => array(
                'title' => __( 'Information', 'sendi-api' ),
                'type' => 'title',
                'description' => __(
                    '<div style="background: #f0fdf4; padding: 15px; border-left: 4px solid #22c55e; border-radius: 4px;">
                        <strong>Cash on delivery</strong><br>
                        The customer pays the delivery driver directly upon delivery.
                    </div>',
                    'sendi-api'
                ),
            ),
        );
    }

    public function calculate_shipping( $package = array() ) {
        $estimated_cost = $this->get_estimated_cost( $package );
        
        $rate = array(
            'id' => $this->id,
            'label' => $this->title,
            'cost' => 0,
            'package' => $package,
            'meta_data' => array(
                'description' => $this->description ?: __( 'Cash on delivery', 'sendi-api' ),
                'estimated_cost' => $estimated_cost,
                'payment_method' => 'cash_on_delivery'
            )
        );
        
        if ( $estimated_cost > 0 ) {
            $rate['label'] .= ' (' . wc_price( $estimated_cost ) . ' ' . __( 'on delivery', 'sendi-api' ) . ')';
        }
        
        $this->add_rate( $rate );
    }

    private function get_estimated_cost( $package ) {
        try {
            $api = new API();
            $communes_response = $api->get_communes();
            
            if ( ! $communes_response['success'] || empty( $communes_response['data'] ) ) {
                return null;
            }
            
            $dest_commune = $this->get_destination_commune( $package );
            $pickup_commune = get_option( 'livraison_api_pickup_commune', '' );
            
            if ( empty( $dest_commune ) || empty( $pickup_commune ) ) {
                return null;
            }
            
            $price = $this->calculate_price( $communes_response['data'], $pickup_commune, $dest_commune );
            return $price;
            
        } catch ( \Exception $e ) {
            // ✅ CORRECTION: Utiliser livraison_api_log() au lieu de error_log()
            livraison_api_log( 'Shipping error: ' . $e->getMessage(), 'error' );
            return null;
        }
    }

    private function get_destination_commune( $package ) {
        $destination = $package['destination'];
        
        if ( WC()->session ) {
            $session_commune = WC()->session->get( 'livraison_commune' );
            if ( ! empty( $session_commune ) ) {
                return $session_commune;
            }
        }
        
        if ( ! empty( $destination['city'] ) ) {
            return $destination['city'];
        }
        
        return '';
    }

    private function calculate_price( $communes, $pickup, $destination ) {
        $pickup_commune = null;
        $dest_commune = null;
        
        $pickup = trim( strtolower( $pickup ) );
        $destination = trim( strtolower( $destination ) );
        
        foreach ( $communes as $commune ) {
            $commune_name = trim( strtolower( $commune['name'] ) );
            
            if ( $commune_name === $pickup ) {
                $pickup_commune = $commune;
            }
            if ( $commune_name === $destination ) {
                $dest_commune = $commune;
            }
            
            if ( $pickup_commune && $dest_commune ) {
                break;
            }
        }
        
        if ( ! $pickup_commune || ! $dest_commune ) {
            return null;
        }
        
        if ( $pickup_commune['id'] === $dest_commune['id'] ) {
            return floatval( $pickup_commune['priceSame'] ?? 1500 );
        }
        
        return floatval( $pickup_commune['priceDifferent'] ?? 2000 );
    }

    public function admin_options() {
        ?>
        <div style="margin-bottom: 20px;">
            <div style="background: #fef3c7; padding: 15px; border-radius: 5px; border: 1px solid #f59e0b;">
                <h3><?php esc_html_e( 'Cash on Delivery', 'sendi-api' ); ?></h3>
                <ul style="margin: 0;">
                    <li><?php esc_html_e( 'The customer does not pay shipping fees online.', 'sendi-api' ); ?></li>
                    <li><?php esc_html_e( 'The customer pays the delivery driver directly upon delivery.', 'sendi-api' ); ?></li>
                    <li><?php esc_html_e( 'The price is calculated by the Sendi API.', 'sendi-api' ); ?></li>
                </ul>
            </div>
        </div>
        <?php
        parent::admin_options();
    }
}