<?php $this->start('body');
    $types      = $this->data['types'] ?? [];
    $projects   = $this->data['projects'] ?? [];
    $cats       = $this->data['categories'] ?? [];
    $req        = $this->data['requestable'] ?? [];
    $preType    = (string)($this->data['pre_type'] ?? 'PETTY_CASH');
    $prePid     = (int)($this->data['pre_project_id'] ?? 0);
    $threshold  = (float)($this->data['threshold'] ?? 500000);
?>

<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-hand-holding-usd me-2 text-muted"></i>New cash request</h5>
        <div class="text-muted small mt-1" style="font-size:.72rem;">
            Draft any internal cash request. Approval routes by amount: <strong>≤ TZS <?= number_format($threshold); ?></strong> = PM → FM; above that = PM → FM → Exec.
        </div>
    </div>
    <a href="<?= PROOT; ?>CashRequests/my" class="btn btn-sm" style="background:#F8FAFC;border:1px solid #E2E8F0;color:#334155;">
        <i class="fas fa-list me-1" style="color:#7A8BA1;"></i>My requests
    </a>
</div>

<div class="card border-0 shadow-sm mb-3">
    <div class="card-body p-3" style="background:#F8FAFC;">
        <form id="crForm" onsubmit="return false;">
            <div class="row g-2 mb-2">
                <div class="col-md-3">
                    <label class="form-label" style="font-size:.72rem;color:#334155;font-weight:600;">Type</label>
                    <select id="cr_type" class="form-select form-select-sm">
                        <?php foreach ($req as $k):
                            $lbl = $types[$k]['label'] ?? $k;
                            $ico = $types[$k]['icon']  ?? 'fas fa-hand-holding-usd';
                        ?>
                            <option value="<?= $k; ?>" <?= $k === $preType ? 'selected' : ''; ?>><?= htmlspecialchars($lbl); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-5">
                    <label class="form-label" style="font-size:.72rem;color:#334155;font-weight:600;">Project <span class="text-muted" style="font-weight:400;">(optional)</span></label>
                    <select id="cr_project" class="form-select form-select-sm">
                        <option value="0">— No project / central —</option>
                        <?php foreach ($projects as $p): ?>
                            <option value="<?= (int)$p['c0d']; ?>" <?= (int)$p['c0d'] === $prePid ? 'selected' : ''; ?>>
                                <?= htmlspecialchars($p['project_no']); ?> · <?= htmlspecialchars($p['project_name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label" style="font-size:.72rem;color:#334155;font-weight:600;">Amount <span style="color:#C48579;">*</span></label>
                    <input type="number" step="0.01" min="0" id="cr_amount" class="form-control form-control-sm" placeholder="0">
                    <div id="cr_route_hint" class="small mt-1" style="font-size:.62rem;color:#94A3B8;">
                        Route: <strong id="cr_route">PM → FM</strong>
                    </div>
                </div>
                <div class="col-md-2">
                    <label class="form-label" style="font-size:.72rem;color:#334155;font-weight:600;">Currency</label>
                    <select id="cr_currency" class="form-select form-select-sm">
                        <option value="TZS">TZS</option>
                        <option value="USD">USD</option>
                        <option value="EUR">EUR</option>
                    </select>
                </div>
            </div>

            <div class="row g-2 mb-2">
                <div class="col-md-8">
                    <label class="form-label" style="font-size:.72rem;color:#334155;font-weight:600;">Purpose <span style="color:#C48579;">*</span></label>
                    <input type="text" id="cr_purpose" class="form-control form-control-sm" placeholder="e.g. Sample purchase for hospital equipment tender (5 supplier samples)">
                </div>
                <div class="col-md-4">
                    <label class="form-label" style="font-size:.72rem;color:#334155;font-weight:600;">Budget category</label>
                    <select id="cr_budget_cat" class="form-select form-select-sm">
                        <option value="0">— None —</option>
                        <?php foreach ($cats as $c): ?>
                            <option value="<?= (int)$c['c0d']; ?>"><?= htmlspecialchars($c['category_name']); ?><?= $c['category_code'] ? ' · ' . htmlspecialchars($c['category_code']) : ''; ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>

            <!-- Slice 8Z-k · payment preference (optional — Accountant confirms at Prepare step) -->
            <div class="row g-2 mb-2">
                <div class="col-md-4">
                    <label class="form-label" style="font-size:.72rem;color:#334155;font-weight:600;">Preferred payment method <span class="text-muted" style="font-weight:400;">(optional)</span></label>
                    <select id="cr_method" class="form-select form-select-sm">
                        <option value="">— Accountant decides —</option>
                        <option value="MOBILE_MONEY">Mobile money</option>
                        <option value="BANK_TRANSFER">Bank transfer</option>
                        <option value="PETTY_CASH">Petty cash</option>
                        <option value="CASH_HANDOVER">Cash handover (last resort)</option>
                        <option value="CHEQUE">Cheque</option>
                    </select>
                </div>
                <div class="col-md-8">
                    <label class="form-label" style="font-size:.72rem;color:#334155;font-weight:600;">Preferred destination <span class="text-muted" style="font-weight:400;">(optional · <a href="<?= PROOT; ?>PayeeAccounts/my" target="_blank" style="color:#7A9E7E;">register one</a> if missing)</span></label>
                    <select id="cr_account" class="form-select form-select-sm">
                        <option value="">— none · Accountant picks —</option>
                    </select>
                    <div class="text-muted" style="font-size:.62rem;">Only your <strong>approved</strong> and <strong>pending</strong> destinations show. Ad-hoc use of pending accounts requires Accountant reason.</div>
                </div>
            </div>

            <div class="alert py-2 mb-2 small" style="background:#EEF2F6;border:1px solid #7A8BA1;color:#334155;font-size:.72rem;">
                <i class="fas fa-info-circle me-1"></i>
                Payee defaults to you (<?= htmlspecialchars($_SESSION['full_name'] ?? ''); ?>). Accountant will confirm the disbursement plan at the Prepare step — they can accept your preference or override with a mandatory reason.
            </div>

            <div class="text-end">
                <button type="button" id="btn_submit_cr" class="btn btn-sm" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;">
                    <i class="fas fa-paper-plane me-1"></i>Submit for approval
                </button>
            </div>
        </form>
    </div>
</div>

<script>
(function () {
    var $amt = document.getElementById('cr_amount');
    var $route = document.getElementById('cr_route');
    var threshold = <?= (float)$threshold; ?>;
    function refreshRoute() {
        var v = parseFloat($amt.value || 0);
        $route.textContent = (v > threshold) ? 'PM → Accountant → FM → Exec (Large)' : 'PM → Accountant → FM (Standard)';
    }
    $amt.addEventListener('input', refreshRoute); refreshRoute();

    // Slice 8Z-k · load requester's approved + pending accounts into the destination picker
    (function loadAccounts() {
        $.get('<?= PROOT; ?>PayeeAccounts/listAj?payee_type=STAFF', function (r) {
            if (!r || !r.ok || !r.rows) return;
            var sel = document.getElementById('cr_account');
            r.rows.forEach(function (a) {
                var label = a.provider_name + ' · ' + a.account_masked + ' · ' + a.holder_name +
                            (a.status === 'PENDING' ? '  [pending FM]' : '');
                var opt = document.createElement('option');
                opt.value = a.id;
                opt.textContent = label;
                if (a.is_default) opt.selected = true;
                sel.appendChild(opt);
            });
        }, 'json');
    })();

    document.getElementById('btn_submit_cr').addEventListener('click', function () {
        var payload = {
            lpo_type:             document.getElementById('cr_type').value,
            project_id:           document.getElementById('cr_project').value,
            amount:               $amt.value,
            currency:             document.getElementById('cr_currency').value,
            purpose:              document.getElementById('cr_purpose').value.trim(),
            budget_category_id:   document.getElementById('cr_budget_cat').value,
            preferred_method:     document.getElementById('cr_method').value,
            preferred_account_id: document.getElementById('cr_account').value
        };
        if (!payload.purpose)   { $.alert({title:'Purpose required', content:'Explain what the cash is for.', type:'orange'}); return; }
        if (!(parseFloat(payload.amount) > 0)) { $.alert({title:'Amount required', content:'Enter a positive amount.', type:'orange'}); return; }
        $.confirm({
            title: 'Submit cash request?',
            content: 'The request goes to PM first, then FM' + (parseFloat(payload.amount) > threshold ? ', then Exec.' : '.'),
            type: 'green',
            buttons: {
                confirm: { text: 'Submit', btnClass: 'btn-success', action: function () {
                    $.post('<?= PROOT; ?>CashRequests/saveAj', payload, function (r) {
                        if (r && r.ok) {
                            rsToast('Submitted.', 'success');
                            setTimeout(function () { window.location.href = '<?= PROOT; ?>Lpos/view/' + r.id; }, 500);
                        } else {
                            $.alert({title:'Could not submit', content:(r && r.msg) || 'Server error', type:'red'});
                        }
                    }, 'json').fail(function () { $.alert({title:'Network error', content:'Try again', type:'red'}); });
                }},
                cancel: function () {}
            }
        });
    });
})();
</script>

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