<?php
$accounts = [];
try {
    if (can_see('accounts')) {
        $accounts = \App\Models\Account::allForSelect();
    }
} catch (Throwable $e) {
    $accounts = [];
}
$taskLeads = [];
try {
    if (can_see('leads')) {
        $taskLeads = \App\Models\Lead::allForSelect();
    }
} catch (Throwable $e) {
    $taskLeads = [];
}
$taskDeals = [];
try {
    if (can_see('opportunities')) {
        $taskDeals = \App\Models\Opportunity::allForSelect();
    }
} catch (Throwable $e) {
    $taskDeals = [];
}
$owners = [];
try {
    $tid = \App\Core\Auth::instance()->tenantId();
    if ($tid) {
        $owners = \App\Models\User::salespeople($tid);
    }
} catch (Throwable $e) {
    $owners = [];
}
$pipelineStages = [];
try {
    if (can_see('opportunities')) {
        $pipelineStages = \App\Models\PipelineStage::allActive();
    }
} catch (Throwable $e) {
    $pipelineStages = [];
}
$qaTabs = [];
if (can_edit('leads')) {
    $qaTabs[] = ['id' => 'qa-lead', 'label' => noun('lead', 'Lead'), 'icon' => 'bi-person-plus', 'hint' => 'A new person to qualify'];
}
if (can_edit('accounts')) {
    $qaTabs[] = ['id' => 'qa-account', 'label' => noun('account', 'Account'), 'icon' => 'bi-buildings', 'hint' => 'A company you sell to'];
}
if (can_edit('opportunities')) {
    $qaTabs[] = ['id' => 'qa-opp', 'label' => noun('opportunity', 'Deal'), 'icon' => 'bi-briefcase', 'hint' => 'A deal on an account'];
}
if (can_edit('tasks')) {
    $qaTabs[] = ['id' => 'qa-task', 'label' => 'Task', 'icon' => 'bi-check2-square', 'hint' => 'Something to do next'];
}
if (can_edit('tasks')) {
    $qaTabs[] = ['id' => 'qa-call', 'label' => 'Call', 'icon' => 'bi-telephone', 'hint' => 'Log a call on a record'];
}
if (can_edit('emails')) {
    $qaTabs[] = ['id' => 'qa-email', 'label' => 'Email', 'icon' => 'bi-envelope', 'hint' => 'Log a one-to-one message'];
}
if (can_edit('tasks')) {
    $qaTabs[] = ['id' => 'qa-note', 'label' => 'Note', 'icon' => 'bi-sticky', 'hint' => 'A quick note on the record'];
}
if (can_edit('opportunities')) {
    $qaTabs[] = ['id' => 'qa-stage', 'label' => 'Stage', 'icon' => 'bi-flag', 'hint' => 'Move a deal to the next stage'];
}
$qaFirst = $qaTabs[0]['id'] ?? '';
if ($qaTabs === []) {
    return;
}
?>
<div class="modal fade" id="quickAddModal" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered qa-dialog">
    <div class="modal-content qa-modal">
      <div class="qa-head">
        <div class="qa-head-icon"><i class="bi bi-plus-lg"></i></div>
        <div class="min-w-0 flex-grow-1">
          <h5 class="modal-title">Add new</h5>
          <p class="qa-head-sub mb-0">Pick a type, fill a few fields, and save.</p>
        </div>
        <button class="btn-close btn-close-white" type="button" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body qa-body">
        <?php if ($qaTabs): ?>
        <div class="qa-tabs nav" role="tablist">
          <?php foreach ($qaTabs as $tab): ?>
            <button class="nav-link qa-tab <?= $tab['id'] === $qaFirst ? 'active' : '' ?>" data-bs-toggle="pill" data-bs-target="#<?= e($tab['id']) ?>" type="button">
              <span class="qa-tab-icon"><i class="bi <?= e($tab['icon']) ?>"></i></span>
              <?= e($tab['label']) ?>
            </button>
          <?php endforeach; ?>
        </div>
        <?php endif; ?>

        <div class="tab-content">
          <?php if (can_edit('leads')): ?>
          <form class="tab-pane fade <?= $qaFirst === 'qa-lead' ? 'show active' : '' ?> ajax-form" id="qa-lead" action="<?= e(url('leads')) ?>" method="post">
            <?= csrf_field() ?>
            <p class="qa-pane-hint">A new person to qualify or convert.</p>
            <div class="qa-fields">
              <div class="qa-field"><label class="form-label">First name *</label><input class="form-control" name="first_name" required maxlength="80" placeholder="First"></div>
              <?php if (show_field('lead_create', 'last_name')): ?>
              <div class="qa-field"><label class="form-label">Last name</label><input class="form-control" name="last_name" maxlength="80" placeholder="Last"></div>
              <?php endif; ?>
              <?php if (show_field('lead_create', 'company')): ?>
              <div class="qa-field"><label class="form-label">Company</label><input class="form-control" name="company" maxlength="180" placeholder="Company name"></div>
              <?php endif; ?>
              <?php if (show_field('lead_create', 'source')): ?>
              <div class="qa-field"><label class="form-label">Source</label>
                <select class="form-select" name="source">
                  <option value="">Select</option>
                  <option>Website</option><option>Referral</option><option>Call</option><option>Trade show</option><option>Other</option>
                </select>
              </div>
              <?php endif; ?>
              <?php if (show_field('lead_create', 'email')): ?>
              <div class="qa-field"><label class="form-label">Email</label><input class="form-control" type="email" name="email" placeholder="name@company.com"></div>
              <?php endif; ?>
              <?php if (show_field('lead_create', 'phone')): ?>
              <div class="qa-field"><label class="form-label">Phone</label><input class="form-control" name="phone" placeholder="555-0000"></div>
              <?php endif; ?>
            </div>
            <?php \App\Core\View::partial('industry_fields', ['fields' => entity_fields('lead'), 'values' => [], 'form' => 'lead_create']); ?>
            <button class="btn btn-primary qa-submit" type="submit"><i class="bi bi-person-plus"></i> Create lead</button>
          </form>
          <?php endif; ?>
          <?php if (can_edit('accounts')): ?>
          <form class="tab-pane fade <?= $qaFirst === 'qa-account' ? 'show active' : '' ?> ajax-form" id="qa-account" action="<?= e(url('accounts')) ?>" method="post">
            <?= csrf_field() ?>
            <p class="qa-pane-hint">A company you sell to.</p>
            <div class="qa-fields">
              <div class="qa-field"><label class="form-label"><?= e(noun('account', 'Account')) ?> name *</label>
                <input class="form-control" name="name" required maxlength="180" placeholder="Company name"></div>
              <div class="qa-field"><label class="form-label">Phone</label>
                <input class="form-control" name="phone" placeholder="555-0000"></div>
              <div class="qa-field"><label class="form-label">Email</label>
                <input class="form-control" type="email" name="email" placeholder="hello@company.com"></div>
            </div>
            <?php \App\Core\View::partial('industry_fields', ['fields' => entity_fields('account'), 'values' => []]); ?>
            <button class="btn btn-primary qa-submit" type="submit"><i class="bi bi-buildings"></i> Create account</button>
          </form>
          <?php endif; ?>
          <?php if (can_edit('opportunities')): ?>
          <form class="tab-pane fade <?= $qaFirst === 'qa-opp' ? 'show active' : '' ?> ajax-form" id="qa-opp" action="<?= e(url('opportunities')) ?>" method="post">
            <?= csrf_field() ?>
            <p class="qa-pane-hint">A deal tied to an account.</p>
            <div class="qa-fields">
              <div class="qa-field"><label class="form-label">Name *</label>
                <input class="form-control" name="name" required placeholder="Deal name"></div>
              <div class="qa-field"><label class="form-label">Account *</label>
                <select class="form-select" name="account_id" required>
                  <option value="">Select account</option>
                  <?php foreach ($accounts as $a): ?><option value="<?= (int) $a['id'] ?>"><?= e($a['name']) ?></option><?php endforeach; ?>
                </select></div>
              <?php if (show_field('opportunity_create', 'amount')): ?>
              <div class="qa-field"><label class="form-label">Amount</label>
                <input class="form-control" name="amount" type="number" min="0" step="0.01" placeholder="0"></div>
              <?php endif; ?>
            </div>
            <?php \App\Core\View::partial('industry_fields', ['fields' => entity_fields('opportunity'), 'values' => [], 'form' => 'opportunity_create']); ?>
            <button class="btn btn-primary qa-submit" type="submit"><i class="bi bi-briefcase"></i> Create <?= e(noun('opportunity', 'deal')) ?></button>
          </form>
          <?php endif; ?>
          <?php if (can_edit('tasks')): ?>
          <form class="tab-pane fade <?= $qaFirst === 'qa-task' ? 'show active' : '' ?> ajax-form" id="qa-task" action="<?= e(url('tasks')) ?>" method="post" enctype="multipart/form-data">
            <?= csrf_field() ?>
            <p class="qa-pane-hint">Something to do next. Link it to a lead, deal, or account.</p>
            <div class="qa-fields">
              <div class="qa-field"><label class="form-label">Task *</label>
                <input class="form-control" name="title" required maxlength="180" placeholder="What needs to happen?"></div>
              <div class="qa-field"><label class="form-label">Related to</label>
                <select class="form-select" id="qa-task-related-type" name="related_type">
                  <option value="">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 js-task-related 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 js-task-related 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 js-task-related 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>
              <?php if ($owners): ?>
              <div class="qa-field"><label class="form-label">Owner</label>
                <select class="form-select" name="owner_id">
                  <?php foreach ($owners as $o): ?>
                    <option value="<?= (int) $o['id'] ?>" <?= (int) $o['id'] === (int) auth()->id() ? 'selected' : '' ?>><?= e($o['first_name'] . ' ' . $o['last_name']) ?></option>
                  <?php endforeach; ?>
                </select></div>
              <?php endif; ?>
              <div class="qa-field"><label class="form-label">Date</label>
                <input class="form-control" type="date" name="due_date"></div>
              <div class="qa-field"><label class="form-label">Time</label>
                <input class="form-control" type="time" name="due_time"></div>
              <div class="qa-field"><label class="form-label">Priority</label>
                <select class="form-select" name="priority">
                  <option value="normal">Normal</option>
                  <option value="high">High</option>
                  <option value="low">Low</option>
                </select></div>
              <div class="qa-field"><label class="form-label">File</label>
                <input class="form-control" type="file" name="file" accept=".pdf,.doc,.docx,.jpg,.jpeg,.png,application/pdf,image/jpeg,image/png,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document">
                <p class="qa-pane-hint mb-0 mt-1">Optional. PDF, Word, JPEG, or PNG. Up to 8 MB.</p></div>
            </div>
            <button class="btn btn-primary qa-submit" type="submit"><i class="bi bi-check2-square"></i> Create task</button>
          </form>
          <form class="tab-pane fade <?= $qaFirst === 'qa-note' ? 'show active' : '' ?> ajax-form" id="qa-note" action="<?= e(url('activities')) ?>" method="post" enctype="multipart/form-data">
            <?= csrf_field() ?>
            <input type="hidden" name="type" value="note">
            <p class="qa-pane-hint">A short note on a lead, deal, or account. You can attach a file.</p>
            <div class="qa-fields">
              <div class="qa-field"><label class="form-label">Note *</label>
                <input class="form-control" name="subject" required placeholder="What happened?"></div>
              <?php \App\Core\View::partial('qa_related_fields', [
                  'selectId' => 'qa-note-related-type',
                  'boxClass' => 'js-note-related',
                  'needRecord' => true,
                  'taskLeads' => $taskLeads,
                  'taskDeals' => $taskDeals,
                  'accounts' => $accounts,
              ]); ?>
              <div class="qa-field"><label class="form-label">File</label>
                <input class="form-control" type="file" name="file" accept=".pdf,.doc,.docx,.jpg,.jpeg,.png,application/pdf,image/jpeg,image/png,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document">
                <p class="qa-pane-hint mb-0 mt-1">Optional. PDF, Word, JPEG, or PNG. Up to 8 MB.</p></div>
              <div class="qa-wide"><label class="form-label">Details</label>
                <textarea class="form-control" name="body" rows="3" placeholder="Details (optional)"></textarea></div>
            </div>
            <button class="btn btn-primary qa-submit" type="submit"><i class="bi bi-sticky"></i> Save note</button>
          </form>
          <form class="tab-pane fade <?= $qaFirst === 'qa-call' ? 'show active' : '' ?> ajax-form" id="qa-call" action="<?= e(url('activities')) ?>" method="post">
            <?= csrf_field() ?>
            <input type="hidden" name="type" value="call">
            <p class="qa-pane-hint">Log a call on a lead, deal, or account.</p>
            <div class="qa-fields">
              <div class="qa-field"><label class="form-label">Call *</label>
                <input class="form-control" name="subject" required placeholder="Who did you call?"></div>
              <?php \App\Core\View::partial('qa_related_fields', [
                  'selectId' => 'qa-call-related-type',
                  'boxClass' => 'js-call-related',
                  'needRecord' => true,
                  'taskLeads' => $taskLeads,
                  'taskDeals' => $taskDeals,
                  'accounts' => $accounts,
              ]); ?>
              <div class="qa-wide"><label class="form-label">Details</label>
                <textarea class="form-control" name="body" rows="3" placeholder="What you talked about (optional)"></textarea></div>
            </div>
            <button class="btn btn-primary qa-submit" type="submit"><i class="bi bi-telephone"></i> Save call</button>
          </form>
          <?php endif; ?>
          <?php if (can_edit('emails')): ?>
          <form class="tab-pane fade <?= $qaFirst === 'qa-email' ? 'show active' : '' ?> ajax-form" id="qa-email" action="<?= e(url('emails')) ?>" method="post" data-reload="false">
            <?= csrf_field() ?>
            <input type="hidden" id="qa-email-related-type" name="related_type" value="">
            <input type="hidden" id="qa-email-related-id" name="related_id" value="">
            <p class="qa-pane-hint">Log a one-to-one message.</p>
            <div class="qa-fields">
              <div class="qa-field"><label class="form-label">To *</label>
                <input class="form-control" type="email" name="to_email" required placeholder="name@company.com"></div>
              <div class="qa-field"><label class="form-label">Subject *</label>
                <input class="form-control" name="subject" required placeholder="Subject"></div>
              <div class="qa-wide"><label class="form-label">Message</label>
                <textarea class="form-control" name="body" rows="4" placeholder="What you sent or received"></textarea></div>
            </div>
            <button class="btn btn-primary qa-submit" type="submit"><i class="bi bi-envelope"></i> Log email</button>
          </form>
          <?php endif; ?>
          <?php if (can_edit('opportunities')): ?>
          <form class="tab-pane fade <?= $qaFirst === 'qa-stage' ? 'show active' : '' ?> ajax-form" id="qa-stage" action="<?= e(url('opportunities')) ?>" method="post" enctype="multipart/form-data">
            <?= csrf_field() ?>
            <p class="qa-pane-hint">Move an open deal to a new stage.</p>
            <div class="qa-fields">
              <div class="qa-field"><label class="form-label"><?= e(opportunity_label()) ?> *</label>
                <select class="form-select" id="qa-stage-deal" name="opportunity_id" required>
                  <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"><label class="form-label">New stage *</label>
                <select class="form-select js-stage-select" name="stage_id" required>
                  <option value=""><?= $pipelineStages ? 'Select' : 'No stages' ?></option>
                  <?php foreach ($pipelineStages as $st): ?>
                    <option value="<?= (int) $st['id'] ?>" data-paper="<?= e(stage_paper_kind($st)) ?>"><?= e($st['name']) ?></option>
                  <?php endforeach; ?>
                </select></div>
              <div class="qa-field"><label class="form-label">Win / loss reason</label>
                <input class="form-control" name="win_loss_reason" placeholder="Required if you close as lost"></div>
              <?php \App\Core\View::partial('stage_paper_field', [
                  'hint' => 'Required for Proposal and Agreement unless that deal already has the PDF.',
              ]); ?>
            </div>
            <button class="btn btn-primary qa-submit" type="submit"><i class="bi bi-flag"></i> Update stage</button>
          </form>
          <?php endif; ?>
        </div>
      </div>
    </div>
  </div>
</div>
