<?php
namespace PortalPeople\netsuite\models\products;
use yii;
use yii\helpers\Json;

class Netsuite extends \common\models\DynamicModel
{

    public static function segment_title()
    {
        return 'NetSuite Attributes';
    }
    /**
     * Undocumented function
     *
     *    'colour' => [
     *        'rules' => [
     *            'string'
     *        ],
     *        'label' => Yii::t('app', "Colour",),
     *        'input' => 'default',
     *     ],
     * @return void
     */
    public static function localattributes()
    {
        return [
            'erpid' => [
                'rules' => [
                    ['integer']
                ],
                'label' => Yii::t('app', "ID",),
                'input' => 'default',
            ],
            'erp_name' => [
                'rules' => [
                    ['string']
                ],
                'label' => Yii::t('app', "Name",),
                'input' => 'default',
            ],
            'erp_qty' => [
                'rules' => [
                    ['integer']
                ],
                'label' => Yii::t('app', "QTY",),
                'input' => 'default',
            ],
            'erp_discountid' => [
                'rules' => [
                    ['integer']
                ],
                'label' => Yii::t('app', "Discount ID",),
                'input' => 'default',
            ],
            'erp_link' => [
                'rules' => [
                    ['string']
                ],
                'label' => Yii::t('app', "Link",),
                'input' => 'default',
            ],
            'erp_cost' => [
                'rules' => [
                    ['number']
                ],
                'label' => Yii::t('app', "Cost",),
                'input' => 'default',
            ],
            'unit' => [
                'rules' => [
                    ['string']
                ],
                'label' => Yii::t('app', "Unit",),
                'input' => 'default',
            ],
            'uom_name' => [
                'rules' => [
                    ['string']
                ],
                'label' => Yii::t('app', "Unit of Measure Name",),
                'input' => 'default',
            ],
            'haulierid' => [
                'rules' => [
                    ['safe']
                ],
                'label' => Yii::t('app', "Haulier ID",),
                'input' => [
                    'input' => 'checkboxList',
                    'fieldclass' => null,
                    'fieldlist' => \backend\models\Accounts::intids('haulier'),
                    'options' => ['label' => false, 'prompt' => 'Please Select'],
                    'width' => 'col-md-12',
                ],
            ],
            'supplierid' => [
                'rules' => [
                    ['string']
                ],
                'label' => Yii::t('app', "Supplier ID",),
                'input' => [
                    'input' => 'dropDownList',
                    'fieldclass' => null,
                    'fieldlist' => \backend\models\Accounts::intids('supplier'),
                    'options' => ['label' => false, 'prompt' => 'Please Select'],
                    'width' => 'col-md-12',
                ],
            ],
        ];
    }


    public function dataLoad($modelData) {
        $ext_data = json_decode($modelData->data, true);
        $data = $ext_data['netsuite'] ?? null;
        
        // Populate from stored ext_data first
        if ($data !== null) {
            $this->load($data, '');
            }
            
            // If we have an erpid, build the erp_link and fetch live data from NetSuite
            if (!empty($this->erpid)) {
            $accountId = Yii::$app->params['netsuite']['account_id'] ?? null;
            if ($accountId) {
                $this->erp_link = 'https://' . $accountId . '.suitetalk.api.netsuite.com/services/rest/record/v1/inventoryItem/' . $this->erpid;
                }
                
                if (!empty($this->erp_link) && (!Yii::$app->request->isConsoleRequest && Yii::$app->request->isGet && Yii::$app->controller->action->id === 'update' && Yii::$app->request->get('id') == $modelData->id)) {
                try {
                    
                    $response = Yii::$app->cache->getorset('netsuite_product_' . $this->erpid, function() {
                        return \common\components\NetSuiteApi::get($this->erp_link);
                    }, 3600); // Cache for 1 hour
                    if ($response && $response->isOk) {
                        $nsData = Json::decode($response->content, true);
                        // Map NetSuite fields → model properties (always overwrite from live data)
                        if (!empty($nsData['itemId']) && empty($this->erp_name)) {
                            $this->erp_name = $nsData['itemId'];
                        }
                        if (isset($nsData['lastPurchasePrice']) && empty($this->erp_cost)) {
                            $this->erp_cost = $nsData['lastPurchasePrice'];
                        }
                        if (!empty($nsData['unitsType']['refName']) && empty($this->uom_name)) {
                            $this->uom_name = $nsData['unitsType']['refName'];
                        }
                        if (!empty($nsData['stockUnit']) && empty($this->unit)) {
                            $this->unit = $nsData['stockUnit'];
                        }
                    } else {
                        Yii::error('Failed to fetch NetSuite data for erpid ' . $this->erpid . ': ' . ($response ? $response->content : 'No response'), 'netsuite');
                    }
                } catch (\Exception $e) {
                    Yii::error('NetSuite dataLoad error for erpid ' . $this->erpid . ': ' . $e->getMessage(), 'netsuite');
                }
            }
        }
        $decoded = is_array($modelData->data) ? $modelData->data : (json_decode($modelData->data, true) ?? []);
        $decoded['netsuite'] = $this;
        $modelData->data = $decoded;
    }
}

