<?php
use App\Services\SetupDefaults;
$forms = $draft['forms'] ?? [];
$formMeta = [
    'lead_create' => ['Add a lead', 'What shows in Add New → Lead'],
    'opportunity_create' => ['Add a deal', 'What shows in Add New → Deal'],
    'visit' => ['Visit', 'Assigned technician / consultant'],
    'service_request' => ['Service request', 'Subject, visit date, and details'],
];
$entityFor = ['lead_create' => 'lead', 'opportunity_create' => 'opportunity', 'visit' => 'service', 'service_request' => 'service'];
?>
<div class="sup-page">
  <?php \App\Core\View::partial('setup_nav', compact('section', 'dirty', 'canUndo', 'publishedAt')); ?>
  <form class="set-section ajax-form" action="<?= e(url('setup/save')) ?>" method="post">
    <?= csrf_field() ?>
    <input type="hidden" name="section" value="forms">
    <div class="set-section-head">
      <div>
        <div class="set-section-title"><i class="bi bi-ui-checks-grid"></i> 5. Form builder</div>
        <p class="set-section-sub">Choose which boxes show when someone creates a lead, deal, visit, or service request. Locked boxes stay on.</p>
      </div>
      <button class="btn btn-primary" type="submit">Save draft</button>
    </div>
    <div class="sup-form-grid">
      <?php foreach ($formMeta as $form => $meta):
          $shown = $forms[$form] ?? array_keys(SetupDefaults::CORE_FORM_FIELDS[$form]);
          $locked = SetupDefaults::LOCKED_FORM_FIELDS[$form] ?? [];
          $choices = SetupDefaults::CORE_FORM_FIELDS[$form];
          foreach ($draft['fields'] ?? [] as $f) {
              if (($f['entity'] ?? '') === $entityFor[$form] && !empty($f['active'])) {
                  $choices[$f['key']] = $f['label'];
              }
          }
      ?>
        <article class="sup-form-card">
          <h2><?= e($meta[0]) ?></h2>
          <p><?= e($meta[1]) ?></p>
          <?php foreach ($choices as $key => $label):
              $isLocked = in_array($key, $locked, true);
          ?>
            <label class="sup-check <?= $isLocked ? 'is-lock' : '' ?>">
              <input type="checkbox" name="forms[<?= e($form) ?>][]" value="<?= e($key) ?>" <?= in_array($key, $shown, true) || $isLocked ? 'checked' : '' ?> <?= $isLocked ? 'disabled' : '' ?>>
              <?= e($label) ?>
              <?php if ($isLocked): ?>
                <input type="hidden" name="forms[<?= e($form) ?>][]" value="<?= e($key) ?>">
                <small>Required</small>
              <?php endif; ?>
            </label>
          <?php endforeach; ?>
        </article>
      <?php endforeach; ?>
    </div>
  </form>
</div>
