<?php 
namespace PortalPeople\netsuite\controllers;
use Yii;
use backend\models\Cartsbe;
class NetsuiteController extends \yii\web\Controller
{
     /**
     * Links Order to Netsuite, Pops a modal.
     *
     * @param [type] $id
     * @return void
     */
    public function actionLinktons($id)
    {
        $netsuiteConfig = Yii::$app->params['netsuite'] ?? [];
        $cartClass = $netsuiteConfig['cartClass'] ?? 'backend\models\Cartsbe';
        
        $model = $cartClass::findOne($id, 'en');
        $netsuite = $model->data->netsuite;
        Yii::$app->response->format = 'json';
        if (Yii::$app->request->isGet == true) {
            return $this->renderAjax('@PortalPeople/netsuite/views/cart/linktons', ['model' => $model, 'netsuite' => $netsuite]);
        } elseif (Yii::$app->request->isPost == true && $netsuite->load(Yii::$app->request->post()) && $netsuite->validate() && $model->save()) {
            return ['status' => 200, 'Message' => 'Linked'];
        } elseif (Yii::$app->request->isPost) {
            return ['status' => 100, 'Message' => 'Error'];
        }
    }

    public function actionSendordertonetsuite(){
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $netsuiteConfig = Yii::$app->params['netsuite'] ?? [];
        $cartClass = $netsuiteConfig['cartClass'] ?? 'backend\models\Cartsbe';
        $id = Yii::$app->request->post('id');
        $model = $cartClass::findOne($id, 'en');
        if($model){
            try {
                $result = \PortalPeople\netsuite\components\NetSuite::SendOrderToNetsuite($id);
                
                // Handle response - check statusCode (HttpClient) or status (custom object)
                $statusCode = $result->statusCode ?? $result->status ?? 0;
                
                if((int)$statusCode >= 200 && (int)$statusCode < 300){
                    $message = 'Order sent to NetSuite successfully.';
                    if (!empty($result->already_exists)) {
                        $message = 'Order already exists in NetSuite.';
                    }
                    return ['status' => 200, 'Message' => $message];
                }else{
                    $errorMsg = isset($result->content) ? $result->content : 'Unknown error';
                    if (is_object($errorMsg)) {
                        $errorMsg = json_encode($errorMsg);
                    }
                    return ['status' => 100, 'Message' => 'Failed to send order to NetSuite: ' . $errorMsg];
                }
            } catch (\Exception $e) {
                Yii::error("Error sending order to NetSuite: " . $e->getMessage());
                return ['status' => 100, 'Message' => 'Error sending to NetSuite: ' . $e->getMessage()];
            }
        }else{
            return ['status' => 100, 'Message' => 'Cart not found.'];
        }
    }

    public function actionGetorder(){
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $id = Yii::$app->request->get('id') ?? Yii::$app->request->post('id');
        if (!$id) {
            return ['status' => 100, 'Message' => 'No cart ID provided.'];
        }

        $netsuiteConfig = Yii::$app->params['netsuite'] ?? [];
        $cartClass = $netsuiteConfig['cartClass'] ?? 'backend\models\Cartsbe';
        $model = $cartClass::findOne($id);
        if (!$model) {
            return ['status' => 100, 'Message' => 'Cart not found.'];
        }

        $externalId = $model->id . '/F';
        $order = \PortalPeople\netsuite\components\NetSuite::GetSalesOrderByExternalId($externalId);

        if ($order === null) {
            return ['status' => 404, 'Message' => "No NetSuite sales order found for externalId: {$externalId}"];
        }

        return ['status' => 200, 'order' => $order];
    }

    public function actionGetorderfromnetsuite($id){
        
      return \PortalPeople\netsuite\components\NetSuite::GetSendOrderfromNetsuite($id);
    }

    public function actionGetordermeta(){
        $this->layout = false;

        $raw = Yii::$app->netsuiteClient->getMetadataCatalog('salesorder');
        $properties = $raw['properties'] ?? [];
        $fields = [];

        foreach ($properties as $key => $prop) {
            $type = $prop['type'] ?? 'object';

            if ($type === 'object' && isset($prop['properties']['items']['type']) && $prop['properties']['items']['type'] === 'array') {
                $subFields = [];
                foreach ($prop['properties']['items']['items']['properties'] ?? [] as $subKey => $subProp) {
                    if (in_array($subKey, ['links', 'refName'])) continue;
                    $subFields[] = [
                        'field'    => $subKey,
                        'title'    => $subProp['title'] ?? null,
                        'type'     => $subProp['type'] ?? 'object',
                        'format'   => $subProp['format'] ?? null,
                        'nullable' => $subProp['nullable'] ?? false,
                        'custom'   => isset($subProp['x-ns-custom-field']),
                    ];
                }
                $fields[$key] = [
                    'field'     => $key,
                    'title'     => $prop['title'] ?? null,
                    'type'      => 'sublist',
                    'subFields' => $subFields,
                    'custom'    => isset($prop['x-ns-custom-field']),
                ];
                continue;
            }

            $fields[$key] = [
                'field'       => $key,
                'title'       => $prop['title'] ?? null,
                'type'        => $type,
                'format'      => $prop['format'] ?? null,
                'nullable'    => $prop['nullable'] ?? false,
                'custom'      => isset($prop['x-ns-custom-field']),
                'enum'        => $prop['properties']['id']['enum'] ?? ($prop['enum'] ?? null),
                'description' => isset($prop['description']) ? substr(strip_tags($prop['description']), 0, 120) : null,
            ];
        }

        uasort($fields, function($a, $b) {
            if ($a['custom'] !== $b['custom']) return $a['custom'] ? 1 : -1;
            return strcmp($a['field'], $b['field']);
        });

        $totalFields    = count($fields);
        $standardFields = count(array_filter($fields, fn($f) => !$f['custom']));
        $customFields   = count(array_filter($fields, fn($f) => $f['custom']));

        $typeColour = function(string $type): string {
            return match($type) {
                'string'  => '#0d6efd',
                'integer' => '#198754',
                'number'  => '#198754',
                'boolean' => '#dc3545',
                'object'  => '#6f42c1',
                'sublist' => '#fd7e14',
                default   => '#6c757d',
            };
        };

        ob_start(); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>NetSuite Sales Order Metadata</title>
<style>
  *, *::before, *::after { box-sizing: border-box; }
  body { font-family: system-ui, sans-serif; font-size: 13px; background: #f8f9fa; color: #212529; margin: 0; padding: 20px; }
  h1 { font-size: 1.4rem; margin-bottom: 4px; }
  .stats { display: flex; gap: 12px; margin-bottom: 16px; flex-wrap: wrap; }
  .stat { background: #fff; border: 1px solid #dee2e6; border-radius: 6px; padding: 8px 16px; text-align: center; }
  .stat strong { display: block; font-size: 1.5rem; }
  .stat span { color: #6c757d; font-size: 11px; }
  .controls { margin-bottom: 12px; display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
  input[type=search] { padding: 5px 10px; border: 1px solid #ced4da; border-radius: 4px; font-size: 13px; width: 260px; }
  label { font-size: 12px; display: flex; align-items: center; gap: 4px; cursor: pointer; }
  table { width: 100%; border-collapse: collapse; background: #fff; border-radius: 8px; overflow: hidden; box-shadow: 0 1px 3px rgba(0,0,0,.1); }
  thead th { background: #212529; color: #fff; padding: 8px 10px; text-align: left; white-space: nowrap; position: sticky; top: 0; }
  tbody tr:nth-child(even) { background: #f8f9fa; }
  tbody tr:hover { background: #e9ecef; }
  td { padding: 6px 10px; vertical-align: top; border-bottom: 1px solid #dee2e6; }
  .badge { display: inline-block; padding: 1px 7px; border-radius: 20px; font-size: 11px; font-weight: 600; color: #fff; white-space: nowrap; }
  .badge-custom { background: #6f42c1; }
  .badge-null  { background: #adb5bd; }
  code { font-size: 12px; background: #e9ecef; padding: 1px 5px; border-radius: 3px; }
  .field-name { font-family: monospace; font-size: 12px; }
  details summary { cursor: pointer; color: #fd7e14; font-size: 11px; }
  details table { margin-top: 4px; }
  details thead th { background: #fd7e14; font-size: 11px; }
  .hidden { display: none; }
</style>
</head>
<body>
<h1>NetSuite &mdash; Sales Order Field Metadata</h1>
<div class="stats">
  <div class="stat"><strong><?= $totalFields ?></strong><span>Total Fields</span></div>
  <div class="stat"><strong><?= $standardFields ?></strong><span>Standard</span></div>
  <div class="stat"><strong><?= $customFields ?></strong><span>Custom (custbody_*)</span></div>
</div>
<div class="controls">
  <input type="search" id="search" placeholder="Search field name or title&hellip;" oninput="filterTable()">
  <label><input type="checkbox" id="hideCustom" onchange="filterTable()"> Hide custom fields</label>
  <label><input type="checkbox" id="hideStandard" onchange="filterTable()"> Hide standard fields</label>
</div>
<table id="metaTable">
  <thead>
    <tr>
      <th>#</th>
      <th>Field Name</th>
      <th>Title</th>
      <th>Type</th>
      <th>Format</th>
      <th>Nullable</th>
      <th>Custom</th>
      <th>Enum / Description</th>
    </tr>
  </thead>
  <tbody>
<?php $i = 0; foreach ($fields as $f): $i++; ?>
    <tr data-custom="<?= $f['custom'] ? '1' : '0' ?>">
      <td><?= $i ?></td>
      <td><span class="field-name"><?= htmlspecialchars($f['field']) ?></span></td>
      <td><?= htmlspecialchars((string)($f['title'] ?? '')) ?></td>
      <td><span class="badge" style="background:<?= $typeColour($f['type']) ?>"><?= htmlspecialchars($f['type']) ?></span></td>
      <td><?= !empty($f['format'] ?? null) ? '<code>'.htmlspecialchars($f['format']).'</code>' : '' ?></td>
      <td><?= ($f['nullable'] ?? false) ? '<span class="badge badge-null">null</span>' : '' ?></td>
      <td><?= $f['custom'] ? '<span class="badge badge-custom">custom</span>' : '' ?></td>
      <td>
        <?php if ($f['type'] === 'sublist' && !empty($f['subFields'])): ?>
          <details>
            <summary><?= count($f['subFields']) ?> sub-fields</summary>
            <table>
              <thead><tr><th>Field</th><th>Title</th><th>Type</th><th>Format</th><th>Custom</th></tr></thead>
              <tbody>
              <?php foreach ($f['subFields'] as $sf): ?>
                <tr>
                  <td class="field-name"><?= htmlspecialchars($sf['field']) ?></td>
                  <td><?= htmlspecialchars((string)($sf['title'] ?? '')) ?></td>
                  <td><span class="badge" style="background:<?= $typeColour($sf['type']) ?>"><?= htmlspecialchars($sf['type']) ?></span></td>
                  <td><?= $sf['format'] ? '<code>'.htmlspecialchars($sf['format']).'</code>' : '' ?></td>
                  <td><?= $sf['custom'] ? '<span class="badge badge-custom">custom</span>' : '' ?></td>
                </tr>
              <?php endforeach; ?>
              </tbody>
            </table>
          </details>
        <?php elseif (!empty($f['enum'])): ?>
          <details>
            <summary><?= count($f['enum']) ?> enum values</summary>
            <div style="font-size:11px;margin-top:4px"><?= implode(', ', array_map('htmlspecialchars', $f['enum'])) ?></div>
          </details>
        <?php else: ?>
          <span style="color:#6c757d;font-size:11px"><?= htmlspecialchars((string)($f['description'] ?? '')) ?></span>
        <?php endif; ?>
      </td>
    </tr>
<?php endforeach; ?>
  </tbody>
</table>
<script>
function filterTable() {
  const q = document.getElementById('search').value.toLowerCase();
  const hideCustom = document.getElementById('hideCustom').checked;
  const hideStandard = document.getElementById('hideStandard').checked;
  document.querySelectorAll('#metaTable tbody tr').forEach(row => {
    const isCustom = row.dataset.custom === '1';
    const text = row.innerText.toLowerCase();
    const matchSearch = !q || text.includes(q);
    const matchFilter = !(hideCustom && isCustom) && !(hideStandard && !isCustom);
    row.classList.toggle('hidden', !matchSearch || !matchFilter);
  });
}
</script>
</body>
</html>
<?php
        return ob_get_clean();
    }
}
