<?php

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

class EcomZone extends Module
{
    private $errors = [];
    private $api;
    
    public function __construct()
    {
        $this->name = 'ecomzone';
        $this->tab = 'market_place';
        $this->version = '1.0.0';
        $this->author = 'Your Name';
        $this->need_instance = 0;
        $this->bootstrap = true;
        $this->ps_versions_compliancy = [
            'min' => '1.7.0.0',
            'max' => _PS_VERSION_
        ];

        parent::__construct();

        $this->displayName = $this->l('EcomZone Integration');
        $this->description = $this->l('Integrates PrestaShop with EcomZone Dropshipping API');
        
        // Initialize API
        require_once(dirname(__FILE__) . '/classes/EcomZoneAPI.php');
        $this->api = new EcomZoneAPI();
    }

    public function install()
    {
        if (!parent::install()) {
            $this->errors[] = $this->l('Could not install the module');
            return false;
        }

        if (!$this->registerHook('actionProductUpdate')) {
            $this->errors[] = $this->l('Could not register hooks');
            return false;
        }

        if (!Configuration::updateValue('ECOMZONE_API_KEY', '') ||
            !Configuration::updateValue('ECOMZONE_API_URL', 'https://dropship.ecomzone.eu/api')) {
            $this->errors[] = $this->l('Could not set default configuration');
            return false;
        }

        return true;
    }

    public function getContent()
    {
        $output = '';
        
        if (Tools::isSubmit('submitEcomZone')) {
            $apiKey = Tools::getValue('ECOMZONE_API_KEY');
            
            if (!$apiKey) {
                $output .= $this->displayError($this->l('API Key is required'));
            } else {
                Configuration::updateValue('ECOMZONE_API_KEY', $apiKey);
                $output .= $this->displayConfirmation($this->l('Settings updated'));
            }
        }

        return $output . $this->displayForm();
    }

    public function displayForm()
    {
        $fields_form[0]['form'] = [
            'legend' => [
                'title' => $this->l('Settings'),
            ],
            'input' => [
                [
                    'type' => 'text',
                    'label' => $this->l('API Key'),
                    'name' => 'ECOMZONE_API_KEY',
                    'required' => true,
                    'size' => 50
                ],
            ],
            'submit' => [
                'title' => $this->l('Save'),
                'class' => 'btn btn-default pull-right'
            ]
        ];

        $helper = new HelperForm();
        $helper->module = $this;
        $helper->name_controller = $this->name;
        $helper->token = Tools::getAdminTokenLite('AdminModules');
        $helper->currentIndex = AdminController::$currentIndex . '&configure=' . $this->name;
        $helper->default_form_language = Configuration::get('PS_LANG_DEFAULT');
        $helper->fields_value['ECOMZONE_API_KEY'] = Configuration::get('ECOMZONE_API_KEY');

        return $helper->generateForm($fields_form);
    }

    public function getErrors()
    {
        return $this->errors;
    }

    public function hookActionProductUpdate($params)
    {
        try {
            $product = $params['product'];
            $productId = $product->id;
            
            // Get product reference (SKU)
            $reference = $product->reference;
            
            if (!empty($reference)) {
                // Get product data from EcomZone
                $ecomZoneProduct = $this->api->getProduct($reference);
                
                if ($ecomZoneProduct && isset($ecomZoneProduct['data'])) {
                    // Update stock
                    if (isset($ecomZoneProduct['data']['stock'])) {
                        StockAvailable::setQuantity($productId, 0, (int)$ecomZoneProduct['data']['stock']);
                    }
                    
                    // Update price
                    if (isset($ecomZoneProduct['data']['product_price'])) {
                        $product->price = (float)$ecomZoneProduct['data']['product_price'];
                        $product->update();
                    }
                    
                    PrestaShopLogger::addLog(
                        sprintf('EcomZone: Updated product %s (ID: %d)', $reference, $productId),
                        1, // Notice level
                        null,
                        'Product',
                        $productId,
                        true
                    );
                }
            }
        } catch (Exception $e) {
            PrestaShopLogger::addLog(
                sprintf('EcomZone: Error updating product %d: %s', $productId, $e->getMessage()),
                3, // Error level
                null,
                'Product',
                $productId,
                true
            );
        }
    }
} 