<?php
$o = $opp;
$dealWord = opportunity_label();
$owner = trim((string) ($o['owner_name'] ?? ''));
$account = trim((string) ($o['account_name'] ?? ''));
$stageName = trim((string) ($o['stage_name'] ?? ''));
$isWon = (int) ($o['is_won'] ?? 0) === 1;
$isLost = (int) ($o['is_lost'] ?? 0) === 1;
$tone = $isWon ? 'won' : ($isLost ? 'lost' : 'open');
$nextDue = due_label($o['next_step_at'] ?? null);
$stages = $stages ?? [];
$papers = $papers ?? [];
$hasPaper = $hasPaper ?? ['proposal' => false, 'agreement' => false];
$curSort = (int) ($o['sort_order'] ?? 0);
$curId = (int) ($o['stage_id'] ?? 0);
$feed = [];
$stageFeed = [];
foreach ($timeline ?? [] as $t) {
    $type = (string) ($t['type'] ?? '');
    if ($type === 'stage') {
        $stageFeed[] = $t;
        continue;
    }
    $feed[] = $t;
}
?>
<div class="rec-page opp-show">
  <a class="rec-back" href="<?= e(url('opportunities')) ?>"><i class="bi bi-arrow-left"></i> All <?= e(strtolower($dealWord) === 'deal' ? 'deals' : 'opportunities') ?></a>

  <div class="rec-hero rec-tone-<?= e($tone) ?>">
    <div class="rec-hero-main">
      <div class="rec-hero-avatar"><i class="bi bi-briefcase"></i></div>
      <div class="min-w-0">
        <p class="rec-kicker"><?= e($dealWord) ?> · an open sale on an account</p>
        <div class="d-flex flex-wrap align-items-center gap-2 mb-1">
          <h1 class="page-title mb-0"><?= e($o['name'] ?: 'Untitled') ?></h1>
          <span class="rec-status rec-status-<?= e($tone) ?>"><?= e($stageName !== '' ? $stageName : 'No stage') ?></span>
          <?php if ((float) ($o['amount'] ?? 0) > 0): ?>
            <span class="rec-amount"><?= e(money_fmt($o['amount'])) ?></span>
          <?php endif; ?>
        </div>
        <div class="rec-hero-sub">
          <?php if ($account !== ''): ?>
            <a href="<?= e(url('accounts/' . (int) $o['account_id'])) ?>"><i class="bi bi-buildings"></i> <?= e($account) ?></a>
          <?php endif; ?>
          <?php if ($owner !== ''): ?>
            <span class="task-owner-chip" title="<?= e($owner) ?>">
              <span class="task-avatar"><?= e(name_initials($owner)) ?></span>
              <span class="task-owner text-truncate"><?= e($owner) ?></span>
            </span>
          <?php endif; ?>
          <span class="text-muted">Added <?= e(dt_fmt($o['created_at'] ?? null, 'M j, Y')) ?></span>
        </div>
        <div class="rec-hero-contact">
          <span><i class="bi bi-flag"></i> Next: <?= e(trim((string) ($o['next_step'] ?? '')) !== '' ? $o['next_step'] : 'Not set') ?></span>
          <span class="<?= e($nextDue['class'] ?: 'text-muted') ?>"><i class="bi bi-calendar-event"></i> <?= e($nextDue['text'] !== '' ? $nextDue['text'] : 'No due date') ?></span>
          <?php if (!empty($o['close_date'])): ?>
            <span><i class="bi bi-hourglass-split"></i> Close <?= e(dt_fmt($o['close_date'], 'M j, Y')) ?></span>
          <?php endif; ?>
        </div>
      </div>
    </div>
    <div class="rec-hero-actions">
      <?php if ($isWon): ?>
        <div class="rec-banner is-won"><i class="bi bi-trophy-fill"></i><div><strong>Won</strong><div>This <?= e(strtolower($dealWord)) ?> is closed as won.</div></div></div>
      <?php elseif ($isLost): ?>
        <div class="rec-banner is-lost"><i class="bi bi-x-circle-fill"></i><div><strong>Lost</strong><div><?= e(trim((string) ($o['win_loss_reason'] ?? '')) !== '' ? $o['win_loss_reason'] : 'This deal did not close.') ?></div></div></div>
      <?php elseif (can_edit('quotes') || can_edit('orders') || can_edit('contracts') || can_edit('service_jobs')): ?>
        <p class="rec-action-hint">Create the paper that goes with a win: quote, order, contract, or job.</p>
        <form class="ajax-form" action="<?= e(url('opportunities/'.$o['id'].'/fulfill')) ?>" method="post">
          <?= csrf_field() ?>
          <button class="btn btn-primary" type="submit"><i class="bi bi-box-arrow-up-right"></i> Create quote / order / contract / job</button>
        </form>
      <?php endif; ?>
    </div>
  </div>

  <div class="row g-3">
    <div class="col-lg-8">
      <div class="card-soft rec-card p-3 mb-3">
        <?php \App\Core\View::partial('record_section_head', [
            'icon' => 'bi-signpost-split',
            'title' => 'Pipeline path',
            'hint' => 'Where this ' . strtolower($dealWord) . ' is. Move the stage in the box below when something changes.',
        ]); ?>
        <div class="rec-pipe">
          <?php foreach ($stages as $i => $step):
              $sid = (int) $step['id'];
              $sort = (int) ($step['sort_order'] ?? $i);
              $isCurrent = $sid === $curId;
              $isDone = !$isCurrent && !$isLost && $sort < $curSort;
              $isSkipped = $isLost && !$isCurrent;
              $code = !empty($step['is_won']) ? 'won' : (!empty($step['is_lost']) ? 'lost' : 'open');
          ?>
            <div class="rec-pipe-item is-<?= e($code) ?> <?= $isCurrent ? 'is-current' : '' ?> <?= $isDone ? 'is-done' : '' ?> <?= $isSkipped ? 'is-skipped' : '' ?>">
              <span class="rec-pipe-n"><?= $isDone ? '✓' : ($isCurrent ? '●' : (string) ($i + 1)) ?></span>
              <span class="rec-pipe-name"><?= e($step['name']) ?></span>
              <?php if ($isCurrent): ?><span class="rec-pipe-now">Now</span><?php endif; ?>
            </div>
          <?php endforeach; ?>
        </div>
      </div>

      <div class="card-soft rec-card p-3 mb-3">
        <?php \App\Core\View::partial('record_section_head', [
            'icon' => 'bi-pencil-square',
            'title' => 'Update this ' . strtolower($dealWord),
            'hint' => 'Change the name, amount, or next step. Then save. Use Move stage when the sale moves forward or is closed.',
        ]); ?>
        <form class="ajax-form rec-update" action="<?= e(url('opportunities/'.$o['id'])) ?>" method="post">
          <?= csrf_field() ?>
          <div class="qa-fields rec-fields">
            <div class="qa-field"><label class="form-label" for="opp-name">Name *</label>
              <input class="form-control" id="opp-name" name="name" value="<?= e($o['name']) ?>" required></div>
            <div class="qa-field"><label class="form-label" for="opp-amount">Amount</label>
              <input class="form-control" id="opp-amount" name="amount" type="number" min="0" step="0.01" value="<?= e($o['amount']) ?>"></div>
            <div class="qa-field"><label class="form-label" for="opp-next">Next step</label>
              <input class="form-control" id="opp-next" name="next_step" value="<?= e($o['next_step']) ?>" placeholder="What happens next?"></div>
            <div class="qa-field"><label class="form-label" for="opp-due">Next step due</label>
              <input class="form-control" id="opp-due" type="datetime-local" name="next_step_at" value="<?= !empty($o['next_step_at']) ? e(date('Y-m-d\TH:i', strtotime((string) $o['next_step_at']))) : '' ?>"></div>
          </div>
          <?php \App\Core\View::partial('industry_fields', ['fields' => entity_fields('opportunity'), 'values' => $attrs ?? []]); ?>
          <button class="btn btn-primary mt-3" type="submit"><i class="bi bi-check-lg"></i> Save changes</button>
        </form>

        <hr class="rec-split">
        <h3 class="rec-subhead">Move stage</h3>
        <p class="rec-section-hint mb-2">Pick the new stage. Proposal and Agreement need a PDF. If you close as lost, add a short reason.</p>
        <form class="ajax-form" action="<?= e(url('opportunities/'.$o['id'].'/stage')) ?>" method="post" enctype="multipart/form-data">
          <?= csrf_field() ?>
          <div class="qa-fields rec-fields">
            <div class="qa-field">
              <label class="form-label" for="opp-stage">New stage *</label>
              <select class="form-select js-stage-select" id="opp-stage" name="stage_id" required>
                <?php foreach ($stages as $s):
                    $paperKind = stage_paper_kind($s);
                    $already = $paperKind !== '' && !empty($hasPaper[$paperKind]);
                ?>
                  <option value="<?= (int) $s['id'] ?>" <?= (int) $s['id'] === $curId ? 'selected' : '' ?> data-paper="<?= e($paperKind) ?>" data-has-paper="<?= $already ? '1' : '0' ?>"><?= e($s['name']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="qa-field">
              <label class="form-label" for="opp-reason">Win / loss reason</label>
              <input class="form-control" id="opp-reason" name="win_loss_reason" value="<?= e($o['win_loss_reason'] ?? '') ?>" placeholder="Required if you close as lost">
            </div>
            <?php \App\Core\View::partial('stage_paper_field', [
                'hint' => 'Upload the matching PDF. It stays on this deal and is shared with the customer.',
            ]); ?>
          </div>
          <button class="btn btn-outline-primary mt-3" type="submit"><i class="bi bi-flag"></i> Update stage</button>
        </form>
      </div>

      <?php if ($stageFeed): ?>
      <div class="card-soft rec-card p-3 mb-3">
        <?php \App\Core\View::partial('record_section_head', [
            'icon' => 'bi-clock-history',
            'title' => 'Stage changes',
            'hint' => 'Who moved this ' . strtolower($dealWord) . ' and when.',
        ]); ?>
        <div class="rec-status-tl">
          <?php foreach ($stageFeed as $i => $h):
              $isNow = $i === 0;
          ?>
            <div class="rec-status-tl-item <?= $isNow ? 'is-current' : '' ?>">
              <span class="rec-status-tl-dot"></span>
              <div class="min-w-0">
                <div class="d-flex flex-wrap align-items-center gap-2">
                  <strong><?= e($h['subject'] ?: 'Stage update') ?></strong>
                  <?php if ($isNow): ?><span class="rec-status-tl-now">Latest</span><?php endif; ?>
                </div>
                <?php if (!empty($h['body'])): ?><div class="small"><?= e($h['body']) ?></div><?php endif; ?>
                <div class="small text-muted">
                  <?= e($h['owner_name'] ?: 'Someone') ?>
                  · <?= e(dt_fmt($h['activity_at'] ?? null, 'M j, Y g:i A')) ?>
                  · <?= e(relative_when($h['activity_at'] ?? null)) ?>
                </div>
              </div>
            </div>
          <?php endforeach; ?>
        </div>
      </div>
      <?php endif; ?>

      <?php \App\Core\View::partial('record_activity_block', [
          'relatedType' => 'opportunity',
          'relatedId' => (int) $o['id'],
          'feed' => $feed,
          'emptyHint' => 'Calls, emails, and notes for this ' . strtolower($dealWord) . ' will show up here.',
      ]); ?>
    </div>

    <div class="col-lg-4">
      <div class="card-soft rec-card p-3 mb-3">
        <?php \App\Core\View::partial('record_section_head', [
            'icon' => 'bi-file-earmark-pdf',
            'title' => 'Proposal and agreement',
            'hint' => 'PDFs added when this ' . strtolower($dealWord) . ' moves to those stages.',
        ]); ?>
        <?php if ($papers): ?>
          <div class="rec-paper-list">
            <?php foreach ($papers as $doc):
                $kind = (string) ($doc['body'] ?? '');
                if ($kind !== 'proposal' && $kind !== 'agreement') {
                    $kind = stage_paper_kind(['name' => (string) ($doc['title'] ?? '')]);
                }
                $kindLabel = stage_paper_label($kind) ?: 'PDF';
            ?>
              <div class="rec-paper-row">
                <span class="rec-paper-kind"><?= e($kindLabel) ?></span>
                <div class="min-w-0">
                  <?= document_file_chip($doc['file_name'] ?? null, (int) $doc['id']) ?>
                  <div class="small text-muted"><?= e(dt_fmt($doc['created_at'] ?? null, 'M j, Y g:i A')) ?></div>
                </div>
              </div>
            <?php endforeach; ?>
          </div>
        <?php else: ?>
          <p class="rec-section-hint mb-0">No PDF yet. Use Move stage, choose Proposal or Agreement, and attach the file.</p>
        <?php endif; ?>
      </div>
      <?php \App\Core\View::partial('record_facts', [
          'title' => 'About this ' . strtolower($dealWord),
          'hint' => 'The account, money, and next step.',
          'icon' => 'bi-briefcase',
          'facts' => [
              ['label' => 'Account', 'value' => $account, 'href' => !empty($o['account_id']) ? url('accounts/' . (int) $o['account_id']) : ''],
              ['label' => 'Amount', 'value' => (float) ($o['amount'] ?? 0) > 0 ? money_fmt($o['amount']) : ''],
              ['label' => 'Stage', 'value' => $stageName],
              ['label' => 'Win chance', 'value' => isset($o['probability']) ? ((int) $o['probability'] . '%') : ''],
              ['label' => 'Next step', 'value' => $o['next_step'] ?? ''],
              ['label' => 'Due', 'value' => $nextDue['text'] !== '' ? $nextDue['text'] : ''],
              ['label' => 'Close date', 'value' => !empty($o['close_date']) ? dt_fmt($o['close_date'], 'M j, Y') : ''],
              ['label' => 'Owner', 'value' => $owner !== '' ? $owner : 'Unassigned'],
              ['label' => 'Added', 'value' => dt_fmt($o['created_at'] ?? null, 'M j, Y g:i A')],
          ],
      ]); ?>
      <?php \App\Core\View::partial('related_task_box', [
          'relatedType' => 'opportunity',
          'relatedId' => (int) $o['id'],
          'tasks' => $tasks ?? [],
          'ownerId' => (int) ($o['owner_id'] ?? 0),
          'empty' => 'No tasks on this ' . strtolower($dealWord) . ' yet.',
          'boxId' => 'deal-tasks',
          'hint' => 'Follow-ups and to-dos for this sale.',
      ]); ?>
    </div>
  </div>
</div>
