<?php $this->start('body');
    $a     = $this->data['asset'] ?? [];
    $nbv   = (float)$this->data['nbv'];
    $banks = $this->data['banks'] ?? [];
?>

<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-hand-holding-usd me-2" style="color:#7A8BA1;"></i>Dispose asset · <?= htmlspecialchars($a['asset_no']); ?></h5>
        <div class="text-muted small mt-1" style="color:#64748B;"><?= htmlspecialchars($a['name']); ?> · <?= htmlspecialchars((string)$a['category_name']); ?></div>
    </div>
    <a href="<?= PROOT; ?>Assets/view/<?= (int)$a['c0d']; ?>" class="btn btn-sm" style="background:#F8FAFC;border:1px solid #E2E8F0;color:#334155;"><i class="fas fa-arrow-left me-1"></i>Back to asset</a>
</div>

<div class="row g-3 mb-3">
    <div class="col-md-4"><div class="card border-0 shadow-sm h-100" style="background:#F8FAFC;"><div class="card-body p-3">
        <div style="text-transform:uppercase;letter-spacing:.4px;font-size:.66rem;color:#64748B;">Purchase cost</div>
        <div style="font-weight:700;font-size:1.3rem;color:#334155;">TZS <?= number_format((float)$a['purchase_cost']); ?></div>
    </div></div></div>
    <div class="col-md-4"><div class="card border-0 shadow-sm h-100" style="background:#F8FAFC;"><div class="card-body p-3">
        <div style="text-transform:uppercase;letter-spacing:.4px;font-size:.66rem;color:#64748B;">Accumulated depreciation</div>
        <div style="font-weight:700;font-size:1.3rem;color:#C48579;">− TZS <?= number_format((float)$a['accumulated_depreciation']); ?></div>
    </div></div></div>
    <div class="col-md-4"><div class="card border-0 shadow-sm h-100" style="border-left:4px solid #334155 !important;background:#F8FAFC;"><div class="card-body p-3">
        <div style="text-transform:uppercase;letter-spacing:.4px;font-size:.66rem;color:#64748B;">Net book value</div>
        <div style="font-weight:700;font-size:1.4rem;color:#334155;">TZS <?= number_format($nbv); ?></div>
    </div></div></div>
</div>

<div class="card border-0 shadow-sm" style="background:#F8FAFC;">
    <div class="card-header bg-white" style="border-bottom:1px solid #E2E8F0;">
        <strong style="color:#334155;">Disposal details</strong>
    </div>
    <div class="card-body p-3">
        <div class="row g-2">
            <div class="col-md-3">
                <label class="form-label" style="color:#334155;">Disposal date *</label>
                <input type="date" id="disposal_date" value="<?= date('Y-m-d'); ?>" class="form-control form-control-sm">
            </div>
            <div class="col-md-3">
                <label class="form-label" style="color:#334155;">Method *</label>
                <select id="disposal_method" class="form-select form-select-sm">
                    <option value="SALE">Sale</option>
                    <option value="SCRAP">Scrap</option>
                    <option value="DONATION">Donation</option>
                    <option value="WRITE_OFF">Write-off / Lost</option>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label" style="color:#334155;">Sale price (TZS)</label>
                <input type="number" step="0.01" id="sale_price" value="0" class="form-control form-control-sm">
            </div>
            <div class="col-md-3">
                <label class="form-label" style="color:#334155;">Sale-proceeds bank</label>
                <select id="bank_account_id" class="form-select form-select-sm">
                    <?php foreach ($banks as $b): ?>
                        <option value="<?= (int)$b['c0d']; ?>"><?= htmlspecialchars($b['account_code'] . ' — ' . $b['account_name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-6">
                <label class="form-label" style="color:#334155;">Buyer / recipient</label>
                <input type="text" id="buyer_name" class="form-control form-control-sm" placeholder="e.g. Auction House Ltd — leave blank if scrap/write-off">
            </div>
            <div class="col-md-6">
                <label class="form-label" style="color:#334155;">Notes</label>
                <input type="text" id="notes" class="form-control form-control-sm">
            </div>
        </div>

        <div id="gl_preview" class="mt-3 p-2" style="background:#F1F5F9;border-radius:4px;font-size:.86rem;color:#334155;">
            <i class="fas fa-info-circle me-1" style="color:#7A8BA1;"></i>
            <strong>Preview:</strong> <span id="gl_text">Enter a sale price to see gain/loss.</span>
        </div>
    </div>
    <div class="card-footer bg-white d-flex justify-content-end gap-2" style="border-top:1px solid #E2E8F0;">
        <a href="<?= PROOT; ?>Assets/view/<?= (int)$a['c0d']; ?>" class="btn btn-sm" style="background:#F8FAFC;border:1px solid #E2E8F0;color:#334155;">Cancel</a>
        <button type="button" id="btn_dispose" class="btn btn-sm" style="background:#C48579;border-color:#C48579;color:#fff;font-weight:600;"><i class="fas fa-hand-holding-usd me-1"></i>Post disposal</button>
    </div>
</div>

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

<?php $this->start('section_js'); ?>
<script>
$(function () {
    var PROOT = '<?= PROOT; ?>';
    var ASSET_ID = <?= (int)$a['c0d']; ?>;
    var NBV = <?= (float)$nbv; ?>;

    function updatePreview() {
        var method = $('#disposal_method').val();
        var sp = parseFloat($('#sale_price').val()) || 0;
        if (method !== 'SALE') sp = 0;
        var gl = sp - NBV;
        var glTxt;
        if (Math.abs(gl) < 0.01)      glTxt = '<span style="color:#334155;">Break-even (sale = NBV).</span>';
        else if (gl > 0)              glTxt = '<span style="color:#7A9E7E;font-weight:600;">Gain of TZS ' + gl.toLocaleString() + '</span> — will credit 7910 Gain on Disposal.';
        else                          glTxt = '<span style="color:#C48579;font-weight:600;">Loss of TZS ' + Math.abs(gl).toLocaleString() + '</span> — will debit 6910 Loss on Disposal.';
        $('#gl_text').html(glTxt);
    }
    $('#sale_price, #disposal_method').on('input change', updatePreview);
    $('#disposal_method').on('change', function () {
        if ($(this).val() !== 'SALE') { $('#sale_price').val(0).prop('disabled', true); $('#bank_account_id').prop('disabled', true); }
        else                          { $('#sale_price').prop('disabled', false);      $('#bank_account_id').prop('disabled', false); }
        updatePreview();
    });

    $('#btn_dispose').on('click', function () {
        $.confirm({
            title: 'Post disposal?',
            content: 'This creates a journal (Dr Bank / Dr Acc. Dep. / Cr Asset Cost / ±Gain-Loss), flips the asset to <strong>DISPOSED</strong>, and zeroes its book value. Cannot be undone.',
            type: 'orange',
            buttons: {
                yes: { text: 'Post disposal', btnClass: 'btn-warning', action: function () {
                    var $btn = $('#btn_dispose').prop('disabled', true).html('<i class="fas fa-spinner fa-spin me-1"></i>Posting…');
                    $.post(PROOT + 'Assets/disposeAj', {
                        asset_id:        ASSET_ID,
                        disposal_date:   $('#disposal_date').val(),
                        disposal_method: $('#disposal_method').val(),
                        sale_price:      $('#sale_price').val() || 0,
                        buyer_name:      $('#buyer_name').val(),
                        bank_account_id: $('#bank_account_id').val(),
                        notes:           $('#notes').val(),
                    }, 'json')
                    .done(function (res) {
                        if (res && res.ok) {
                            rsToast('Disposed. JE#' + res.je_id + ' posted. Gain/Loss TZS ' + Math.round(res.gain_or_loss).toLocaleString(), 'success', 3500);
                            setTimeout(function () { location.href = PROOT + 'Assets/view/' + ASSET_ID; }, 900);
                        } else {
                            rsToast('Disposal failed: ' + (res.msg || 'unknown'), 'error', 5000);
                            $btn.prop('disabled', false).html('<i class="fas fa-hand-holding-usd me-1"></i>Post disposal');
                        }
                    })
                    .fail(function () { rsToast('Server unreachable.', 'error'); $btn.prop('disabled', false).html('<i class="fas fa-hand-holding-usd me-1"></i>Post disposal'); });
                }},
                cancel: { text: 'Cancel', btnClass: 'btn-light' }
            }
        });
    });
});
</script>
<?php $this->end(); ?>
