<?php

use yii\widgets\ActiveForm;
use yii\helpers\Html;
use yii\helpers\Json;
//use Yii;

/** @var $this yii\web\View */
/** @var $model \backend\models\Productsbe */

Yii::Warning($model->data->netsuite ?? 'No NetSuite data found', 'netsuite-api-view');
$this->title = 'NetSuite API Data';
$this->params['breadcrumbs'][] = ['label' => 'Products', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;

$apiData = null;
$apiError = null;
$apiUrl = null;

// Extract NetSuite data from product
if ($model && !empty($model->data)) {
    $data = is_string($model->data) ? Json::decode($model->data, true) : $model->data;
    $netusuiteData = $data->netsuite ?? [];
    $apiUrl = $netusuiteData->erp_link ?? null;
    
    // If we have a URL, fetch the data using the working NetSuite OAuth implementation
    if ($apiUrl) {
        try {
            $netsuiteConfig = Yii::$app->params['netsuite'] ?? [];
            
            if (empty($netsuiteConfig['consumer_key']) || empty($netsuiteConfig['certificate_id']) || empty($netsuiteConfig['private_key_path'])) {
                $apiError = 'NetSuite is not configured properly. Please check settings.';
            } else {
                // Resolve private key path
                $privateKeyPath = $netsuiteConfig['private_key_path'];
                if (!file_exists($privateKeyPath)) {
                    $privateKeyPath = $_SERVER['DOCUMENT_ROOT'] . $privateKeyPath;
                }
                
                if (!file_exists($privateKeyPath)) {
                    $apiError = 'Private key file not found: ' . $netsuiteConfig['private_key_path'];
                } else {
                    // Use the working NetSuiteApi::get() method
                    $response = \PortalPeople\netsuite\NetSuiteApi::get($apiUrl);
                    
                    if ($response && $response->isOk) {
                        $apiData = $response->data;
                    } else {
                        $apiError = 'Failed to fetch NetSuite data: ' . ($response ? $response->content : 'No response');
                    }
                }
            }
        } catch (\Exception $e) {
            $apiError = 'Error fetching NetSuite data: ' . $e->getMessage();
            Yii::error($e->getMessage(), 'netsuite-api');
        }
    }
}
?>

<div class="netsuite-api-data">
    <h1><?= Html::encode($this->title) ?></h1>
    
    <?php if ($model && !empty($model->data)): ?>
        <?php if ($apiUrl): ?>
            <div class="api-url-section">
                <p><strong>API URL:</strong> <code><?= Html::encode($apiUrl) ?></code></p>
            </div>
            
            <div class="api-data-section">
                <?php if ($apiError): ?>
                    <div class="alert alert-danger">
                        <strong>Error:</strong> <?= Html::encode($apiError) ?>
                    </div>
                <?php elseif ($apiData !== null): ?>
                    <div class="alert alert-success">
                        <strong>Success:</strong> Data loaded from NetSuite API
                    </div>
                    <pre><?= Html::encode(Json::encode($apiData, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)) ?></pre>
                <?php else: ?>
                    <p>Loading API data...</p>
                <?php endif; ?>
            </div>
        <?php else: ?>
            <div class="alert alert-warning">
                <p>No NetSuite API link found in product data.</p>
            </div>
        <?php endif; ?>
    <?php else: ?>
        <div class="alert alert-info">
            <p>No product data available.</p>
        </div>
    <?php endif; ?>
</div>

<style>
.netsuite-api-data {
    padding: 20px;
}

.api-url-section {
    margin-bottom: 20px;
    padding: 15px;
    background-color: #f5f5f5;
    border-radius: 4px;
    border-left: 4px solid #0275d8;
}

.api-url-section code {
    background-color: #fff;
    padding: 2px 6px;
    border-radius: 3px;
    font-size: 0.9em;
    word-break: break-all;
}

.api-data-section {
    padding: 15px;
    background-color: #f9f9f9;
    border-radius: 4px;
    border: 1px solid #ddd;
}

.api-data-section pre {
    background-color: #fff;
    padding: 10px;
    border-radius: 3px;
    overflow-x: auto;
    max-height: 600px;
    margin: 10px 0 0 0;
}

.alert {
    padding: 12px;
    margin-bottom: 15px;
    border-radius: 4px;
    margin-top: 0;
}

.alert-success {
    background-color: #d4edda;
    color: #155724;
    border: 1px solid #c3e6cb;
}

.alert-warning {
    background-color: #fff3cd;
    color: #856404;
    border: 1px solid #ffeaa7;
}

.alert-info {
    background-color: #d1ecf1;
    color: #0c5460;
    border: 1px solid #bee5eb;
}

.alert-danger {
    background-color: #f8d7da;
    color: #721c24;
    border: 1px solid #f5c6cb;
}
</style>
