<?php
$c = $contact;
$name = trim($c['first_name'] . ' ' . $c['last_name']);
$owner = trim((string) ($c['owner_name'] ?? ''));
$role = trim((string) ($c['title'] ?: $c['role_label'] ?: ''));
$primary = (int) ($c['is_primary'] ?? 0) === 1;
$bounced = ($c['email_status'] ?? 'ok') === 'bounced';
$hasEmail = trim((string) ($c['email'] ?? '')) !== '';
$tone = $bounced ? 'bounced' : ($primary ? 'primary' : 'ok');
$emailLabel = $bounced ? 'Bounced' : ($hasEmail ? 'Email OK' : 'No email');
$emailClass = $bounced ? 'bounced' : ($hasEmail ? 'ok' : 'none');
$timeline = $timeline ?? [];
$colleagues = $colleagues ?? [];
$opportunities = $opportunities ?? [];
$tasks = $tasks ?? [];
$accountTasks = $accountTasks ?? [];
$campaign_mail = $campaign_mail ?? [];
$feed = [];
foreach ($timeline as $t) {
    $body = (string) ($t['body'] ?? '');
    if (str_contains($body, 'Logged from demo seed')) {
        continue;
    }
    $feed[] = $t;
}
$openDeals = [];
$pipeline = 0.0;
foreach ($opportunities as $o) {
    if ((int) ($o['is_won'] ?? 0) === 1 || (int) ($o['is_lost'] ?? 0) === 1) {
        continue;
    }
    $openDeals[] = $o;
    $pipeline += (float) ($o['amount'] ?? 0);
}
$allTasks = [];
foreach ($tasks as $tk) {
    $tk['_scope'] = 'contact';
    $allTasks[] = $tk;
}
foreach ($accountTasks as $tk) {
    $tk['_scope'] = 'account';
    $allTasks[] = $tk;
}
$openTaskN = 0;
foreach ($allTasks as $tk) {
    if (($tk['status'] ?? '') === 'open') {
        $openTaskN++;
    }
}
$mailStatus = [
    'queued' => 'Queued',
    'sent' => 'Sent',
    'delivered' => 'Delivered',
    'opened' => 'Opened',
    'clicked' => 'Clicked',
    'bounced' => 'Bounced',
    'unsubscribed' => 'Unsubscribed',
];
$acctDue = due_label($c['account_next_action_at'] ?? null, ($c['account_status'] ?? '') === 'inactive' ? 'cancelled' : 'open');
$acctCity = trim(implode(', ', array_filter([trim((string) ($c['account_city'] ?? '')), trim((string) ($c['account_state'] ?? ''))])));
?>
<div class="contact-page contact-show">
  <a class="contact-back" href="<?= e(url('contacts')) ?>"><i class="bi bi-arrow-left"></i> All contacts</a>

  <div class="contact-hero contact-tone-<?= e($tone) ?>">
    <div class="contact-hero-main">
      <div class="contact-hero-avatar"><?= e(name_initials($name !== '' ? $name : 'Contact')) ?></div>
      <div class="min-w-0">
        <div class="d-flex flex-wrap align-items-center gap-2 mb-1">
          <h1 class="page-title mb-0"><?= e($name !== '' ? $name : 'Untitled') ?></h1>
          <?php if ($primary): ?><span class="contact-primary">Primary</span><?php endif; ?>
          <span class="lead-status contact-status-<?= e($emailClass) ?>"><?= e($emailLabel) ?></span>
        </div>
        <div class="contact-hero-sub">
          <?php if ($role !== ''): ?><span><i class="bi bi-person-badge"></i> <?= e($role) ?></span><?php endif; ?>
          <?php if (!empty($c['account_id'])): ?>
            <span><i class="bi bi-buildings"></i> <a href="<?= e(url('accounts/'.$c['account_id'])) ?>"><?= e($c['account_name'] ?: 'Account') ?></a></span>
          <?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; ?>
        </div>
        <div class="contact-hero-contact">
          <?php if ($hasEmail): ?>
            <a href="mailto:<?= e($c['email']) ?>"><i class="bi bi-envelope"></i> <?= e($c['email']) ?></a>
          <?php endif; ?>
          <?php if (!empty($c['phone'])): ?>
            <a href="tel:<?= e($c['phone']) ?>"><i class="bi bi-telephone"></i> <?= e($c['phone']) ?></a>
          <?php endif; ?>
          <?php if (!empty($c['role_label']) && $c['role_label'] !== $c['title']): ?>
            <span><i class="bi bi-diagram-3"></i> <?= e($c['role_label']) ?></span>
          <?php endif; ?>
        </div>
      </div>
    </div>
    <div class="contact-hero-actions">
      <?php if (can_see('emails') && $hasEmail): ?>
        <a class="btn btn-outline-primary" href="mailto:<?= e($c['email']) ?>"><i class="bi bi-envelope"></i> Email</a>
      <?php elseif (can_see('emails')): ?>
        <button class="btn btn-outline-primary" type="button" data-bs-toggle="modal" data-bs-target="#quickAddModal"><i class="bi bi-envelope"></i> Email</button>
      <?php endif; ?>
      <?php if (!empty($c['account_id'])): ?>
        <a class="btn btn-primary" href="<?= e(url('accounts/'.$c['account_id'])) ?>"><i class="bi bi-buildings"></i> Open account</a>
      <?php endif; ?>
    </div>
  </div>

  <div class="task-summary mb-3">
    <div class="task-summary-card" style="--task-accent:#16a34a;--task-tint:#f0fdf4">
      <div class="task-summary-icon"><i class="bi bi-envelope-fill"></i></div>
      <div><div class="task-summary-n"><?= e($emailLabel) ?></div><div class="task-summary-l">Inbox status</div></div>
    </div>
    <a class="task-summary-card" href="#contact-deals" style="--task-accent:#0f766e;--task-tint:#f0fdfa">
      <div class="task-summary-icon"><i class="bi bi-briefcase-fill"></i></div>
      <div><div class="task-summary-n"><?= count($openDeals) ?></div><div class="task-summary-l">Open <?= e(strtolower(opportunity_label())) ?></div></div>
    </a>
    <a class="task-summary-card" href="#contact-deals" style="--task-accent:#1a56c8;--task-tint:#eff6ff">
      <div class="task-summary-icon"><i class="bi bi-currency-dollar"></i></div>
      <div><div class="task-summary-n"><?= e(money_compact($pipeline)) ?></div><div class="task-summary-l">Pipeline</div></div>
    </a>
    <a class="task-summary-card" href="#contact-tasks" style="--task-accent:#ea580c;--task-tint:#fff7ed">
      <div class="task-summary-icon"><i class="bi bi-check2-square"></i></div>
      <div><div class="task-summary-n"><?= (int) $openTaskN ?></div><div class="task-summary-l">Open tasks</div></div>
    </a>
  </div>

  <div class="row g-3">
    <div class="col-lg-8">
      <div class="card-soft p-3 mb-3">
        <h2 class="contact-section-title">Activity</h2>
        <?php if (can_see('tasks')): ?>
          <form class="ajax-form mb-3" action="<?= e(url('activities')) ?>" method="post" enctype="multipart/form-data">
            <?= csrf_field() ?>
            <input type="hidden" name="related_type" value="contact">
            <input type="hidden" name="related_id" value="<?= (int) $c['id'] ?>">
            <div class="row g-2">
              <div class="col-md-3">
                <select class="form-select" name="type">
                  <option value="note">Note</option>
                  <option value="call">Call</option>
                  <option value="email">Email</option>
                  <option value="meeting">Meeting</option>
                </select>
              </div>
              <div class="col-md-6"><input class="form-control" name="subject" placeholder="What happened?" required></div>
              <div class="col-md-3"><button class="btn btn-outline-primary w-100" type="submit">Add</button></div>
              <div class="col-12"><textarea class="form-control" name="body" rows="2" placeholder="Details (optional)"></textarea></div>
              <div class="col-12">
                <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">
                <div class="form-text">Optional file: PDF, Word, JPEG, or PNG. Up to 8 MB.</div>
              </div>
            </div>
          </form>
        <?php endif; ?>
        <?php if (!$feed): ?>
          <div class="task-empty contact-empty">
            <div class="task-empty-icon"><i class="bi bi-chat-dots"></i></div>
            <h2>No activity yet</h2>
            <p>Calls, emails, and notes with <?= e($name !== '' ? $name : 'this person') ?> will show up here.</p>
          </div>
        <?php else: ?>
          <?php foreach ($feed as $t):
            $style = activity_style($t['type'] ?? '');
          ?>
            <div class="contact-activity-row">
              <span class="comm-icon" style="background:<?= e($style[1]) ?>22;color:<?= e($style[1]) ?>"><i class="bi <?= e($style[0]) ?>"></i></span>
              <div class="min-w-0 flex-grow-1">
                <div class="fw-semibold"><?= e($t['subject']) ?></div>
                <?php if (!empty($t['body'])): ?><div class="small"><?= nl2br(e($t['body'])) ?></div><?php endif; ?>
                <?= activity_file_chip($t['file_name'] ?? null, (int) $t['id']) ?>
                <div class="small text-muted"><?= e($t['owner_name'] ?: 'Someone') ?> · <?= e(dt_fmt($t['activity_at'], 'M j, Y g:i A')) ?></div>
              </div>
              <span class="small text-muted text-nowrap"><?= e(relative_when($t['activity_at'] ?? null)) ?></span>
            </div>
          <?php endforeach; ?>
        <?php endif; ?>
      </div>

      <div class="card-soft p-3 mb-3" id="contact-deals">
        <h2 class="contact-section-title">Account deals</h2>
        <?php if (!$opportunities): ?>
          <div class="task-empty contact-empty">
            <div class="task-empty-icon"><i class="bi bi-briefcase"></i></div>
            <h2>No deals yet</h2>
            <p><?= e(opportunity_label()) ?> on <?= e($c['account_name'] ?: 'this ' . strtolower(noun('account', 'account'))) ?> will show here.</p>
          </div>
        <?php else: ?>
          <?php foreach ($opportunities as $o):
            $won = (int) ($o['is_won'] ?? 0) === 1;
            $lost = (int) ($o['is_lost'] ?? 0) === 1;
            $odue = due_label($o['next_step_at'] ?? null, $won ? 'completed' : ($lost ? 'cancelled' : 'open'));
            $otone = $lost ? 'lost' : ($won ? 'won' : match ($odue['class'] ?? '') {
                'due-overdue' => 'due',
                'due-today' => 'today',
                default => 'open',
            });
          ?>
            <a class="contact-rel-card opp-tone-<?= e($otone) ?>" href="<?= e(url('opportunities/'.$o['id'])) ?>">
              <div class="contact-rel-icon"><i class="bi bi-briefcase"></i></div>
              <div class="min-w-0 flex-grow-1">
                <div class="lead-name"><?= e($o['name']) ?></div>
                <div class="lead-sub">
                  <span><?= e($o['stage_name']) ?></span>
                  <?php if (!empty($o['next_step'])): ?><span><?= e($o['next_step']) ?></span><?php endif; ?>
                </div>
              </div>
              <div class="task-meta">
                <span class="opp-amt"><?= money_fmt($o['amount']) ?></span>
                <span class="lead-status opp-stage-<?= e($otone) ?>"><?= e($o['stage_name']) ?></span>
                <?php if (!empty($odue['text'])): ?>
                  <span class="due-pill <?= e($odue['class']) ?>"><?= e($odue['text']) ?></span>
                <?php endif; ?>
              </div>
            </a>
          <?php endforeach; ?>
        <?php endif; ?>
      </div>

      <?php if ($colleagues): ?>
      <div class="card-soft p-3">
        <h2 class="contact-section-title">Also at <?= e($c['account_name'] ?: 'this account') ?></h2>
        <?php foreach ($colleagues as $p):
          $pname = trim($p['first_name'].' '.$p['last_name']);
          $prole = trim((string) ($p['title'] ?: $p['role_label'] ?: ''));
        ?>
          <a class="contact-rel-card <?= !empty($p['is_primary']) ? 'is-primary' : '' ?>" href="<?= e(url('contacts/'.$p['id'])) ?>">
            <div class="contact-rel-icon contact-avatar"><?= e(name_initials($pname)) ?></div>
            <div class="min-w-0">
              <div class="lead-name"><?= e($pname) ?><?php if (!empty($p['is_primary'])): ?> <span class="contact-primary">Primary</span><?php endif; ?></div>
              <div class="lead-sub">
                <?php if ($prole !== ''): ?><span><?= e($prole) ?></span><?php endif; ?>
                <?php if (!empty($p['email'])): ?><span><?= e($p['email']) ?></span><?php endif; ?>
              </div>
            </div>
          </a>
        <?php endforeach; ?>
      </div>
      <?php endif; ?>
    </div>

    <div class="col-lg-4">
      <div class="card-soft p-3 mb-3">
        <h2 class="contact-section-title">About</h2>
        <dl class="contact-facts">
          <div><dt>Title</dt><dd><?= e(trim((string) ($c['title'] ?? '')) !== '' ? $c['title'] : '—') ?></dd></div>
          <div><dt>Role</dt><dd><?= e(trim((string) ($c['role_label'] ?? '')) !== '' ? $c['role_label'] : '—') ?></dd></div>
          <div><dt>Email</dt><dd><?php if ($hasEmail): ?><a href="mailto:<?= e($c['email']) ?>"><?= e($c['email']) ?></a><?php else: ?>—<?php endif; ?></dd></div>
          <div><dt>Phone</dt><dd><?php if (!empty($c['phone'])): ?><a href="tel:<?= e($c['phone']) ?>"><?= e($c['phone']) ?></a><?php else: ?>—<?php endif; ?></dd></div>
          <div><dt>Owner</dt><dd><?= e($owner !== '' ? $owner : 'Unassigned') ?></dd></div>
          <div><dt>Added</dt><dd><?= e(dt_fmt($c['created_at'] ?? null, 'M j, Y')) ?></dd></div>
        </dl>
      </div>

      <?php if (!empty($c['account_id'])): ?>
      <a class="card-soft p-3 mb-3 contact-account-card text-decoration-none" href="<?= e(url('accounts/'.$c['account_id'])) ?>">
        <h2 class="contact-section-title">Account</h2>
        <div class="d-flex gap-2 align-items-center mb-2">
          <div class="account-avatar"><?= e(name_initials($c['account_name'] ?? '')) ?></div>
          <div>
            <div class="lead-name"><?= e($c['account_name']) ?></div>
            <div class="small text-muted">
              <?= e(($c['account_status'] ?? '') === 'inactive' ? 'Inactive' : 'Active') ?>
              <?php if ($acctCity !== ''): ?> · <?= e($acctCity) ?><?php endif; ?>
            </div>
          </div>
        </div>
        <?php if (!empty($c['account_next_action'])): ?>
          <div class="small">
            <span class="text-muted">Next:</span> <?= e($c['account_next_action']) ?>
            <?php if (!empty($acctDue['text'])): ?>
              <span class="due-pill <?= e($acctDue['class']) ?>"><?= e($acctDue['text']) ?></span>
            <?php endif; ?>
          </div>
        <?php endif; ?>
      </a>
      <?php endif; ?>

      <div class="card-soft p-3 mb-3" id="contact-tasks">
        <h2 class="contact-section-title">Tasks</h2>
        <?php if (!$allTasks): ?>
          <p class="text-muted mb-0">No tasks for this person or account.</p>
        <?php else: foreach ($allTasks as $tk):
          $tdue = due_label($tk['due_at'] ?? null, $tk['status'] ?? 'open');
        ?>
          <div class="contact-task-row">
            <div class="min-w-0">
              <div class="fw-semibold"><?= e($tk['title']) ?></div>
              <div class="small text-muted"><?= ($tk['_scope'] ?? '') === 'account' ? 'On account' : 'On contact' ?><?php if (!empty($tk['owner_name'])): ?> · <?= e($tk['owner_name']) ?><?php endif; ?></div>
            </div>
            <?php if (!empty($tdue['text'])): ?>
              <span class="due-pill <?= e($tdue['class']) ?>"><?= e($tdue['text']) ?></span>
            <?php endif; ?>
          </div>
        <?php endforeach; endif; ?>
      </div>

      <div class="card-soft p-3">
        <h2 class="contact-section-title">Marketing email</h2>
        <?php if (!$campaign_mail): ?>
          <p class="text-muted mb-0">No marketing emails to this person yet.</p>
        <?php else: foreach ($campaign_mail as $m):
          $ms = (string) ($m['status'] ?? '');
        ?>
          <div class="contact-mail-row">
            <strong><?= e($m['campaign_name'] ?? $m['subject']) ?></strong>
            <div class="small text-muted">
              <?= e($mailStatus[$ms] ?? $ms) ?>
              <?php if (!empty($m['opened_at'])): ?> · opened <?= e(dt_fmt($m['opened_at'], 'M j, g:i A')) ?><?php endif; ?>
              <?php if (!empty($m['clicked_at'])): ?> · clicked<?php endif; ?>
            </div>
          </div>
        <?php endforeach; endif; ?>
      </div>
    </div>
  </div>
</div>
