<?php $this->start('body');
    $stmt  = $this->data['stmt']  ?? [];
    $lines = $this->data['lines'] ?? [];
    $book  = $this->data['book']  ?? [];

    $stmtDeb = array_sum(array_map(fn($l) => (float)$l['debit'],  $lines));
    $stmtCrd = array_sum(array_map(fn($l) => (float)$l['credit'], $lines));
    $totalLines = count($lines);
    $matchedCnt = count(array_filter($lines, fn($l) => $l['match_status'] !== 'UNMATCHED'));
    $unmatched  = $totalLines - $matchedCnt;
    $isReconciled = ($stmt['status'] === 'RECONCILED');

    $statusChip = [
        'DRAFT'       => ['bg' => '#e8e0d5', 'ink' => '#7a6f63', 'label' => 'Draft'],
        'IN_PROGRESS' => ['bg' => '#eae0d0', 'ink' => '#7a6039', 'label' => 'In progress'],
        'RECONCILED'  => ['bg' => '#d8e5d1', 'ink' => '#4a6b3a', 'label' => 'Reconciled'],
    ];
    $chip = $statusChip[$stmt['status']] ?? ['bg'=>'#e8e0d5','ink'=>'#7a6f63','label'=>$stmt['status']];

    $matchChip = [
        'UNMATCHED'       => ['bg' => '#e8d5cf', 'ink' => '#8a4a3a', 'label' => 'Unmatched'],
        'AUTO_MATCHED'   => ['bg' => '#d8e5d1', 'ink' => '#4a6b3a', 'label' => 'Auto'],
        'MANUAL_MATCHED' => ['bg' => '#d8e5d1', 'ink' => '#4a6b3a', 'label' => 'Manual'],
        'IGNORED'        => ['bg' => '#e8e0d5', 'ink' => '#7a6f63', 'label' => 'Ignored'],
    ];
?>

<div class="d-flex align-items-center justify-content-between mb-3">
    <div>
        <h5 class="mb-0" style="font-weight:600;color:#4a3f36;">
            <i class="fas fa-university me-2" style="color:#c9a875;"></i>Reconcile · <?= htmlspecialchars($stmt['account_code']); ?> <?= htmlspecialchars($stmt['bank_name']); ?>
        </h5>
        <div class="text-muted small mt-1" style="color:#7a6f63;">
            Statement dated <?= htmlspecialchars($stmt['statement_date']); ?> &middot; imported <?= htmlspecialchars(date('d M Y H:i', strtotime($stmt['imported_on']))); ?> by <?= htmlspecialchars($stmt['imported_by_name']); ?>
        </div>
    </div>
    <div class="d-flex align-items-center gap-2">
        <span class="badge" style="background:<?= $chip['bg']; ?>;color:<?= $chip['ink']; ?>;font-size:.68rem;text-transform:capitalize;padding:.35rem .7rem;"><?= $chip['label']; ?></span>
        <a href="<?= PROOT; ?>BankRec" class="btn btn-sm" style="background:#faf6f0;border:1px solid #eae0d0;color:#4a3f36;"><i class="fas fa-arrow-left me-1"></i>Back</a>
    </div>
</div>

<!-- ── KPI strip ────────────────────────────────────────────────────────── -->
<div class="row g-3 mb-3">
    <div class="col-md-3"><div class="card border-0 shadow-sm h-100" style="border-left:4px solid #c9a875 !important;background:#faf6f0;"><div class="card-body p-3">
        <div style="text-transform:uppercase;letter-spacing:.4px;font-size:.66rem;color:#7a6f63;">Opening</div>
        <div style="font-weight:700;font-size:1.15rem;color:#4a3f36;">TZS <?= number_format((float)$stmt['opening_balance']); ?></div>
    </div></div></div>
    <div class="col-md-3"><div class="card border-0 shadow-sm h-100" style="border-left:4px solid #7a9e6e !important;background:#faf6f0;"><div class="card-body p-3">
        <div style="text-transform:uppercase;letter-spacing:.4px;font-size:.66rem;color:#7a6f63;">Total credits (in)</div>
        <div style="font-weight:700;font-size:1.15rem;color:#4a6b3f;">+ TZS <?= number_format($stmtCrd); ?></div>
    </div></div></div>
    <div class="col-md-3"><div class="card border-0 shadow-sm h-100" style="border-left:4px solid #b56b58 !important;background:#faf6f0;"><div class="card-body p-3">
        <div style="text-transform:uppercase;letter-spacing:.4px;font-size:.66rem;color:#7a6f63;">Total debits (out)</div>
        <div style="font-weight:700;font-size:1.15rem;color:#8a4a3a;">&minus; TZS <?= number_format($stmtDeb); ?></div>
    </div></div></div>
    <div class="col-md-3"><div class="card border-0 shadow-sm h-100" style="border-left:4px solid <?= $unmatched === 0 ? '#7a9e6e' : '#c9a875'; ?> !important;background:#faf6f0;"><div class="card-body p-3">
        <div style="text-transform:uppercase;letter-spacing:.4px;font-size:.66rem;color:#7a6f63;">Progress</div>
        <div style="font-weight:700;font-size:1.15rem;color:#4a3f36;"><?= $matchedCnt; ?> / <?= $totalLines; ?> matched</div>
        <div style="font-size:.72rem;color:#7a6f63;"><?= $unmatched; ?> unmatched</div>
    </div></div></div>
</div>

<!-- ── Toolbar ──────────────────────────────────────────────────────────── -->
<?php if (!$isReconciled): ?>
<div class="card border-0 shadow-sm mb-3" style="background:#faf6f0;">
    <div class="card-body p-2 d-flex align-items-center justify-content-between">
        <div style="color:#4a3f36;font-size:.86rem;">
            <i class="fas fa-magic me-1" style="color:#c9a875;"></i>
            Auto-match compares statement debits with book credits (and vice versa) on the same bank COA within &plusmn;3 days.
        </div>
        <div class="d-flex gap-2">
            <button type="button" id="btn_automatch" class="btn btn-sm" style="background:#c9a875;border-color:#c9a875;color:#4a3f36;font-weight:600;">
                <i class="fas fa-bolt me-1"></i>Run auto-match
            </button>
            <button type="button" id="btn_reconcile" class="btn btn-sm" style="background:#7a9e6e;border-color:#7a9e6e;color:#fff;font-weight:600;" <?= $unmatched > 0 ? 'disabled' : ''; ?>>
                <i class="fas fa-check-double me-1"></i>Mark reconciled
            </button>
        </div>
    </div>
</div>
<?php endif; ?>

<div class="row g-3">
    <!-- ── Statement lines ────────────────────────────────────────────── -->
    <div class="col-lg-7">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white d-flex align-items-center justify-content-between" style="border-bottom:1px solid #eae0d0;">
                <strong style="color:#4a3f36;"><i class="fas fa-file-alt me-2" style="color:#c9a875;"></i>Statement lines</strong>
                <span class="text-muted small" style="color:#7a6f63;"><?= $totalLines; ?> line(s)</span>
            </div>
            <div class="table-responsive" style="max-height:640px;overflow:auto;">
                <table class="table table-sm mb-0 align-middle">
                    <thead style="background:#f5efe6;position:sticky;top:0;z-index:1;">
                        <tr>
                            <th style="color:#4a3f36;">Date</th>
                            <th style="color:#4a3f36;">Description</th>
                            <th class="text-end" style="color:#4a3f36;">Dr</th>
                            <th class="text-end" style="color:#4a3f36;">Cr</th>
                            <th style="color:#4a3f36;">Status</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody id="stmt_body">
                        <?php foreach ($lines as $l):
                            $mc = $matchChip[$l['match_status']] ?? ['bg'=>'#e8e0d5','ink'=>'#7a6f63','label'=>$l['match_status']];
                            $rowBg = $l['match_status'] === 'UNMATCHED' ? '' : 'background:#faf6f0;';
                        ?>
                            <tr class="stmt-line" data-id="<?= (int)$l['c0d']; ?>" data-status="<?= htmlspecialchars($l['match_status']); ?>" style="<?= $rowBg; ?>cursor:<?= $isReconciled ? 'default' : 'pointer'; ?>;">
                                <td class="text-muted small" style="color:#4a3f36;white-space:nowrap;"><?= htmlspecialchars($l['txn_date']); ?></td>
                                <td class="small" style="color:#4a3f36;max-width:240px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="<?= htmlspecialchars((string)$l['description']); ?>">
                                    <?= htmlspecialchars((string)$l['description']); ?>
                                    <?php if (!empty($l['reference'])): ?><div class="small" style="color:#a89a8a;font-size:.68rem;"><?= htmlspecialchars((string)$l['reference']); ?></div><?php endif; ?>
                                    <?php if (!empty($l['je_no'])): ?><div style="font-size:.68rem;color:#4a6b3f;"><i class="fas fa-link me-1"></i>JE#<?= htmlspecialchars((string)$l['je_no']); ?></div><?php endif; ?>
                                </td>
                                <td class="text-end" style="color:<?= (float)$l['debit']>0?'#8a4a3a':'#a89a8a'; ?>;"><?= (float)$l['debit']>0 ? number_format((float)$l['debit']) : '—'; ?></td>
                                <td class="text-end" style="color:<?= (float)$l['credit']>0?'#4a6b3f':'#a89a8a'; ?>;"><?= (float)$l['credit']>0 ? number_format((float)$l['credit']) : '—'; ?></td>
                                <td><span class="badge" style="background:<?= $mc['bg']; ?>;color:<?= $mc['ink']; ?>;font-size:.6rem;text-transform:capitalize;"><?= $mc['label']; ?></span></td>
                                <td class="text-end">
                                    <?php if (!$isReconciled): ?>
                                        <?php if ($l['match_status'] === 'UNMATCHED'): ?>
                                            <button type="button" class="btn btn-sm btn-ignore" data-id="<?= (int)$l['c0d']; ?>" title="Ignore (bank fee/interest — no book counterpart)" style="background:transparent;border:none;color:#a89a8a;padding:.2rem .4rem;"><i class="fas fa-times"></i></button>
                                        <?php else: ?>
                                            <button type="button" class="btn btn-sm btn-unmatch" data-id="<?= (int)$l['c0d']; ?>" title="Unmatch" style="background:transparent;border:none;color:#b56b58;padding:.2rem .4rem;"><i class="fas fa-unlink"></i></button>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if (empty($lines)): ?>
                            <tr><td colspan="6" class="text-center py-4" style="color:#a89a8a;">No lines in this statement.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- ── Book journal lines ─────────────────────────────────────────── -->
    <div class="col-lg-5">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white d-flex align-items-center justify-content-between" style="border-bottom:1px solid #eae0d0;">
                <strong style="color:#4a3f36;"><i class="fas fa-book me-2" style="color:#c9a875;"></i>Unmatched book entries</strong>
                <span class="text-muted small" style="color:#7a6f63;"><?= count($book); ?> line(s)</span>
            </div>
            <div class="table-responsive" style="max-height:640px;overflow:auto;">
                <table class="table table-sm mb-0 align-middle">
                    <thead style="background:#f5efe6;position:sticky;top:0;z-index:1;">
                        <tr>
                            <th style="color:#4a3f36;">Date</th>
                            <th style="color:#4a3f36;">Source</th>
                            <th class="text-end" style="color:#4a3f36;">Dr</th>
                            <th class="text-end" style="color:#4a3f36;">Cr</th>
                        </tr>
                    </thead>
                    <tbody id="book_body">
                        <?php foreach ($book as $b): ?>
                            <tr class="book-line" data-id="<?= (int)$b['c0d']; ?>" style="cursor:<?= $isReconciled ? 'default' : 'pointer'; ?>;">
                                <td class="text-muted small" style="color:#4a3f36;white-space:nowrap;"><?= htmlspecialchars($b['entry_date']); ?></td>
                                <td class="small" style="color:#4a3f36;max-width:200px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="<?= htmlspecialchars((string)$b['je_narrative']); ?>">
                                    <span class="badge" style="background:#eae0d0;color:#7a6039;font-size:.6rem;text-transform:capitalize;"><?= htmlspecialchars(strtolower((string)$b['source_type'])); ?></span>
                                    <?= htmlspecialchars((string)($b['je_narrative'] ?? '')); ?>
                                    <div style="font-size:.66rem;color:#a89a8a;">JE#<?= htmlspecialchars((string)$b['je_no']); ?></div>
                                </td>
                                <td class="text-end" style="color:<?= (float)$b['debit']>0?'#4a6b3f':'#a89a8a'; ?>;"><?= (float)$b['debit']>0 ? number_format((float)$b['debit']) : '—'; ?></td>
                                <td class="text-end" style="color:<?= (float)$b['credit']>0?'#8a4a3a':'#a89a8a'; ?>;"><?= (float)$b['credit']>0 ? number_format((float)$b['credit']) : '—'; ?></td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if (empty($book)): ?>
                            <tr><td colspan="4" class="text-center py-4" style="color:#a89a8a;">All book entries matched. <i class="fas fa-check-circle" style="color:#7a9e6e;"></i></td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
            <div class="card-footer bg-white" style="border-top:1px solid #eae0d0;font-size:.74rem;color:#7a6f63;">
                <i class="fas fa-info-circle me-1" style="color:#c9a875;"></i>
                Click an <strong>unmatched</strong> statement line, then a book line to pair them.
            </div>
        </div>
    </div>
</div>

<?php $this->end(); ?>

<?php $this->start('section_js'); ?>
<script>
(function () {
    var PROOT   = '<?= PROOT; ?>';
    var STMT_ID = <?= (int)$stmt['c0d']; ?>;
    var LOCKED  = <?= $isReconciled ? 'true' : 'false'; ?>;
    var selectedStmt = null;

    if (LOCKED) return; // read-only view once reconciled

    // Highlight selected statement line (only if UNMATCHED)
    $('#stmt_body').on('click', '.stmt-line', function () {
        var $tr = $(this);
        if ($tr.data('status') !== 'UNMATCHED') return;
        $('.stmt-line').removeClass('selected').css('outline', '');
        $tr.addClass('selected').css('outline', '2px solid #c9a875');
        selectedStmt = parseInt($tr.data('id'), 10);
        rsToast('Statement line selected — click a book entry to pair.', 'info', 2200);
    });

    // Click a book line to pair
    $('#book_body').on('click', '.book-line', function () {
        var jl = parseInt($(this).data('id'), 10);
        if (!selectedStmt) { rsToast('Select an unmatched statement line first.', 'warning'); return; }
        $.post(PROOT + 'BankRec/matchAj', { statement_line_id: selectedStmt, journal_line_id: jl }, 'json')
            .done(function (res) {
                if (res && res.ok) { rsToast('Matched. Reloading…', 'success'); setTimeout(function () { location.reload(); }, 500); }
                else                { rsToast(res && res.msg ? res.msg : 'Match failed.', 'error', 4000); }
            })
            .fail(function () { rsToast('Server unreachable.', 'error'); });
    });

    // Unmatch
    $('#stmt_body').on('click', '.btn-unmatch', function (ev) {
        ev.stopPropagation();
        var sl = parseInt($(this).data('id'), 10);
        $.confirm({
            title: 'Unmatch this line?',
            content: 'The book entry will return to the unmatched pool.',
            type: 'orange',
            buttons: {
                yes: { text: 'Unmatch', btnClass: 'btn-warning', action: function () {
                    $.post(PROOT + 'BankRec/unmatchAj', { statement_line_id: sl }, 'json')
                        .done(function (res) {
                            if (res && res.ok) { rsToast('Unmatched. Reloading…', 'success'); setTimeout(function () { location.reload(); }, 400); }
                            else                { rsToast('Failed: ' + (res.msg || 'unknown'), 'error'); }
                        });
                }},
                cancel: { text: 'Cancel', btnClass: 'btn-light' }
            }
        });
    });

    // Ignore (bank fee / interest, no book counterpart)
    $('#stmt_body').on('click', '.btn-ignore', function (ev) {
        ev.stopPropagation();
        var sl = parseInt($(this).data('id'), 10);
        $.confirm({
            title: 'Ignore this line?',
            content: 'Use this for bank fees or interest that have no book counterpart yet. You can post the missing JE later.',
            type: 'orange',
            buttons: {
                yes: { text: 'Ignore', btnClass: 'btn-warning', action: function () {
                    $.post(PROOT + 'BankRec/ignoreAj', { statement_line_id: sl }, 'json')
                        .done(function (res) {
                            if (res && res.ok) { rsToast('Line ignored. Reloading…', 'success'); setTimeout(function () { location.reload(); }, 400); }
                            else                { rsToast('Failed: ' + (res.msg || 'unknown'), 'error'); }
                        });
                }},
                cancel: { text: 'Cancel', btnClass: 'btn-light' }
            }
        });
    });

    // Auto-match
    $('#btn_automatch').on('click', function () {
        var $btn = $(this).prop('disabled', true).html('<i class="fas fa-spinner fa-spin me-1"></i>Matching…');
        $.post(PROOT + 'BankRec/autoMatchAj/' + STMT_ID, {}, 'json')
            .done(function (res) {
                if (res && res.ok) {
                    if (res.matched > 0) { rsToast('Auto-matched ' + res.matched + ' line(s). Reloading…', 'success'); setTimeout(function () { location.reload(); }, 600); }
                    else                 { rsToast('No new matches found — nothing lined up.', 'info', 3500); $btn.prop('disabled', false).html('<i class="fas fa-bolt me-1"></i>Run auto-match'); }
                } else {
                    rsToast('Auto-match failed: ' + (res.msg || 'unknown'), 'error', 4500);
                    $btn.prop('disabled', false).html('<i class="fas fa-bolt me-1"></i>Run auto-match');
                }
            })
            .fail(function () { rsToast('Server unreachable.', 'error'); $btn.prop('disabled', false).html('<i class="fas fa-bolt me-1"></i>Run auto-match'); });
    });

    // Mark reconciled
    $('#btn_reconcile').on('click', function () {
        $.confirm({
            title: 'Mark statement as reconciled?',
            content: 'This locks the statement — no further edits. Every line is matched or explicitly ignored.',
            type: 'green',
            buttons: {
                yes: { text: 'Reconcile', btnClass: 'btn-success', action: function () {
                    $.post(PROOT + 'BankRec/markReconciledAj/' + STMT_ID, {}, 'json')
                        .done(function (res) {
                            if (res && res.ok) { rsToast('Statement reconciled.', 'success'); setTimeout(function () { location.reload(); }, 500); }
                            else                { rsToast(res && res.msg ? res.msg : 'Reconcile failed.', 'error', 4500); }
                        });
                }},
                cancel: { text: 'Cancel', btnClass: 'btn-light' }
            }
        });
    });
})();
</script>
<?php $this->end(); ?>
