<?php $this->start('body');
    $box       = $this->data['box']    ?? null;
    $recent    = $this->data['recent'] ?? [];
    $canConfig = (bool)($this->data['can_config'] ?? false);
    $currency  = $box['currency'] ?? 'TZS';
    $bal       = (float)($box['current_balance'] ?? 0);
    $float     = (float)($box['float_amount']    ?? 0);
    $pct       = $float > 0 ? min(100, round($bal / $float * 100)) : 0;
    $threshold = $float > 0 ? $float * ((int)($box['low_water_pct'] ?? 30) / 100.0) : 0;
    $isLow     = $float > 0 && $bal < $threshold;
    $movementChip = [
        'DISBURSE'   => ['#F5EAE1','#C48579','Disbursed'],
        'REPLENISH'  => ['#EAF2E8','#3F5C43','Replenished'],
        'RETURN'     => ['#EEF2F6','#7A8BA1','Returned'],
        'ADJUSTMENT' => ['#EDE7DC','#5B4F3C','Adjusted'],
    ];
?>

<div class="d-flex align-items-center justify-content-between mb-3">
    <div>
        <h5 class="mb-0" style="font-weight:600;"><i class="fas fa-wallet me-2 text-muted"></i><?= htmlspecialchars($box['name'] ?? 'Petty Cash Box'); ?></h5>
        <div class="text-muted small mt-1" style="font-size:.72rem;">
            Custodian: <?= htmlspecialchars($box['custodian_name'] ?: '—'); ?>
            · Float target: <?= $currency; ?> <?= number_format($float); ?>
            · Threshold: <?= (int)($box['low_water_pct'] ?? 30); ?>% (<?= $currency; ?> <?= number_format($threshold); ?>)
        </div>
    </div>
    <div>
        <a href="<?= PROOT; ?>PettyCashBox/movements" class="btn btn-sm btn-outline-secondary me-1"><i class="fas fa-history me-1"></i>Full log</a>
        <?php if ($canConfig): ?>
            <button type="button" id="btn_config" class="btn btn-sm btn-outline-secondary"><i class="fas fa-sliders-h me-1"></i>Configure</button>
        <?php endif; ?>
    </div>
</div>

<div class="row g-3 mb-3">
    <div class="col-md-6">
        <div class="card border-0 shadow-sm h-100" style="background:<?= $isLow ? '#F5EAE1' : '#F8FAFC'; ?>;border:1px solid <?= $isLow ? '#C48579' : '#E2E8F0'; ?>;">
            <div class="card-body p-3">
                <div class="text-muted small" style="font-size:.68rem;">Current balance</div>
                <div style="font-weight:700;font-size:1.9rem;color:<?= $isLow ? '#C48579' : '#334155'; ?>;">
                    <?= $currency; ?> <?= number_format($bal); ?>
                </div>
                <?php if ($float > 0): ?>
                    <div class="progress mt-2" style="height:6px;background:#E2E8F0;">
                        <div class="progress-bar" role="progressbar" style="width:<?= $pct; ?>%;background:<?= $isLow ? '#C48579' : '#7A9E7E'; ?>;"></div>
                    </div>
                    <div class="text-muted mt-1" style="font-size:.62rem;">
                        <?= $pct; ?>% of float
                        <?php if ($isLow): ?><span class="ms-2" style="color:#C48579;font-weight:600;"><i class="fas fa-exclamation-triangle me-1"></i>Below <?= (int)$box['low_water_pct']; ?>% threshold — replenish</span><?php endif; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <div class="col-md-6">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body p-3">
                <div class="text-muted small mb-2" style="font-size:.68rem;font-weight:600;">Quick actions</div>
                <button type="button" id="btn_replenish" class="btn btn-sm w-100 mb-2" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;">
                    <i class="fas fa-arrow-down me-1"></i>Replenish (bank → tin)
                </button>
                <?php if ($canConfig): ?>
                    <button type="button" id="btn_adjust" class="btn btn-sm w-100" style="background:#fff;border:1px solid #EDE7DC;color:#5B4F3C;font-weight:600;">
                        <i class="fas fa-balance-scale me-1"></i>Record over/short
                    </button>
                <?php endif; ?>
                <div class="text-muted mt-2" style="font-size:.62rem;">
                    Max single disbursement: <?= $currency; ?> <?= number_format((float)($box['max_disbursement'] ?? 0)); ?>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="card border-0 shadow-sm">
    <div class="card-header py-2 small" style="background:#F8FAFC;border-bottom:1px solid #E2E8F0;font-weight:600;color:#334155;">
        <i class="fas fa-clock me-1 text-muted"></i>Recent movements (last 20)
    </div>
    <div class="table-responsive">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light">
                <tr>
                    <th style="width:110px;">When</th>
                    <th style="width:110px;">Type</th>
                    <th class="text-end" style="width:130px;">Amount</th>
                    <th class="text-end" style="width:130px;">Balance after</th>
                    <th>Narrative</th>
                    <th style="width:110px;">LPO</th>
                    <th style="width:150px;">By</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($recent as $m):
                    $mc = $movementChip[$m['movement_type']] ?? ['#F1F5F9','#334155',$m['movement_type']];
                    $sign = ($m['movement_type'] === 'DISBURSE' || ((float)$m['amount'] < 0)) ? '−' : '+';
                    $absAmt = abs((float)$m['amount']);
                ?>
                    <tr>
                        <td class="small text-muted"><?= htmlspecialchars(date('d M · H:i', strtotime($m['performed_on']))); ?></td>
                        <td><span class="badge" style="background:<?= $mc[0]; ?>;color:<?= $mc[1]; ?>;border:1px solid <?= $mc[1]; ?>;font-size:.62rem;text-transform:capitalize;"><?= htmlspecialchars($mc[2]); ?></span></td>
                        <td class="text-end small" style="font-weight:600;color:<?= $sign === '−' ? '#C48579' : '#3F5C43'; ?>;"><?= $sign; ?> <?= number_format($absAmt); ?></td>
                        <td class="text-end small text-muted"><?= number_format((float)$m['balance_after']); ?></td>
                        <td class="small text-muted"><?= htmlspecialchars((string)$m['narrative']); ?></td>
                        <td class="small">
                            <?php if (!empty($m['lpo_no'])): ?>
                                <a href="<?= PROOT; ?>Lpos/view/<?= (int)$m['related_lpo_id']; ?>" class="text-decoration-none" style="color:#7A8BA1;font-weight:600;"><?= htmlspecialchars($m['lpo_no']); ?></a>
                            <?php else: ?>
                                <span class="text-muted">—</span>
                            <?php endif; ?>
                        </td>
                        <td class="small text-muted"><?= htmlspecialchars((string)$m['performed_by_name']); ?></td>
                    </tr>
                <?php endforeach; ?>
                <?php if (empty($recent)): ?>
                    <tr><td colspan="7" class="text-center text-muted py-4" style="font-size:.72rem;">No movements yet — replenish the box to start.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
(function () {
    document.getElementById('btn_replenish').addEventListener('click', function () {
        $.confirm({
            title: 'Replenish petty cash?',
            content:
                '<form id="rp_form"><div class="row g-2 mb-2"><div class="col-6">' +
                '<label class="form-label small">Amount *</label>' +
                '<input type="number" step="0.01" min="0" name="amount" class="form-control form-control-sm" required></div></div>' +
                '<label class="form-label small">Narrative</label>' +
                '<input type="text" name="narrative" class="form-control form-control-sm" placeholder="e.g. Float top-up · CBA acct 1234 → tin"></form>',
            type: 'green',
            buttons: {
                save: { text: 'Replenish', btnClass: 'btn-success', action: function () {
                    var fd = document.getElementById('rp_form');
                    var payload = { amount: fd.amount.value, narrative: fd.narrative.value };
                    if (!(parseFloat(payload.amount)>0)) { $.alert({title:'Amount required',type:'orange'}); return false; }
                    $.post('<?= PROOT; ?>PettyCashBox/replenishAj', payload, function (r) {
                        if (r && r.ok) { rsToast('Balance now ' + Number(r.balance_after).toLocaleString(), 'success'); setTimeout(function(){location.reload();}, 500); }
                        else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                    }, 'json');
                    return false;
                }},
                cancel: function () {}
            }
        });
    });

    <?php if ($canConfig): ?>
    document.getElementById('btn_adjust').addEventListener('click', function () {
        $.confirm({
            title: 'Record over/short',
            content:
                '<div class="small text-muted mb-2">Positive = overage (found extra cash). Negative = shortage.</div>' +
                '<form id="aj_form"><div class="row g-2 mb-2"><div class="col-6">' +
                '<label class="form-label small">Amount (± signed) *</label>' +
                '<input type="number" step="0.01" name="amount" class="form-control form-control-sm" required></div></div>' +
                '<label class="form-label small">Narrative *</label>' +
                '<textarea name="narrative" class="form-control form-control-sm" rows="2" required placeholder="Explain — required for audit"></textarea></form>',
            type: 'orange',
            buttons: {
                save: { text: 'Record', btnClass: 'btn-warning', action: function () {
                    var fd = document.getElementById('aj_form');
                    var payload = { amount: fd.amount.value, narrative: fd.narrative.value };
                    if (parseFloat(payload.amount)===0 || isNaN(parseFloat(payload.amount))) { $.alert({title:'Amount required',type:'orange'}); return false; }
                    if (!payload.narrative.trim()) { $.alert({title:'Narrative required',type:'orange'}); return false; }
                    $.post('<?= PROOT; ?>PettyCashBox/adjustmentAj', payload, function (r) {
                        if (r && r.ok) { rsToast('Adjusted. Balance now ' + Number(r.balance_after).toLocaleString(), 'success'); setTimeout(function(){location.reload();}, 500); }
                        else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                    }, 'json');
                    return false;
                }},
                cancel: function () {}
            }
        });
    });

    document.getElementById('btn_config').addEventListener('click', function () {
        $.confirm({
            title: 'Configure petty cash box',
            content:
                '<form id="cf_form">' +
                '<div class="mb-2"><label class="form-label small">Box name</label>' +
                '<input type="text" name="name" class="form-control form-control-sm" value="<?= htmlspecialchars(addslashes($box['name'] ?? ''), ENT_QUOTES); ?>"></div>' +
                '<div class="mb-2"><label class="form-label small">Custodian name</label>' +
                '<input type="text" name="custodian_name" class="form-control form-control-sm" value="<?= htmlspecialchars(addslashes($box['custodian_name'] ?? ''), ENT_QUOTES); ?>"></div>' +
                '<div class="row g-2 mb-2">' +
                '<div class="col-4"><label class="form-label small">Float target</label><input type="number" step="0.01" min="0" name="float_amount" class="form-control form-control-sm" value="<?= (float)($box['float_amount'] ?? 0); ?>"></div>' +
                '<div class="col-4"><label class="form-label small">Max disbursement</label><input type="number" step="0.01" min="0" name="max_disbursement" class="form-control form-control-sm" value="<?= (float)($box['max_disbursement'] ?? 0); ?>"></div>' +
                '<div class="col-4"><label class="form-label small">Low-water %</label><input type="number" min="1" max="100" name="low_water_pct" class="form-control form-control-sm" value="<?= (int)($box['low_water_pct'] ?? 30); ?>"></div>' +
                '</div></form>',
            type: 'blue',
            buttons: {
                save: { text: 'Save', btnClass: 'btn-primary', action: function () {
                    var fd = document.getElementById('cf_form');
                    var payload = {
                        name: fd.name.value,
                        custodian_name: fd.custodian_name.value,
                        float_amount: fd.float_amount.value,
                        max_disbursement: fd.max_disbursement.value,
                        low_water_pct: fd.low_water_pct.value
                    };
                    $.post('<?= PROOT; ?>PettyCashBox/configAj', payload, function (r) {
                        if (r && r.ok) { rsToast('Saved.', 'success'); setTimeout(function(){location.reload();}, 400); }
                        else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                    }, 'json');
                    return false;
                }},
                cancel: function () {}
            }
        });
    });
    <?php endif; ?>
})();
</script>

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