<?php $this->start('body');
    $year    = (int)$this->v('year');
    $month   = (int)$this->v('month');
    $preview = $this->data['preview'] ?? [];
    $totalAmt = (float)($this->data['total_amount'] ?? 0);
?>

<div class="d-flex align-items-center justify-content-between mb-3">
    <div>
        <h5 class="mb-0" style="font-weight:600;color:#334155;"><i class="fas fa-calculator me-2" style="color:#7A8BA1;"></i>Run Monthly Depreciation</h5>
        <div class="text-muted small mt-1" style="color:#64748B;">Preview posts one JE per category (Dr Depreciation Expense · Cr Accumulated Depreciation) and updates each asset's book value.</div>
    </div>
    <a href="<?= PROOT; ?>Assets" class="btn btn-sm" style="background:#F8FAFC;border:1px solid #E2E8F0;color:#334155;"><i class="fas fa-arrow-left me-1"></i>Back to register</a>
</div>

<form method="get" action="<?= PROOT; ?>Assets/runDepreciation" class="card border-0 shadow-sm mb-3" style="background:#F8FAFC;">
    <div class="card-body p-2">
        <div class="row g-2 align-items-end">
            <div class="col-md-2"><label class="form-label" style="color:#334155;">Year</label>
                <input type="number" name="year" value="<?= $year; ?>" min="2000" max="2099" class="form-control form-control-sm"></div>
            <div class="col-md-3"><label class="form-label" style="color:#334155;">Month</label>
                <select name="month" class="form-select form-select-sm">
                    <?php for ($m = 1; $m <= 12; $m++): ?>
                        <option value="<?= $m; ?>" <?= $m === $month ? 'selected' : ''; ?>><?= sprintf('%02d', $m); ?> — <?= date('F', mktime(0,0,0,$m,1)); ?></option>
                    <?php endfor; ?>
                </select></div>
            <div class="col-md-7 text-end">
                <button type="submit" class="btn btn-sm" style="background:#7A8BA1;border-color:#7A8BA1;color:#fff;font-weight:600;"><i class="fas fa-eye me-1"></i>Preview period</button>
                <button type="button" id="btn_post" class="btn btn-sm" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;" <?= empty($preview) ? 'disabled' : ''; ?>><i class="fas fa-check me-1"></i>Post depreciation</button>
            </div>
        </div>
    </div>
</form>

<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 #E2E8F0;">
        <strong style="color:#334155;">Preview · <?= sprintf('%04d-%02d', $year, $month); ?></strong>
        <span class="text-muted small" style="color:#64748B;"><?= count($preview); ?> asset(s) · TZS <?= number_format($totalAmt); ?> total</span>
    </div>
    <div class="table-responsive">
        <table class="table table-sm mb-0 align-middle">
            <thead style="background:#F1F5F9;">
                <tr>
                    <th style="color:#334155;">Asset #</th>
                    <th style="color:#334155;">Name</th>
                    <th class="text-end" style="color:#334155;">Cost</th>
                    <th class="text-end" style="color:#334155;">Accumulated</th>
                    <th class="text-end" style="color:#334155;">Book value before</th>
                    <th class="text-end" style="color:#334155;">Depreciation</th>
                    <th class="text-end" style="color:#334155;">Book value after</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($preview as $p): ?>
                    <tr>
                        <td style="color:#334155;font-weight:500;"><?= htmlspecialchars($p['asset_no']); ?></td>
                        <td style="color:#334155;"><?= htmlspecialchars($p['name']); ?></td>
                        <td class="text-end" style="color:#334155;"><?= number_format((float)$p['cost']); ?></td>
                        <td class="text-end" style="color:#C48579;"><?= number_format((float)$p['accumulated']); ?></td>
                        <td class="text-end" style="color:#334155;"><?= number_format((float)$p['book_value_before']); ?></td>
                        <td class="text-end" style="font-weight:600;color:#C48579;">− <?= number_format((float)$p['depreciation_amount']); ?></td>
                        <td class="text-end" style="font-weight:600;color:#334155;"><?= number_format((float)$p['book_value_after']); ?></td>
                    </tr>
                <?php endforeach; ?>
                <?php if (empty($preview)): ?>
                    <tr><td colspan="7" class="text-center py-4" style="color:#94A3B8;">
                        Nothing to depreciate for <?= sprintf('%04d-%02d', $year, $month); ?>. Either no in-service assets started before period end, or this month was already posted.
                    </td></tr>
                <?php endif; ?>
            </tbody>
            <?php if (!empty($preview)): ?>
            <tfoot style="background:#E2E8F0;">
                <tr>
                    <td colspan="5" class="text-end" style="font-weight:700;color:#334155;">Total this period</td>
                    <td class="text-end" style="font-weight:700;color:#C48579;">− <?= number_format($totalAmt); ?></td>
                    <td></td>
                </tr>
            </tfoot>
            <?php endif; ?>
        </table>
    </div>
</div>

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

<?php $this->start('section_js'); ?>
<script>
$(function () {
    var PROOT = '<?= PROOT; ?>';
    $('#btn_post').on('click', function () {
        $.confirm({
            title: 'Post depreciation for <?= sprintf('%04d-%02d', $year, $month); ?>?',
            content: 'This will create one journal per category (Dr Depreciation Expense · Cr Accumulated Depreciation) totalling TZS <?= number_format($totalAmt); ?> and update each asset\'s book value. Cannot be re-posted for the same period.',
            type: 'green',
            buttons: {
                yes: { text: 'Post', btnClass: 'btn-success', action: function () {
                    var $btn = $('#btn_post').prop('disabled', true).html('<i class="fas fa-spinner fa-spin me-1"></i>Posting…');
                    $.post(PROOT + 'Assets/runDepreciationAj', { year: <?= $year; ?>, month: <?= $month; ?> }, 'json')
                        .done(function (res) {
                            if (res && res.ok) {
                                rsToast('Posted ' + res.line_count + ' line(s) across ' + res.je_ids.length + ' journal(s). Total TZS ' + Math.round(res.total_amount).toLocaleString(), 'success', 4000);
                                setTimeout(function () { location.reload(); }, 900);
                            } else {
                                rsToast('Post failed: ' + (res.msg || 'unknown'), 'error', 5000);
                                $btn.prop('disabled', false).html('<i class="fas fa-check me-1"></i>Post depreciation');
                            }
                        })
                        .fail(function () { rsToast('Server unreachable.', 'error'); $btn.prop('disabled', false).html('<i class="fas fa-check me-1"></i>Post depreciation'); });
                }},
                cancel: { text: 'Cancel', btnClass: 'btn-light' }
            }
        });
    });
});
</script>
<?php $this->end(); ?>
