<?php
$rows = $rows ?? [];
$accounts = $accounts ?? [];
$owners = $owners ?? [];
$type = $type ?? 'all';
$counts = $counts ?? ['quotes' => 0, 'contracts' => 0, 'files' => 0];
$q = $q ?? '';
$signature = $signature ?? 'all';
$created = $created ?? 'all';
$assigned = (int) ($assigned ?? 0);
$showAssigned = (bool) ($showAssigned ?? false);
$accountId = (int) ($accountId ?? 0);
$page = (int) ($page ?? 1);
$pages = (int) ($pages ?? 1);
$signLabels = [
    'pending' => 'Waiting',
    'signed' => 'Document Signed',
    'declined' => 'Declined',
];
$rowType = static function (array $r): string {
    $related = (string) ($r['related_type'] ?? '');
    $kind = (string) ($r['kind'] ?? '');
    if ($related === 'quote' || $kind === 'quote') {
        return 'quotes';
    }
    if ($related === 'contract' || in_array($kind, ['contract', 'esign'], true)) {
        return 'contracts';
    }
    return 'others';
};
$icos = ['quotes' => 'bi-file-earmark-richtext', 'contracts' => 'bi-file-earmark-ruled', 'others' => 'bi-file-earmark-pdf'];
$filtered = $q !== '' || $accountId > 0 || $assigned > 0 || $signature !== 'all' || $type !== 'all' || $created !== 'all';
?>
<div class="svc-page">
  <div class="d-flex flex-wrap justify-content-between align-items-start gap-3 mb-3">
    <div>
      <h1 class="page-title">Documents</h1>
      <p class="page-sub mb-0">Quotes, contracts, and files shared with the customer. PDF only, up to 8 MB.</p>
    </div>
    <?php if (can_edit('documents') && $accounts !== []): ?>
      <a class="btn btn-primary" href="#doc-create"><i class="bi bi-plus-lg"></i> Share a PDF</a>
    <?php endif; ?>
  </div>
  <div class="task-summary mb-3">
    <?php foreach ([['Quotes', $counts['quotes'] ?? 0, 'bi-file-earmark-richtext', '#2563eb', '#eff6ff'], ['Contracts', $counts['contracts'] ?? 0, 'bi-file-earmark-ruled', '#0f766e', '#f0fdfa'], ['Others', $counts['files'] ?? 0, 'bi-folder2-open', '#7c3aed', '#f5f3ff'], ['All', ($counts['quotes'] ?? 0) + ($counts['contracts'] ?? 0) + ($counts['files'] ?? 0), 'bi-collection', '#ea580c', '#fff7ed']] as $s): ?>
      <div class="task-summary-card" style="--task-accent: <?= e($s[3]) ?>; --task-tint: <?= e($s[4]) ?>">
        <div class="task-summary-icon"><i class="bi <?= e($s[2]) ?>"></i></div>
        <div><div class="task-summary-n"><?= (int) $s[1] ?></div><div class="task-summary-l"><?= e($s[0]) ?></div></div>
      </div>
    <?php endforeach; ?>
  </div>

  <form class="task-filters opp-filters card-soft p-3 mb-3" method="get">
    <div class="task-filter-search">
      <label class="form-label" for="doc-q">Search</label>
      <input class="form-control" id="doc-q" name="q" value="<?= e($q) ?>" placeholder="Search title, file name, account, or who signed" autocomplete="off">
    </div>
    <?php if ($showAssigned): ?>
    <div>
      <label class="form-label" for="doc-assigned">Shared by</label>
      <select class="form-select" id="doc-assigned" name="assigned">
        <option value="0" <?= $assigned === 0 ? 'selected' : '' ?>>All</option>
        <?php foreach ($owners as $o): ?>
          <option value="<?= (int) $o['id'] ?>" <?= $assigned === (int) $o['id'] ? 'selected' : '' ?>><?= e(trim($o['first_name'] . ' ' . $o['last_name'])) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <?php endif; ?>
    <div>
      <label class="form-label" for="doc-account"><?= e(noun('account', 'Account')) ?></label>
      <select class="form-select" id="doc-account" name="account">
        <option value="0" <?= $accountId === 0 ? 'selected' : '' ?>>All</option>
        <?php foreach ($accounts as $acc): ?>
          <option value="<?= (int) $acc['id'] ?>" <?= $accountId === (int) $acc['id'] ? 'selected' : '' ?>><?= e($acc['name']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div>
      <label class="form-label" for="doc-type">Type</label>
      <select class="form-select" id="doc-type" name="type">
        <option value="all" <?= $type === 'all' ? 'selected' : '' ?>>All</option>
        <option value="quotes" <?= $type === 'quotes' ? 'selected' : '' ?>>Quotes</option>
        <option value="contracts" <?= $type === 'contracts' ? 'selected' : '' ?>>Contracts</option>
        <option value="others" <?= $type === 'others' ? 'selected' : '' ?>>Others</option>
      </select>
    </div>
    <div>
      <label class="form-label" for="doc-created">Created</label>
      <select class="form-select" id="doc-created" name="created">
        <option value="all" <?= $created === 'all' ? 'selected' : '' ?>>All</option>
        <option value="today" <?= $created === 'today' ? 'selected' : '' ?>>Today</option>
        <option value="week" <?= $created === 'week' ? 'selected' : '' ?>>This week</option>
        <option value="month" <?= $created === 'month' ? 'selected' : '' ?>>This month</option>
      </select>
    </div>
    <div>
      <label class="form-label" for="doc-signature">Signature</label>
      <select class="form-select" id="doc-signature" name="signature">
        <option value="all" <?= $signature === 'all' ? 'selected' : '' ?>>All</option>
        <option value="pending" <?= $signature === 'pending' ? 'selected' : '' ?>>Waiting</option>
        <option value="signed" <?= $signature === 'signed' ? 'selected' : '' ?>>Document Signed</option>
        <option value="none" <?= $signature === 'none' ? 'selected' : '' ?>>No signature</option>
        <option value="declined" <?= $signature === 'declined' ? 'selected' : '' ?>>Declined</option>
      </select>
    </div>
    <div class="task-filter-go">
      <button class="btn btn-primary" type="submit"><i class="bi bi-search"></i> Search</button>
    </div>
  </form>

  <div class="row g-3">
    <div class="col-lg-7">
      <?php if (!$rows): ?>
        <div class="card-soft task-empty">
          <div class="task-empty-icon"><i class="bi <?= e($icos[$type] ?? 'bi-folder2-open') ?>"></i></div>
          <h2>No documents</h2>
          <p><?= $filtered ? 'Try another filter.' : 'Share a PDF, or send a quote or contract to the customer.' ?></p>
        </div>
      <?php else: foreach ($rows as $r):
          $related = (string) ($r['related_type'] ?? '');
          $rid = (int) ($r['related_id'] ?? 0);
          $signSt = (string) ($r['sign_status'] ?? '');
          $kind = $rowType($r);
          $st = commerce_status_label($signSt !== '' ? $signSt : 'draft', $signSt !== '' ? ($signLabels[$signSt] ?? $signSt) : 'File');
      ?>
        <div class="svc-visit svc-tone-<?= e($st['tone']) ?>">
          <div class="svc-visit-main">
            <div class="svc-visit-icon"><i class="bi <?= e($icos[$kind] ?? 'bi-file-earmark-pdf') ?>"></i></div>
            <div class="min-w-0 flex-grow-1">
              <div class="svc-visit-name"><?= e($r['title']) ?></div>
              <div class="svc-visit-sub">
                <?php if (!empty($r['account_name'])): ?>
                  <a href="<?= e(url('accounts/' . $r['account_id'])) ?>"><i class="bi bi-buildings"></i> <?= e($r['account_name']) ?></a>
                <?php endif; ?>
                <?php if ($related === 'quote' && $rid > 0): ?>
                  <a href="<?= e(url('quotes/' . $rid)) ?>"><i class="bi bi-file-earmark-richtext"></i> Quote</a>
                <?php elseif ($related === 'contract' && $rid > 0): ?>
                  <a href="<?= e(url('contracts/' . $rid)) ?>"><i class="bi bi-file-earmark-ruled"></i> Contract</a>
                <?php endif; ?>
                <?php if (!empty($r['owner_name'])): ?><span><i class="bi bi-person"></i> <?= e($r['owner_name']) ?></span><?php endif; ?>
                <?php if (!empty($r['file_name'])): ?><span><i class="bi bi-file-earmark-pdf"></i> <?= e($r['file_name']) ?></span><?php endif; ?>
                <?php if ($signSt === 'signed' && !empty($r['signer_name'])): ?>
                  <span><i class="bi bi-pen"></i> Signed by <?= e($r['signer_name']) ?></span>
                <?php endif; ?>
              </div>
            </div>
            <div class="task-meta">
              <span class="due-pill <?= e($st['class']) ?>"><?= e($st['text']) ?></span>
            </div>
          </div>
          <div class="svc-attend d-flex flex-column gap-2">
            <?php if (!empty($r['file_name'])): ?>
              <a class="btn btn-sm btn-outline-primary" href="<?= e(url('documents/' . $r['id'] . '/file')) ?>" target="_blank" rel="noopener noreferrer"><i class="bi bi-file-earmark-pdf"></i> Open PDF</a>
            <?php endif; ?>
            <?php if ($signSt === 'signed' && !empty($r['signed_file_name'])): ?>
              <a class="btn btn-sm btn-primary" href="<?= e(url('documents/' . $r['id'] . '/signed')) ?>" target="_blank" rel="noopener noreferrer"><i class="bi bi-pen"></i> Signed PDF</a>
            <?php endif; ?>
          </div>
        </div>
      <?php endforeach; endif; ?>
      <?php \App\Core\View::partial('pager', compact('page', 'pages')); ?>
    </div>
    <?php if (can_edit('documents')): ?>
    <div class="col-lg-5" id="doc-create">
      <form class="svc-req ajax-form" action="<?= e(url('documents')) ?>" method="post" enctype="multipart/form-data">
        <?= csrf_field() ?>
        <div class="svc-req-head">
          <span class="svc-req-icon"><i class="bi bi-upload"></i></span>
          <div>
            <div class="svc-req-kicker">Share a PDF</div>
            <h2>Send a file to the customer</h2>
            <p>They see it under Files on the Customer Portal.</p>
          </div>
        </div>
        <div class="svc-req-body">
          <label class="form-label"><?= e(noun('account', 'Account')) ?> *</label>
          <select class="form-select mb-2" name="account_id" required>
            <option value="">Select</option>
            <?php foreach ($accounts as $acc): ?>
              <option value="<?= (int) $acc['id'] ?>"><?= e($acc['name']) ?></option>
            <?php endforeach; ?>
          </select>
          <label class="form-label">Title *</label>
          <input class="form-control mb-2" name="title" required maxlength="180" placeholder="Price list, proposal, contract PDF">
          <label class="form-label">Note (optional)</label>
          <textarea class="form-control mb-2" name="body" rows="2" maxlength="2000"></textarea>
          <label class="form-label">PDF *</label>
          <input class="form-control mb-3" type="file" name="pdf" accept="application/pdf,.pdf" required>
          <div class="svc-req-foot">
            <div class="svc-wait-chips"><span class="lst-chip">Visible to customer</span></div>
            <button class="btn btn-primary" type="submit"><i class="bi bi-check2"></i> Share PDF</button>
          </div>
        </div>
      </form>
    </div>
    <?php endif; ?>
  </div>
</div>
