<?php use App\Core\View; ?>
<?php
$templates = $templates ?? [];
$prefill   = $prefill ?? null;
$groups    = $module['groups'] ?? [];

// Read by the footer: pull in TinyMCE only where there is a richtext field.
$needsEditor = (bool) array_filter($module['fields'], fn ($f) => $f['type'] === 'richtext');

/**
 * Split the fields into the buckets the form renders in order: one list per
 * declared group, then whatever is ungrouped, then the collapsed advanced
 * block, then the sticky save bar. Modules that declare no layout keys land
 * entirely in $ungrouped and render exactly as they did before.
 */
$buckets = ['advanced' => [], 'bar' => [], 'ungrouped' => []];
foreach ($groups as $key => $_) {
    $buckets[$key] = [];
}
foreach ($module['fields'] as $name => $field) {
    $bucket = match (true) {
        !empty($field['bar'])                          => 'bar',
        !empty($field['advanced'])                     => 'advanced',
        isset($groups[$field['group'] ?? ''])          => $field['group'],
        default                                        => 'ungrouped',
    };
    $buckets[$bucket][$name] = $field;
}

$renderField = function (string $name, array $field) use ($row, $prefill, $fks) {
    $label    = $field['label'] ?? ucwords(str_replace('_', ' ', $name));
    $value    = $row[$name] ?? ($prefill[$name] ?? ($field['default'] ?? ''));
    $required = !empty($field['required']) ? 'required' : '';
    $readonly = !empty($field['readonly']) ? 'readonly' : '';
    $showWhen = $field['showWhen'] ?? '';
    ?>
  <div class="field"<?= $showWhen ? ' data-show-when="f-' . View::e($showWhen) . '"' : '' ?>>
    <?php // A checkbox carries its own label inside the switch, so skip the heading. ?>
    <?php if ($field['type'] !== 'checkbox'): ?>
    <label for="f-<?= $name ?>"><?= View::e($label) ?><?= $required ? ' *' : '' ?></label>
    <?php endif; ?>

    <?php if ($field['type'] === 'textarea'): ?>
      <textarea id="f-<?= $name ?>" name="<?= $name ?>" rows="4" <?= $required ?>><?= View::e($value) ?></textarea>

    <?php elseif ($field['type'] === 'richtext'): ?>
      <textarea id="f-<?= $name ?>" name="<?= $name ?>" class="rte" rows="18"><?= View::e($value) ?></textarea>

    <?php elseif ($field['type'] === 'json'): ?>
      <textarea id="f-<?= $name ?>" name="<?= $name ?>" rows="<?= (int) ($field['rows'] ?? 4) ?>"
                class="mono" data-shape="<?= View::e($field['shape'] ?? '') ?>" <?= $required ?>><?= View::e($value) ?></textarea>

    <?php elseif ($field['type'] === 'checkbox'): ?>
      <label class="switch">
        <input type="hidden" name="<?= $name ?>" value="0">
        <input type="checkbox" id="f-<?= $name ?>" name="<?= $name ?>" value="1" <?= $value ? 'checked' : '' ?>>
        <span><?= View::e($label) ?></span>
      </label>

    <?php elseif ($field['type'] === 'select'): ?>
      <select id="f-<?= $name ?>" name="<?= $name ?>">
        <?php foreach ($field['options'] as $opt => $optLabel): ?>
        <option value="<?= View::e($opt) ?>" <?= (string) $value === (string) $opt ? 'selected' : '' ?>>
          <?= View::e($optLabel) ?>
        </option>
        <?php endforeach; ?>
      </select>

    <?php elseif ($field['type'] === 'fk'): ?>
      <select id="f-<?= $name ?>" name="<?= $name ?>">
        <option value="">—</option>
        <?php foreach ($fks[$name] ?? [] as $opt): ?>
        <option value="<?= (int) $opt['id'] ?>" <?= (string) $value === (string) $opt['id'] ? 'selected' : '' ?>>
          <?= View::e($opt['name']) ?>
        </option>
        <?php endforeach; ?>
      </select>

    <?php elseif ($field['type'] === 'image'): ?>
      <div class="image-field">
        <input type="text" id="f-<?= $name ?>" name="<?= $name ?>" value="<?= View::e($value) ?>"
               placeholder="https://… or upload →" <?= $required ?>>
        <label class="btn sm upload-btn">
          Upload<input type="file" accept="image/*" data-target="f-<?= $name ?>" hidden>
        </label>
      </div>
      <img class="preview" src="<?= View::e($value) ?>" alt="" <?= $value ? '' : 'hidden' ?>>

    <?php elseif ($field['type'] === 'password'): ?>
      <input type="password" id="f-<?= $name ?>" name="<?= $name ?>" autocomplete="new-password">

    <?php elseif ($field['type'] === 'number'): ?>
      <input type="number" id="f-<?= $name ?>" name="<?= $name ?>" value="<?= View::e($value) ?>"
             step="<?= View::e($field['step'] ?? '1') ?>" <?= $required ?>>

    <?php elseif ($field['type'] === 'date'): ?>
      <input type="date" id="f-<?= $name ?>" name="<?= $name ?>" value="<?= View::e($value) ?>" <?= $required ?>>

    <?php elseif ($field['type'] === 'time'): ?>
      <input type="time" id="f-<?= $name ?>" name="<?= $name ?>" value="<?= View::e($value) ?>" <?= $required ?>>

    <?php elseif ($field['type'] === 'datetime'): ?>
      <input type="datetime-local" id="f-<?= $name ?>" name="<?= $name ?>"
             value="<?= View::e($value ? str_replace(' ', 'T', substr((string) $value, 0, 16)) : '') ?>" <?= $required ?>>

    <?php else: ?>
      <input type="text" id="f-<?= $name ?>" name="<?= $name ?>" value="<?= View::e($value) ?>"
             <?= !empty($field['autoFrom']) ? 'data-auto-from="f-' . View::e($field['autoFrom']) . '"' : '' ?>
             <?= $required ?> <?= $readonly ?>>
    <?php endif; ?>

    <?php if (!empty($field['help'])): ?><small><?= View::e($field['help']) ?></small><?php endif; ?>
  </div>
    <?php
};

/** Render a bucket, wrapping consecutive fields that share a 'row' key. */
$renderFields = function (array $fields) use ($renderField) {
    $openRow = null;
    foreach ($fields as $name => $field) {
        $rowKey = $field['row'] ?? null;
        if ($rowKey !== $openRow) {
            if ($openRow !== null) {
                echo "</div>\n";
            }
            if ($rowKey !== null) {
                echo '<div class="field-row">' . "\n";
            }
            $openRow = $rowKey;
        }
        $renderField($name, $field);
    }
    if ($openRow !== null) {
        echo "</div>\n";
    }
};
?>
<header class="page-head">
  <h1><?= $row ? 'Edit' : 'New' ?> — <?= View::e($module['label']) ?></h1>
  <p><a href="<?= View::url("/admin/$moduleKey") ?>">← Back to list</a></p>
</header>

<?php if (!$row && $templates): ?>
<div class="panel form">
  <div class="field">
    <label for="tpl-from">Start from an existing <?= View::e(rtrim($module['label'], 's')) ?></label>
    <select id="tpl-from" onchange="if(this.value)location.href=this.value">
      <option value="">Blank — start from scratch</option>
      <?php $base = View::url("/admin/$moduleKey/create"); foreach ($templates as $t): ?>
      <option value="<?= $base ?>?from=<?= (int) $t['id'] ?>"
              <?= $prefill && (string) ($_GET['from'] ?? '') === (string) $t['id'] ? 'selected' : '' ?>>
        <?= View::e($t['label']) ?>
      </option>
      <?php endforeach; ?>
    </select>
    <small>Pick an existing entry to copy its content into the fields below, then adjust it. Nothing is saved until you click Save.</small>
  </div>
</div>
<?php endif; ?>

<form class="form" method="post"
      action="<?= View::url("/admin/$moduleKey" . ($row ? '/' . (int) $row['id'] : '') . '/save') ?>">
  <input type="hidden" name="_csrf" value="<?= $csrf ?>">

  <?php foreach ($groups as $key => $group): ?>
    <?php if (!$buckets[$key]) continue; ?>
  <section class="panel form-sec">
    <div class="form-sec-head">
      <span class="eyebrow"><?= View::e($group['label']) ?></span>
      <?php if (!empty($group['hint'])): ?><p><?= View::e($group['hint']) ?></p><?php endif; ?>
    </div>
    <?php $renderFields($buckets[$key]); ?>
  </section>
  <?php endforeach; ?>

  <?php if ($buckets['ungrouped']): ?>
  <div class="panel">
    <?php $renderFields($buckets['ungrouped']); ?>
  </div>
  <?php endif; ?>

  <?php if ($buckets['advanced']): ?>
  <details class="panel form-adv">
    <summary>Advanced — web address &amp; search listing</summary>
    <div class="form-adv-body">
      <?php $renderFields($buckets['advanced']); ?>
    </div>
  </details>
  <?php endif; ?>

  <div class="save-bar">
    <?php $renderFields($buckets['bar']); ?>
    <button class="btn primary" type="submit">Save</button>
  </div>
</form>
<script>window.__CSRF = <?= json_encode($csrf) ?>;</script>
