<?php
$rows = $rows ?? [];
$counts = $counts ?? [];
$q = $q ?? '';
$status = $status ?? 'active';
$assigned = (int) ($assigned ?? 0);
$showAssigned = (bool) ($showAssigned ?? false);
$accountId = (int) ($accountId ?? 0);
$renewal = $renewal ?? 'all';
$signature = $signature ?? 'all';
$accounts = $accounts ?? [];
$owners = $owners ?? [];
$page = (int) ($page ?? 1);
$pages = (int) ($pages ?? 1);
$draft = $draft ?? [];
$renewFrom = $renewFrom ?? null;
$draftAccount = (int) ($draft['account_id'] ?? 0);
$statusLabels = [
    'draft' => 'Draft',
    'active' => 'Active',
    'expired' => 'Expired',
    'cancelled' => 'Cancelled',
];
$signLabels = [
    'pending' => 'Waiting',
    'signed' => 'Document Signed',
    'declined' => 'Declined',
];
?>
<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">Contracts</h1>
      <p class="page-sub mb-0">Dates, awards, and renewal reminders on the customer. Open a row to see the PDF and ask for a signature.</p>
    </div>
    <?php if (can_edit('contracts') && $accounts !== []): ?>
      <a class="btn btn-primary" href="#contract-form"><i class="bi bi-plus-lg"></i> New contract</a>
    <?php endif; ?>
  </div>
  <div class="task-summary mb-3">
    <?php foreach ([['Active', $counts['active'] ?? 0, 'bi-check-circle-fill', '#16a34a', '#f0fdf4'], ['Due to renew', $counts['renewing'] ?? 0, 'bi-hourglass-split', '#ea580c', '#fff7ed'], ['Expired', $counts['expired'] ?? 0, 'bi-x-circle-fill', '#dc2626', '#fef2f2'], ['Draft', $counts['draft'] ?? 0, 'bi-pencil-fill', '#2563eb', '#eff6ff']] 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="ctr-q">Search</label>
      <input class="form-control" id="ctr-q" name="q" value="<?= e($q) ?>" placeholder="Search title, contract number, or account" autocomplete="off">
    </div>
    <?php if ($showAssigned): ?>
    <div>
      <label class="form-label" for="ctr-assigned">Assigned to</label>
      <select class="form-select" id="ctr-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="ctr-account"><?= e(noun('account', 'Account')) ?></label>
      <select class="form-select" id="ctr-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="ctr-status">Status</label>
      <select class="form-select" id="ctr-status" name="status">
        <option value="all" <?= $status === 'all' ? 'selected' : '' ?>>All</option>
        <option value="draft" <?= $status === 'draft' ? 'selected' : '' ?>>Draft</option>
        <option value="active" <?= $status === 'active' ? 'selected' : '' ?>>Active</option>
        <option value="renewing" <?= $status === 'renewing' ? 'selected' : '' ?>>Due to renew</option>
        <option value="expired" <?= $status === 'expired' ? 'selected' : '' ?>>Expired</option>
        <option value="cancelled" <?= $status === 'cancelled' ? 'selected' : '' ?>>Cancelled</option>
      </select>
    </div>
    <div>
      <label class="form-label" for="ctr-renewal">Renewal</label>
      <select class="form-select" id="ctr-renewal" name="renewal">
        <option value="all" <?= $renewal === 'all' ? 'selected' : '' ?>>All</option>
        <option value="week" <?= $renewal === 'week' ? 'selected' : '' ?>>This week</option>
        <option value="month" <?= $renewal === 'month' ? 'selected' : '' ?>>This month</option>
        <option value="overdue" <?= $renewal === 'overdue' ? 'selected' : '' ?>>Overdue</option>
      </select>
    </div>
    <div>
      <label class="form-label" for="ctr-signature">Signature</label>
      <select class="form-select" id="ctr-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>
      </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 bi-file-earmark-ruled"></i></div><h2>No contracts</h2><p>Try another filter, or add a contract here.</p></div>
      <?php else: foreach ($rows as $r):
          $signSt = (string) ($r['sign_status'] ?? '');
          $st = commerce_status_label($signSt === 'signed' ? 'signed' : (string) $r['status'], $signSt === 'signed' ? 'Document Signed' : ($statusLabels[$r['status']] ?? null));
      ?>
        <div class="svc-visit svc-tone-<?= e($st['tone']) ?>">
          <a class="svc-visit-main" href="<?= e(url('contracts/' . $r['id'])) ?>">
            <div class="svc-visit-icon"><i class="bi bi-file-earmark-ruled"></i></div>
            <div class="min-w-0 flex-grow-1">
              <div class="svc-visit-name"><?= e($r['title']) ?></div>
              <div class="svc-visit-sub">
                <span><i class="bi bi-hash"></i> <?= e($r['number']) ?></span>
                <?php if (!empty($r['account_name'])): ?><span><i class="bi bi-buildings"></i> <?= e($r['account_name']) ?></span><?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['renewal_date'])): ?><span><i class="bi bi-arrow-repeat"></i> Renews <?= e(dt_fmt($r['renewal_date'])) ?></span><?php endif; ?>
                <?php if (!empty($r['file_name'])): ?><span><i class="bi bi-file-earmark-pdf"></i> PDF</span><?php endif; ?>
                <?php if ($signSt === 'pending'): ?><span><i class="bi bi-pen"></i> Waiting on signature</span><?php endif; ?>
              </div>
            </div>
            <div class="task-meta">
              <div class="svc-visit-amt"><strong><?= e(money_fmt($r['amount'])) ?></strong><span>Value</span></div>
              <span class="due-pill <?= e($st['class']) ?>"><?= e($st['text']) ?></span>
            </div>
          </a>
        </div>
      <?php endforeach; endif; ?>
      <?php \App\Core\View::partial('pager', compact('page', 'pages')); ?>
    </div>
    <?php if (can_edit('contracts')): ?>
    <div class="col-lg-5" id="contract-form">
      <form class="svc-req ajax-form" action="<?= e(url('contracts')) ?>" method="post" enctype="multipart/form-data">
        <?= csrf_field() ?>
        <div class="svc-req-head"><span class="svc-req-icon"><i class="bi <?= $renewFrom ? 'bi-arrow-repeat' : 'bi-plus-lg' ?>"></i></span><div>
          <div class="svc-req-kicker"><?= $renewFrom ? 'Renewal' : 'New contract' ?></div>
          <h2><?= $renewFrom ? 'From ' . e($renewFrom['number']) : 'Dates on the customer' ?></h2>
          <p><?= $renewFrom ? 'Dates and amount are filled from the current contract. Upload the new PDF and save.' : 'Upload the contract PDF and set a renewal date.' ?></p>
        </div></div>
        <div class="svc-req-body">
          <?php if (!empty($draft['renewed_from_id'])): ?>
            <input type="hidden" name="renewed_from_id" value="<?= (int) $draft['renewed_from_id'] ?>">
          <?php endif; ?>
          <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'] ?>" <?= $draftAccount === (int) $acc['id'] ? 'selected' : '' ?>><?= e($acc['name']) ?></option>
            <?php endforeach; ?>
          </select>
          <label class="form-label">Title *</label>
          <input class="form-control mb-2" name="title" required value="<?= e((string) ($draft['title'] ?? '')) ?>">
          <label class="form-label">Amount</label>
          <input class="form-control mb-2" name="amount" type="number" step="0.01" value="<?= e((string) ($draft['amount'] ?? '')) ?>">
          <label class="form-label">Start</label>
          <input class="form-control mb-2" type="date" name="start_date" value="<?= e((string) ($draft['start_date'] ?? '')) ?>">
          <label class="form-label">End</label>
          <input class="form-control mb-2" type="date" name="end_date" value="<?= e((string) ($draft['end_date'] ?? '')) ?>">
          <label class="form-label">Renewal</label>
          <input class="form-control mb-2" type="date" name="renewal_date" value="<?= e((string) ($draft['renewal_date'] ?? '')) ?>">
          <label class="form-label">Contract PDF *</label>
          <input class="form-control mb-3" type="file" name="pdf" accept="application/pdf,.pdf" required>
          <button class="btn btn-primary" type="submit"><?= $renewFrom ? 'Save renewal contract' : 'Save contract' ?></button>
        </div>
      </form>
    </div>
    <?php endif; ?>
  </div>
</div>
