<?php $this->start('body'); ?>
<?php
$s = $this->data['s']; $sum = $this->data['sum'];
$lines = $this->data['stmt_lines']; $book = $this->data['book_lines'];
$suggestions = $this->data['suggestions'];

$badge = ['OPEN' => 'warning text-dark', 'RECONCILED' => 'success', 'VOID' => 'secondary'][$s['status']] ?? 'light';
$locked = $s['status'] !== 'OPEN';

// Index suggestions by statement line id
$sugMap = [];
foreach ($suggestions as $x) $sugMap[(int)$x['stmt_line_id']] = $x;

// Index book lines by id for quick lookup on matched statement rows
$bookById = [];
foreach ($book as $b) $bookById[(int)$b['c0d']] = $b;
?>

<div class="d-flex align-items-start justify-content-between mb-3 flex-wrap gap-2">
  <div>
    <h5 class="mb-0 fw-semibold"><i class="fas fa-cash-register me-2 text-muted"></i>
      <span class="font-monospace"><?= htmlspecialchars($s['account_code']); ?></span>
      <?= htmlspecialchars($s['account_name']); ?>
      <span class="badge bg-<?= $badge; ?> ms-2" style="font-size:.65em;vertical-align:middle;"><?= htmlspecialchars($s['status']); ?></span>
    </h5>
    <div class="text-muted small">
      Statement <?= htmlspecialchars($s['reference'] ?: '(no ref)'); ?>
      &middot; <?= humanDate($s['statement_from']); ?> &rarr; <?= humanDate($s['statement_to']); ?>
      <?php if ($s['reconciled_on']): ?> &middot; reconciled <?= humanDateTime($s['reconciled_on']); ?><?php endif; ?>
    </div>
  </div>
  <a href="<?= PROOT; ?>BankRecon" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i>Statements</a>
</div>

<?= flashHtml(); ?>

<!-- KPI strip -->
<div class="row g-2 mb-3">
  <div class="col-6 col-md-3"><div class="card border-0 shadow-sm h-100"><div class="card-body py-2">
    <div class="text-uppercase text-muted small">Statement closing</div>
    <div class="fs-5 fw-bold">TZS <?= number_format((float)$s['closing_balance'], 2); ?></div>
    <div class="small text-muted">from <?= number_format((float)$s['opening_balance'], 2); ?></div>
  </div></div></div>
  <div class="col-6 col-md-3"><div class="card border-0 shadow-sm h-100"><div class="card-body py-2">
    <div class="text-uppercase text-muted small">Book balance</div>
    <div class="fs-5 fw-bold">TZS <?= number_format($sum['book_balance'], 2); ?></div>
    <div class="small text-muted">general ledger @ <?= humanDate($s['statement_to']); ?></div>
  </div></div></div>
  <div class="col-6 col-md-3"><div class="card border-0 shadow-sm h-100"><div class="card-body py-2">
    <div class="text-uppercase text-muted small">Matched</div>
    <div class="fs-5 fw-bold"><?= (int)$sum['stmt_matched']; ?> / <?= (int)$sum['stmt_count']; ?></div>
    <?php $pct = $sum['stmt_count'] > 0 ? round($sum['stmt_matched'] * 100 / $sum['stmt_count']) : 0; ?>
    <div class="progress" style="height:4px;"><div class="progress-bar" style="width:<?= $pct; ?>%;"></div></div>
  </div></div></div>
  <div class="col-6 col-md-3"><div class="card border-0 shadow-sm h-100"><div class="card-body py-2">
    <div class="text-uppercase text-muted small">Difference</div>
    <div class="fs-5 fw-bold <?= abs($sum['difference']) < 0.01 ? 'text-success' : 'text-danger'; ?>">
      TZS <?= number_format($sum['difference'], 2); ?>
    </div>
    <div class="small text-muted">reconciled book vs bank</div>
  </div></div></div>
</div>

<!-- Reconciliation formula -->
<div class="card border-0 shadow-sm mb-3">
  <div class="card-body py-2 small">
    <div class="row g-2">
      <div class="col-md-6">
        <div class="text-uppercase text-muted mb-1" style="font-size:.65em;letter-spacing:.08em;">Book side</div>
        Book balance &nbsp;<strong class="font-monospace"><?= number_format($sum['book_balance'], 2); ?></strong>
        <?php if (abs($sum['unposted_from_stmt']) >= 0.01): ?>
          <?= $sum['unposted_from_stmt'] >= 0 ? ' + ' : ' - '; ?>
          unposted adjustments <strong class="font-monospace"><?= number_format(abs($sum['unposted_from_stmt']), 2); ?></strong>
        <?php endif; ?>
        = <strong class="font-monospace"><?= number_format($sum['reconciled_book'], 2); ?></strong>
      </div>
      <div class="col-md-6">
        <div class="text-uppercase text-muted mb-1" style="font-size:.65em;letter-spacing:.08em;">Bank side</div>
        Statement closing <strong class="font-monospace"><?= number_format((float)$s['closing_balance'], 2); ?></strong>
        <?php if (abs($sum['uncleared_books']) >= 0.01): ?>
          <?= $sum['uncleared_books'] >= 0 ? ' - ' : ' + '; ?>
          uncleared items <strong class="font-monospace"><?= number_format(abs($sum['uncleared_books']), 2); ?></strong>
        <?php endif; ?>
        = <strong class="font-monospace"><?= number_format($sum['reconciled_bank'], 2); ?></strong>
      </div>
    </div>
  </div>
</div>

<!-- Action bar -->
<?php if (!$locked): ?>
  <div class="card border-0 shadow-sm mb-3">
    <div class="card-body py-2 d-flex flex-wrap gap-2 align-items-center">
      <span class="text-uppercase text-muted small me-2"><i class="fas fa-play-circle me-1"></i>Actions</span>
      <?php if (count($suggestions) > 0): ?>
        <form method="POST" action="<?= PROOT; ?>BankRecon/autoMatch/<?= (int)$s['c0d']; ?>" class="d-inline"><?= csrf_field(); ?>
          <button class="btn btn-sm btn-primary"><i class="fas fa-magic me-1"></i>Auto-match (<?= count($suggestions); ?> proposals)</button>
        </form>
      <?php endif; ?>
      <?php if ($sum['stmt_unmatched'] === 0 && abs($sum['difference']) < 0.01): ?>
        <form method="POST" action="<?= PROOT; ?>BankRecon/complete/<?= (int)$s['c0d']; ?>" class="d-inline"><?= csrf_field(); ?>
          <button class="btn btn-sm btn-success"><i class="fas fa-check-circle me-1"></i>Complete reconciliation</button>
        </form>
      <?php endif; ?>
      <button type="button" class="btn btn-sm btn-outline-danger ms-auto" onclick="doVoid()"><i class="fas fa-ban me-1"></i>Void</button>
    </div>
  </div>
<?php endif; ?>

<!-- Two-column workbench -->
<div class="row g-3">

  <!-- Statement lines -->
  <div class="col-lg-6">
    <div class="card border-0 shadow-sm">
      <div class="card-body p-0">
        <div class="p-3 pb-2 d-flex justify-content-between align-items-center">
          <h6 class="text-uppercase text-muted small mb-0">Statement · <?= count($lines); ?> lines</h6>
          <span class="small text-muted">
            <span class="text-success">in <?= number_format($sum['stmt_in'], 0); ?></span>
            &middot;
            <span class="text-danger">out <?= number_format($sum['stmt_out'], 0); ?></span>
          </span>
        </div>
        <table class="table table-sm mb-0 align-middle">
          <thead class="table-light">
            <tr>
              <th style="width:88px;">Date</th>
              <th>Description</th>
              <th class="money" style="width:120px;">Amount</th>
              <th style="width:130px;"></th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($lines as $l):
                $isMatched = (int)$l['matched_journal_line_id'] !== 0;
                $sug = $sugMap[(int)$l['c0d']] ?? null;
            ?>
              <tr class="<?= $isMatched ? 'table-success' : ($sug ? 'table-warning' : ''); ?>">
                <td class="small"><?= humanDate($l['txn_date']); ?></td>
                <td>
                  <div class="small fw-semibold"><?= htmlspecialchars($l['description']); ?></div>
                  <?php if ($l['reference']): ?>
                    <div class="small text-muted font-monospace"><?= htmlspecialchars($l['reference']); ?></div>
                  <?php endif; ?>
                  <?php if ($isMatched): ?>
                    <div class="small text-success">
                      <i class="fas fa-link me-1"></i><?= htmlspecialchars((string)$l['matched_je_no']); ?>
                      &middot; <?= htmlspecialchars((string)($l['matched_narrative'] ?: '')); ?>
                    </div>
                  <?php elseif ($sug): ?>
                    <div class="small text-warning-emphasis">
                      <i class="fas fa-lightbulb me-1"></i>
                      Suggest &rarr; <?= htmlspecialchars((string)$sug['journal_line']['je_no']); ?>
                      (<?= (int)$sug['gap_days']; ?>d)
                    </div>
                  <?php endif; ?>
                </td>
                <td class="money font-monospace small <?= (float)$l['amount'] >= 0 ? 'text-success' : 'text-danger'; ?>">
                  <?= number_format((float)$l['amount'], 2); ?>
                </td>
                <td class="text-end">
                  <?php if (!$locked): ?>
                    <?php if ($isMatched): ?>
                      <form method="POST" action="<?= PROOT; ?>BankRecon/unmatch/<?= (int)$l['c0d']; ?>" class="d-inline"><?= csrf_field(); ?>
                        <button class="btn btn-sm btn-outline-secondary" title="Unmatch"><i class="fas fa-unlink"></i></button>
                      </form>
                    <?php else: ?>
                      <button type="button" class="btn btn-sm btn-outline-primary" onclick="openMatch(<?= (int)$l['c0d']; ?>, <?= (float)$l['amount']; ?>)" title="Match"><i class="fas fa-link"></i></button>
                      <button type="button" class="btn btn-sm btn-outline-info" onclick="openAdjust(<?= (int)$l['c0d']; ?>, <?= (float)$l['amount']; ?>, <?= htmlspecialchars(json_encode($l['description']), ENT_QUOTES); ?>)" title="Post as adjustment JE"><i class="fas fa-plus-circle"></i></button>
                    <?php endif; ?>
                  <?php endif; ?>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <!-- Book lines -->
  <div class="col-lg-6">
    <div class="card border-0 shadow-sm">
      <div class="card-body p-0">
        <div class="p-3 pb-2 d-flex justify-content-between align-items-center">
          <h6 class="text-uppercase text-muted small mb-0">General ledger · <?= count($book); ?> postings</h6>
          <span class="small text-muted">
            uncleared <span class="fw-semibold"><?= number_format($sum['uncleared_books'], 0); ?></span>
            (<?= (int)$sum['uncleared_count']; ?>)
          </span>
        </div>
        <table class="table table-sm mb-0 align-middle">
          <thead class="table-light">
            <tr>
              <th style="width:88px;">Date</th>
              <th>Journal</th>
              <th class="money" style="width:100px;">Debit</th>
              <th class="money" style="width:100px;">Credit</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($book as $b):
                $used = (int)$b['matched_stmt_line_id'] !== 0;
            ?>
              <tr class="<?= $used ? 'table-success' : ''; ?>">
                <td class="small"><?= humanDate($b['entry_date']); ?></td>
                <td>
                  <a href="<?= PROOT; ?>Journals/view/<?= (int)($b['c0d'] ?: 0); ?>" class="font-monospace small text-decoration-none"><?= htmlspecialchars($b['je_no']); ?></a>
                  <div class="small text-muted"><?= htmlspecialchars($b['source_type']); ?><?php if ($b['narrative']): ?> &middot; <?= htmlspecialchars($b['narrative']); ?><?php endif; ?></div>
                  <?php if ($used): ?>
                    <div class="small text-success"><i class="fas fa-link me-1"></i>matched</div>
                  <?php endif; ?>
                </td>
                <td class="money font-monospace small <?= (float)$b['debit'] > 0 ? 'text-success' : ''; ?>">
                  <?= (float)$b['debit'] > 0 ? number_format((float)$b['debit'], 2) : '—'; ?>
                </td>
                <td class="money font-monospace small <?= (float)$b['credit'] > 0 ? 'text-danger' : ''; ?>">
                  <?= (float)$b['credit'] > 0 ? number_format((float)$b['credit'], 2) : '—'; ?>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

<!-- Hidden forms + modal state carriers -->
<form id="matchForm"   method="POST" action="" class="d-none"><?= csrf_field(); ?>
  <input type="hidden" name="journal_line_id" id="fJl">
</form>
<form id="adjustForm"  method="POST" action="" class="d-none"><?= csrf_field(); ?>
  <input type="hidden" name="contra_account_id" id="fContra">
  <input type="hidden" name="narrative"         id="fNarr">
</form>
<form id="voidForm"    method="POST" action="<?= PROOT; ?>BankRecon/voidStmt/<?= (int)$s['c0d']; ?>" class="d-none"><?= csrf_field(); ?></form>

<?php $this->end(); ?>
<?php $this->start('section_js'); ?>
<script>
const PROOT = '<?= PROOT; ?>';

// The book-line candidates the match dialog can pick from, filtered by amount.
const BOOK_LINES = <?= json_encode(array_map(fn($b) => [
    'id'      => (int)$b['c0d'],
    'signed'  => round((float)$b['debit'] - (float)$b['credit'], 2),
    'je_no'   => $b['je_no'],
    'date'    => $b['entry_date'],
    'source'  => $b['source_type'],
    'narr'    => $b['narrative'],
    'used'    => (int)$b['matched_stmt_line_id'] !== 0,
], $book), JSON_UNESCAPED_UNICODE); ?>;

// Expense / income accounts for adjustments (7xxx expenses + 8xxx revenue)
const CONTRA_ACCOUNTS = <?= json_encode(
    (new DB())->mySelect(
        "SELECT c0d, account_code, account_name FROM chart_of_accounts
          WHERE is_active = 1 AND account_type IN ('EXPENSE','REVENUE','ASSET','LIABILITY')
            AND account_code NOT IN ('" . ($s['account_code']) . "')
          ORDER BY account_code", []
    ) ?: [], JSON_UNESCAPED_UNICODE
); ?>;

function openMatch(slId, amount) {
    const options = BOOK_LINES.filter(b => !b.used && Math.abs(b.signed - amount) < 0.01);
    if (!options.length) {
        $.alert('No unmatched journal lines with the same amount (' + amount.toFixed(2) + '). Try posting an adjustment instead.');
        return;
    }
    const opts = options.map(b => `
        <div class="form-check">
          <input class="form-check-input" type="radio" name="mc" id="mc${b.id}" value="${b.id}">
          <label class="form-check-label small" for="mc${b.id}">
            <span class="font-monospace">${b.je_no}</span> · ${b.date} · ${b.source}
            <div class="text-muted small">${b.narr || '(no narrative)'}</div>
          </label>
        </div>`).join('');
    $.confirm({
        title: 'Match statement line',
        content: `<div class="mb-2 small text-muted">Amount: <strong>${amount.toFixed(2)}</strong></div>${opts}`,
        type: 'blue',
        buttons: {
            go: { text: 'Match', btnClass: 'btn-primary', action: function() {
                const c = document.querySelector('input[name="mc"]:checked');
                if (!c) { $.alert('Pick a journal line.'); return false; }
                const f = document.getElementById('matchForm');
                f.action = PROOT + 'BankRecon/match/' + slId;
                document.getElementById('fJl').value = c.value;
                f.submit();
            }},
            back: function(){}
        }
    });
}

function openAdjust(slId, amount, defaultNarr) {
    const dir = amount > 0 ? 'money IN' : 'money OUT';
    const opts = CONTRA_ACCOUNTS.map(a =>
        `<option value="${a.c0d}">${a.account_code} · ${a.account_name}</option>`).join('');
    $.confirm({
        title: 'Post adjustment JE',
        content: `
            <div class="mb-2 small text-muted">
              Creates a balancing journal entry for this ${dir} (${Math.abs(amount).toFixed(2)}).
              The bank side is auto-picked; you choose the contra account.
            </div>
            <label class="form-label small mb-1">Contra account</label>
            <select id="ac" class="form-select form-select-sm mb-2">
              <option value="">— pick —</option>
              ${opts}
            </select>
            <label class="form-label small mb-1">Narrative</label>
            <input id="an" class="form-control form-control-sm" value="${(defaultNarr || '').replace(/"/g,'&quot;')}">
        `,
        type: 'blue',
        buttons: {
            go: { text: 'Post', btnClass: 'btn-primary', action: function() {
                const a = document.getElementById('ac').value;
                const n = document.getElementById('an').value.trim();
                if (!a) { $.alert('Pick a contra account.'); return false; }
                if (!n) { $.alert('Narrative is required.'); return false; }
                const f = document.getElementById('adjustForm');
                f.action = PROOT + 'BankRecon/adjust/' + slId;
                document.getElementById('fContra').value = a;
                document.getElementById('fNarr').value   = n;
                f.submit();
            }},
            back: function(){}
        }
    });
}

function doVoid() {
    $.confirm({
        title: 'Void this statement?',
        content: 'Removes it from the list. Any matches made here will be preserved on the journal lines they linked to, but the statement itself will be inaccessible.',
        type: 'red',
        buttons: {
            go: { text: 'Void', btnClass: 'btn-danger', action: () => document.getElementById('voidForm').submit() },
            back: function(){}
        }
    });
}
</script>
<?php $this->end(); ?>
