<?php
$a = $account;
$st = (string) ($a['status'] ?? 'active');
$owner = trim((string) ($a['owner_name'] ?? ''));
$territory = trim((string) ($a['territory_name'] ?? ''));
$industryName = trim((string) ($a['industry'] ?? ''));
$next = trim((string) ($a['next_action'] ?? ''));
$due = due_label($a['next_action_at'] ?? null, $st === 'inactive' ? 'cancelled' : 'open');
$tone = $st === 'inactive' ? 'inactive' : match ($due['class'] ?? '') {
    'due-overdue' => 'due',
    'due-today' => 'today',
    default => 'active',
};
$web = trim((string) ($a['website'] ?? ''));
$webHref = $web;
if ($web !== '' && !preg_match('#^https?://#i', $web)) {
    $webHref = 'https://' . $web;
}
$addressBits = array_filter([
    trim((string) ($a['address_line'] ?? '')),
    trim(implode(', ', array_filter([trim((string) ($a['city'] ?? '')), trim((string) ($a['state'] ?? ''))]))),
    trim((string) ($a['postal_code'] ?? '')),
], static fn ($v) => $v !== '');
$address = implode(' · ', $addressBits);
$contacts = $contacts ?? [];
$opportunities = $opportunities ?? [];
$tasks = $tasks ?? [];
$timeline = $timeline ?? [];
$campaign_mail = $campaign_mail ?? [];
$fromLead = $fromLead ?? null;
$attrs = $attrs ?? [];
$industry = $industry ?? [];
$openDeals = [];
$wonDeals = [];
$lostDeals = [];
$pipeline = 0.0;
foreach ($opportunities as $o) {
    $won = (int) ($o['is_won'] ?? 0) === 1;
    $lost = (int) ($o['is_lost'] ?? 0) === 1;
    if ($lost) {
        $lostDeals[] = $o;
    } elseif ($won) {
        $wonDeals[] = $o;
    } else {
        $openDeals[] = $o;
        $pipeline += (float) ($o['amount'] ?? 0);
    }
}
$openTasks = 0;
foreach ($tasks as $tk) {
    if (($tk['status'] ?? '') === 'open') {
        $openTasks++;
    }
}
$feed = [];
foreach ($timeline as $t) {
    $body = (string) ($t['body'] ?? '');
    if (str_contains($body, 'Logged from demo seed')) {
        continue;
    }
    $feed[] = $t;
}
$mailStatus = [
    'queued' => 'Queued',
    'sent' => 'Sent',
    'delivered' => 'Delivered',
    'opened' => 'Opened',
    'clicked' => 'Clicked',
    'bounced' => 'Bounced',
    'unsubscribed' => 'Unsubscribed',
];
$fromName = $fromLead ? trim(($fromLead['first_name'] ?? '') . ' ' . ($fromLead['last_name'] ?? '')) : '';
$acctLabel = account_label();
?>
<div class="account-page account-show">
  <a class="account-back" href="<?= e(url('accounts')) ?>"><i class="bi bi-arrow-left"></i> All <?= e(strtolower($acctLabel)) ?></a>

  <div class="account-hero account-tone-<?= e($tone) ?>">
    <div class="account-hero-main">
      <div class="account-hero-avatar"><?= e(name_initials($a['name'] ?? 'Account')) ?></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($a['name']) ?></h1>
          <span class="lead-status account-status-<?= e($st) ?>"><?= e($st === 'active' ? 'Active' : 'Inactive') ?></span>
          <?php if (!empty($due['text']) && $st === 'active'): ?>
            <span class="due-pill <?= e($due['class']) ?>"><?= e($due['text']) ?></span>
          <?php endif; ?>
        </div>
        <div class="account-hero-sub">
          <?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 else: ?>
            <span class="text-muted">Unassigned</span>
          <?php endif; ?>
          <?php if ($territory !== ''): ?><span><i class="bi bi-geo-alt"></i> <?= e($territory) ?></span><?php endif; ?>
          <?php if ($industryName !== ''): ?><span><i class="bi bi-briefcase"></i> <?= e($industryName) ?></span><?php endif; ?>
          <?php if ($fromName !== '' && !empty($fromLead['id'])): ?>
            <span>Converted from <a href="<?= e(url('leads/'.$fromLead['id'])) ?>"><?= e($fromName) ?></a></span>
          <?php endif; ?>
        </div>
        <div class="account-hero-contact">
          <?php if (!empty($a['email'])): ?>
            <a href="mailto:<?= e($a['email']) ?>"><i class="bi bi-envelope"></i> <?= e($a['email']) ?></a>
          <?php endif; ?>
          <?php if (!empty($a['phone'])): ?>
            <a href="tel:<?= e($a['phone']) ?>"><i class="bi bi-telephone"></i> <?= e($a['phone']) ?></a>
          <?php endif; ?>
          <?php if ($web !== ''): ?>
            <a href="<?= e($webHref) ?>" target="_blank" rel="noopener"><i class="bi bi-globe"></i> <?= e(preg_replace('#^https?://#i', '', $web)) ?></a>
          <?php endif; ?>
          <?php if ($next !== ''): ?><span><i class="bi bi-flag"></i> <?= e($next) ?></span><?php endif; ?>
        </div>
      </div>
    </div>
    <div class="account-hero-actions">
      <?php if (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; ?>
      <button class="btn btn-primary" type="button" data-bs-toggle="collapse" data-bs-target="#editAccount"><i class="bi bi-pencil"></i> Edit</button>
    </div>
  </div>

  <div class="collapse mb-3" id="editAccount">
    <form class="card-soft p-3 ajax-form" action="<?= e(url('accounts/'.$a['id'])) ?>" method="post">
      <?= csrf_field() ?>
      <div class="row g-2">
        <div class="col-md-4"><label class="form-label">Name</label><input class="form-control" name="name" value="<?= e($a['name']) ?>" required></div>
        <div class="col-md-4"><label class="form-label">Phone</label><input class="form-control" name="phone" value="<?= e($a['phone']) ?>"></div>
        <div class="col-md-4"><label class="form-label">Email</label><input class="form-control" name="email" value="<?= e($a['email']) ?>"></div>
        <div class="col-md-4"><label class="form-label">Next action</label><input class="form-control" name="next_action" value="<?= e($a['next_action']) ?>"></div>
        <div class="col-md-4"><label class="form-label">Due</label><input class="form-control" type="datetime-local" name="next_action_at" value="<?= $a['next_action_at'] ? date('Y-m-d\TH:i', strtotime($a['next_action_at'])) : '' ?>"></div>
        <div class="col-md-4"><label class="form-label">Status</label>
          <select class="form-select" name="status"><option <?= $a['status']==='active'?'selected':'' ?>>active</option><option <?= $a['status']==='inactive'?'selected':'' ?>>inactive</option></select>
        </div>
      </div>
      <?php \App\Core\View::partial('industry_fields', ['fields' => entity_fields('account'), 'values' => $attrs ?? []]); ?>
      <?php if (!empty($industry) && ($industry['code'] ?? '') === 'service'): ?>
      <div class="row g-2 mt-2">
        <?php if (show_field('visit', 'service_assignee_id')): ?>
        <div class="col-md-4"><label class="form-label">Assigned technician / consultant</label>
          <select class="form-select" name="service_assignee_id">
            <option value="">—</option>
            <?php foreach ($servicePeople as $sp): ?>
              <option value="<?= (int)$sp['id'] ?>" <?= (int)($a['service_assignee_id'] ?? 0) === (int)$sp['id'] ? 'selected' : '' ?>><?= e($sp['first_name'].' '.$sp['last_name']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <?php endif; ?>
      </div>
      <?php endif; ?>
      <button class="btn btn-primary mt-3" type="submit">Save</button>
    </form>
  </div>

  <div class="task-summary mb-3">
    <a class="task-summary-card" href="#account-people" style="--task-accent:#2563eb;--task-tint:#eff6ff">
      <div class="task-summary-icon"><i class="bi bi-people-fill"></i></div>
      <div><div class="task-summary-n"><?= count($contacts) ?></div><div class="task-summary-l">People</div></div>
    </a>
    <a class="task-summary-card" href="#account-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="#account-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="#account-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) $openTasks ?></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" id="account-activity">
        <h2 class="account-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="account">
            <input type="hidden" name="related_id" value="<?= (int)$a['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="visit">Visit</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 account-empty">
            <div class="task-empty-icon"><i class="bi bi-chat-dots"></i></div>
            <h2>No activity yet</h2>
            <p>Calls, visits, and notes for this account will show up here.</p>
          </div>
        <?php else: ?>
          <div class="account-activity">
            <?php foreach ($feed as $t):
              $style = activity_style($t['type'] ?? '');
            ?>
              <div class="account-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; ?>
          </div>
        <?php endif; ?>
      </div>

      <div class="card-soft p-3 mb-3" id="account-deals">
        <h2 class="account-section-title"><?= e(opportunity_label()) ?></h2>
        <?php if (!$opportunities): ?>
          <div class="task-empty account-empty">
            <div class="task-empty-icon"><i class="bi bi-briefcase"></i></div>
            <h2>No <?= e(strtolower(opportunity_label())) ?> yet</h2>
            <p>Use <strong>Add New → <?= e(noun('opportunity', 'Deal')) ?></strong> to add one for this <?= e(strtolower(noun('account', 'account'))) ?>.</p>
          </div>
        <?php else: ?>
          <?php foreach (array_merge($openDeals, $wonDeals, $lostDeals) 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="account-rel-card opp-tone-<?= e($otone) ?>" href="<?= e(url('opportunities/'.$o['id'])) ?>">
              <div class="account-rel-avatar"><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>

      <div class="card-soft p-3" id="account-people">
        <h2 class="account-section-title">People</h2>
        <?php if (!$contacts): ?>
          <div class="task-empty account-empty">
            <div class="task-empty-icon"><i class="bi bi-person"></i></div>
            <h2>No contacts yet</h2>
            <p>Add a person from <strong>Add New → Contact</strong>.</p>
          </div>
        <?php else: ?>
          <?php foreach ($contacts as $c):
            $cname = trim($c['first_name'].' '.$c['last_name']);
            $role = trim((string) ($c['title'] ?: $c['role_label'] ?: ''));
          ?>
            <a class="account-rel-card <?= !empty($c['is_primary']) ? 'is-primary' : '' ?>" href="<?= e(url('contacts/'.$c['id'])) ?>">
              <div class="account-rel-avatar contact-avatar"><?= e(name_initials($cname)) ?></div>
              <div class="min-w-0 flex-grow-1">
                <div class="lead-name">
                  <?= e($cname) ?>
                  <?php if (!empty($c['is_primary'])): ?><span class="contact-primary">Primary</span><?php endif; ?>
                </div>
                <div class="lead-sub">
                  <?php if ($role !== ''): ?><span><?= e($role) ?></span><?php endif; ?>
                  <?php if (!empty($c['email'])): ?><span><?= e($c['email']) ?></span><?php endif; ?>
                  <?php if (!empty($c['phone'])): ?><span><?= e($c['phone']) ?></span><?php endif; ?>
                </div>
              </div>
            </a>
          <?php endforeach; ?>
        <?php endif; ?>
      </div>
    </div>

    <div class="col-lg-4">
      <div class="card-soft p-3 mb-3">
        <h2 class="account-section-title">About</h2>
        <dl class="account-facts">
          <div><dt>Phone</dt><dd><?php if (!empty($a['phone'])): ?><a href="tel:<?= e($a['phone']) ?>"><?= e($a['phone']) ?></a><?php else: ?>—<?php endif; ?></dd></div>
          <div><dt>Email</dt><dd><?php if (!empty($a['email'])): ?><a href="mailto:<?= e($a['email']) ?>"><?= e($a['email']) ?></a><?php else: ?>—<?php endif; ?></dd></div>
          <div><dt>Website</dt><dd><?php if ($web !== ''): ?><a href="<?= e($webHref) ?>" target="_blank" rel="noopener"><?= e(preg_replace('#^https?://#i', '', $web)) ?></a><?php else: ?>—<?php endif; ?></dd></div>
          <div><dt>Territory</dt><dd><?= e($territory !== '' ? $territory : '—') ?></dd></div>
          <div><dt>Industry</dt><dd><?= e($industryName !== '' ? $industryName : '—') ?></dd></div>
          <div><dt>Address</dt><dd><?= e($address !== '' ? $address : '—') ?></dd></div>
          <div><dt>Owner</dt><dd><?= e($owner !== '' ? $owner : 'Unassigned') ?></dd></div>
        </dl>
      </div>

      <div class="card-soft p-3 mb-3 account-next <?= e($due['class'] ?: 'due-none') ?>">
        <h2 class="account-section-title">Next action</h2>
        <?php if ($next === '' && empty($a['next_action_at'])): ?>
          <p class="text-muted mb-0">Nothing scheduled. Use Edit to set a next step.</p>
        <?php else: ?>
          <div class="fw-bold mb-1"><?= e($next !== '' ? $next : 'Follow up') ?></div>
          <?php if (!empty($due['text'])): ?>
            <span class="due-pill <?= e($due['class']) ?>"><?= e($due['text']) ?></span>
            <span class="small text-muted ms-1"><?= e(dt_fmt($a['next_action_at'], 'M j, Y g:i A')) ?></span>
          <?php endif; ?>
        <?php endif; ?>
      </div>

      <div class="card-soft p-3 mb-3">
        <h2 class="account-section-title"><?= e($industry['name'] ?? 'Industry') ?> fields</h2>
        <?php if (empty($industry['account_fields'])): ?>
          <p class="text-muted mb-0">No extra boxes for this setup.</p>
        <?php else: foreach ($industry['account_fields'] as $f):
          $raw = (string) ($attrs[$f['key']] ?? '');
          $shown = $raw;
          if ($raw === '') {
              $shown = '—';
          } elseif (($f['type'] ?? '') === 'select') {
              $shown = (string) (($f['options'][$raw] ?? $raw));
          } elseif (($f['type'] ?? '') === 'date') {
              $shown = dt_fmt($raw);
          } elseif (($f['type'] ?? '') === 'money') {
              $shown = money_fmt($raw);
          }
        ?>
          <div class="account-fact-line"><span><?= e($f['label']) ?></span><strong><?= e($shown) ?></strong></div>
        <?php endforeach; endif; ?>
        <?php if (($industry['code'] ?? '') === 'service'): ?>
          <div class="account-fact-line"><span>Last visit</span><strong><?= e(dt_fmt($a['last_visit_at'], 'M j, Y g:i A')) ?></strong></div>
        <?php endif; ?>
      </div>

      <?php \App\Core\View::partial('related_task_box', [
          'relatedType' => 'account',
          'relatedId' => (int) $a['id'],
          'tasks' => $tasks ?? [],
          'ownerId' => (int) ($a['owner_id'] ?? 0),
          'empty' => 'No tasks on this account yet.',
          'boxId' => 'account-tasks',
      ]); ?>

      <div class="card-soft p-3 mb-3" id="account-mail">
        <h2 class="account-section-title">Marketing email</h2>
        <?php if (!$campaign_mail): ?>
          <p class="text-muted mb-0">No marketing emails yet.</p>
        <?php else: foreach ($campaign_mail as $m):
          $ms = (string) ($m['status'] ?? '');
        ?>
          <div class="account-mail-row">
            <strong><?= e($m['campaign_name'] ?? $m['subject']) ?></strong>
            <div class="small text-muted">
              <?= e($m['email'] ?? '') ?> · <?= 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>

      <?php
      $commerceBits = [];
      if (can_see('quotes') && !empty($quotes)) {
          $commerceBits[] = [count($quotes) . ' quotes', url('quotes')];
      }
      if (can_see('orders') && !empty($orders)) {
          $commerceBits[] = [count($orders) . ' orders', url('orders')];
      }
      if (can_see('contracts') && !empty($contracts)) {
          $commerceBits[] = [count($contracts) . ' contracts', url('contracts')];
      }
      if (can_see('invoices') && !empty($invoices)) {
          $commerceBits[] = [count($invoices) . ' invoices', url('invoices')];
      }
      if (can_see('service_jobs') && !empty($jobs)) {
          $commerceBits[] = [count($jobs) . ' jobs', url('jobs')];
      }
      if (can_see('equipment') && !empty($equipment)) {
          $commerceBits[] = [count($equipment) . ' machines', url('equipment')];
      }
      if ($commerceBits): ?>
      <div class="card-soft p-3 mb-3">
        <h2 class="account-section-title">Orders and service</h2>
        <div class="d-flex flex-wrap gap-2">
          <?php foreach ($commerceBits as $bit): ?>
            <a class="lst-chip" href="<?= e($bit[1]) ?>"><?= e($bit[0]) ?></a>
          <?php endforeach; ?>
        </div>
      </div>
      <?php endif; ?>

      <?php if (can_see('service_visits') && ($industry['code'] ?? '') === 'service'): ?>
      <form class="card-soft p-3 ajax-form" action="<?= e(url('service/notes')) ?>" method="post">
        <?= csrf_field() ?>
        <input type="hidden" name="account_id" value="<?= (int)$a['id'] ?>">
        <h2 class="account-section-title">Notes after a visit</h2>
        <textarea class="form-control mb-2" name="body" rows="3" required placeholder="What was done on site"></textarea>
        <button class="btn btn-primary" type="submit">Save visit notes</button>
      </form>
      <?php endif; ?>
    </div>
  </div>
</div>
