<?php
$selectId = $selectId ?? 'qa-related-type';
$boxClass = $boxClass ?? 'js-related';
$needRecord = !empty($needRecord);
$taskLeads = $taskLeads ?? [];
$taskDeals = $taskDeals ?? [];
$accounts = $accounts ?? [];
?>
<div class="qa-field">
  <label class="form-label">Related to<?= $needRecord ? ' *' : '' ?></label>
  <select class="form-select" id="<?= e($selectId) ?>" name="related_type" <?= $needRecord ? 'required' : '' ?>>
    <option value=""><?= $needRecord ? 'Select' : 'None' ?></option>
    <?php if (can_see('leads')): ?><option value="lead"><?= e(noun('lead', 'Lead')) ?></option><?php endif; ?>
    <?php if (can_see('opportunities')): ?><option value="opportunity"><?= e(opportunity_label()) ?></option><?php endif; ?>
    <?php if (can_see('accounts')): ?><option value="account"><?= e(noun('account', 'Account')) ?></option><?php endif; ?>
  </select>
</div>
<div class="qa-field <?= e($boxClass) ?> d-none" data-type="lead">
  <label class="form-label"><?= e(noun('lead', 'Lead')) ?></label>
  <select class="form-select" name="related_id" disabled>
    <option value=""><?= $taskLeads ? 'Select' : 'No open leads' ?></option>
    <?php foreach ($taskLeads as $leadOpt):
        $leadName = trim(($leadOpt['first_name'] ?? '') . ' ' . ($leadOpt['last_name'] ?? ''));
        $co = trim((string) ($leadOpt['company'] ?? ''));
    ?>
      <option value="<?= (int) $leadOpt['id'] ?>"><?= e($leadName !== '' ? $leadName : 'Lead') ?><?= $co !== '' ? ' · ' . e($co) : '' ?></option>
    <?php endforeach; ?>
  </select>
</div>
<div class="qa-field <?= e($boxClass) ?> d-none" data-type="opportunity">
  <label class="form-label"><?= e(opportunity_label()) ?></label>
  <select class="form-select" name="related_id" disabled>
    <option value=""><?= $taskDeals ? 'Select' : 'No open deals' ?></option>
    <?php foreach ($taskDeals as $dealOpt): ?>
      <option value="<?= (int) $dealOpt['id'] ?>"><?= e($dealOpt['name']) ?><?php if (!empty($dealOpt['account_name'])): ?> · <?= e($dealOpt['account_name']) ?><?php endif; ?></option>
    <?php endforeach; ?>
  </select>
</div>
<div class="qa-field <?= e($boxClass) ?> d-none" data-type="account">
  <label class="form-label"><?= e(noun('account', 'Account')) ?></label>
  <select class="form-select" name="related_id" disabled>
    <option value=""><?= $accounts ? 'Select' : 'No accounts' ?></option>
    <?php foreach ($accounts as $a): ?>
      <option value="<?= (int) $a['id'] ?>"><?= e($a['name']) ?></option>
    <?php endforeach; ?>
  </select>
</div>
