<?php $this->start('body');
    $d = $this->data['defaults'] ?? [];
    $canWrite = UserGroups::can('PricingDefaults', 'saveAj');
?>
<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-sliders-h me-1" style="color:#7A8BA1;"></i>Pricing Defaults
        </h5>
        <div class="text-muted" style="font-size:.72rem;">Org-wide starting values applied to every new pricing draft. Editable by CRM, Finance Manager, Executive, Administrator.</div>
    </div>
</div>

<!-- Explanation card (matches the Tenders/view pricing tab tone) -->
<div class="card border-0 shadow-sm mb-3" style="background:#FDF7EC;border-left:3px solid #D4A574 !important;">
    <div class="card-body p-3" style="font-size:.82rem;color:#334155;">
        <div><strong style="color:#8B6914;"><i class="fas fa-lightbulb me-1"></i>How defaults apply</strong></div>
        <div class="mt-1" style="line-height:1.5;">
            When someone clicks <strong>"Start blank draft"</strong> or <strong>"Start draft &amp; seed from Items"</strong> on a tender, the new pricing version inherits these defaults. If they clone from an existing version, those numbers still win (that's the point of "clone from vN"). Once the version is created, per-version overrides live in the Version settings row on that tender's Pricing tab.
        </div>
        <div class="mt-2" style="font-size:.76rem;color:#64748B;">
            <i class="fas fa-info-circle me-1" style="color:#7A8BA1;"></i>
            Changing these values does <strong>not</strong> touch existing pricing versions — it only affects drafts created from now on.
        </div>
    </div>
</div>

<form id="pd_form" class="card border-0 shadow-sm">
    <div class="card-body p-3">
        <div class="row g-3">
            <div class="col-md-4">
                <label class="form-label" style="color:#334155;font-size:.78rem;font-weight:600;">Default markup %</label>
                <input type="number" step="0.001" min="0" max="500" id="pd_markup" class="form-control form-control-sm" value="<?= (float)($d['default_markup_pct'] ?? 20); ?>" <?= $canWrite ? '' : 'disabled'; ?>>
                <div class="small mt-1" style="color:#94A3B8;font-size:.68rem;">Sell price = cost × (1 + markup ÷ 100)</div>
            </div>
            <div class="col-md-4">
                <label class="form-label" style="color:#334155;font-size:.78rem;font-weight:600;">Default contingency %</label>
                <input type="number" step="0.001" min="0" max="500" id="pd_cont" class="form-control form-control-sm" value="<?= (float)($d['default_contingency_pct'] ?? 2); ?>" <?= $canWrite ? '' : 'disabled'; ?>>
                <div class="small mt-1" style="color:#94A3B8;font-size:.68rem;">Buffer on top of the priced BOQ.</div>
            </div>
            <div class="col-md-4">
                <label class="form-label" style="color:#334155;font-size:.78rem;font-weight:600;">Default VAT %</label>
                <input type="number" step="0.001" min="0" max="500" id="pd_vat" class="form-control form-control-sm" value="<?= (float)($d['default_vat_pct'] ?? 18); ?>" <?= $canWrite ? '' : 'disabled'; ?>>
                <div class="small mt-1" style="color:#94A3B8;font-size:.68rem;">Tanzanian standard rate is 18%.</div>
            </div>

            <div class="col-md-4">
                <label class="form-label" style="color:#334155;font-size:.78rem;font-weight:600;">Default prelims amount</label>
                <input type="number" step="0.01" min="0" id="pd_prelims" class="form-control form-control-sm" value="<?= (float)($d['default_prelims_amount'] ?? 0); ?>" <?= $canWrite ? '' : 'disabled'; ?>>
                <div class="small mt-1" style="color:#94A3B8;font-size:.68rem;">Fixed preliminaries added to sell total.</div>
            </div>
            <div class="col-md-4">
                <label class="form-label" style="color:#334155;font-size:.78rem;font-weight:600;">Default currency</label>
                <input type="text" maxlength="6" id="pd_currency" class="form-control form-control-sm" value="<?= htmlspecialchars((string)($d['default_currency'] ?? 'TZS')); ?>" style="text-transform:uppercase;" <?= $canWrite ? '' : 'disabled'; ?>>
                <div class="small mt-1" style="color:#94A3B8;font-size:.68rem;">ISO code, e.g. TZS, USD, KES.</div>
            </div>
            <div class="col-md-4">
                <label class="form-label" style="color:#334155;font-size:.78rem;font-weight:600;">Notes (internal)</label>
                <input type="text" maxlength="500" id="pd_notes" class="form-control form-control-sm" value="<?= htmlspecialchars((string)($d['notes'] ?? '')); ?>" <?= $canWrite ? '' : 'disabled'; ?>>
            </div>

            <div class="col-12 mt-2 pt-2" style="border-top:1px dashed #E2E8F0;">
                <div class="small mb-2" style="color:#8B6914;background:#FDF7EC;border-left:3px solid #D4A574;padding:.5rem .7rem;font-size:.76rem;">
                    <i class="fas fa-layer-group me-1"></i><strong>Goods pricing defaults</strong> — drives the auto-loaded overhead template on new Goods drafts, and what the client-facing Excel export shows.
                </div>
            </div>
            <div class="col-md-4">
                <label class="form-label" style="color:#334155;font-size:.78rem;font-weight:600;">Default procurement mode (Goods)</label>
                <select id="pd_proc_mode" class="form-select form-select-sm" <?= $canWrite ? '' : 'disabled'; ?>>
                    <?php $pm = (string)($d['default_procurement_mode'] ?? 'LOCAL'); ?>
                    <option value="LOCAL"  <?= $pm === 'LOCAL'  ? 'selected' : ''; ?>>Local purchase</option>
                    <option value="IMPORT" <?= $pm === 'IMPORT' ? 'selected' : ''; ?>>Import</option>
                    <option value="MIXED"  <?= $pm === 'MIXED'  ? 'selected' : ''; ?>>Mixed (local + import)</option>
                </select>
                <div class="small mt-1" style="color:#94A3B8;font-size:.68rem;">Sets which overhead quick-load template auto-runs on a new goods draft.</div>
            </div>
            <div class="col-md-4">
                <label class="form-label" style="color:#334155;font-size:.78rem;font-weight:600;">Default client BOQ visibility</label>
                <select id="pd_boq_vis" class="form-select form-select-sm" <?= $canWrite ? '' : 'disabled'; ?>>
                    <?php $bv = (string)($d['default_client_boq_visibility'] ?? 'ITEMS_AND_SECTIONS'); ?>
                    <option value="ITEMS_AND_SECTIONS" <?= $bv === 'ITEMS_AND_SECTIONS' ? 'selected' : ''; ?>>Sections + items (full BOQ)</option>
                    <option value="ITEMS_ONLY"         <?= $bv === 'ITEMS_ONLY'         ? 'selected' : ''; ?>>Items only (flat list)</option>
                    <option value="LUMPSUM_ONLY"       <?= $bv === 'LUMPSUM_ONLY'       ? 'selected' : ''; ?>>Lumpsum only (no BOQ)</option>
                </select>
                <div class="small mt-1" style="color:#94A3B8;font-size:.68rem;">Sets what the client-facing Excel export shows by default. Per-version override always available.</div>
            </div>
        </div>

        <?php if (!empty($d['edited_on'])): ?>
            <div class="mt-3 small" style="color:#64748B;font-size:.72rem;">
                <i class="fas fa-history me-1"></i>Last edited <?= htmlspecialchars((string)$d['edited_on']); ?><?= !empty($d['edited_by_name']) ? ' by ' . htmlspecialchars((string)$d['edited_by_name']) : ''; ?>
            </div>
        <?php endif; ?>
    </div>

    <?php if ($canWrite): ?>
    <div class="card-footer bg-white d-flex justify-content-end" style="border-top:1px solid #E2E8F0;">
        <button type="button" id="pd_save" class="btn btn-sm" style="background:#7A8BA1;border-color:#7A8BA1;color:#fff;font-weight:600;padding:.4rem 1.2rem;">
            <i class="fas fa-save me-1"></i>Save defaults
        </button>
    </div>
    <?php endif; ?>
</form>

<script>
$(document).ready(function () {
    $('#pd_save').on('click', function () {
        var $btn = $(this).prop('disabled', true).html('<i class="fas fa-spinner fa-spin me-1"></i>Saving…');
        $.post(PROOT + 'PricingDefaults/saveAj', {
            default_markup_pct:            $('#pd_markup').val()    || 0,
            default_contingency_pct:       $('#pd_cont').val()      || 0,
            default_vat_pct:               $('#pd_vat').val()       || 0,
            default_prelims_amount:        $('#pd_prelims').val()   || 0,
            default_currency:              $('#pd_currency').val()  || 'TZS',
            default_procurement_mode:      $('#pd_proc_mode').val() || 'LOCAL',
            default_client_boq_visibility: $('#pd_boq_vis').val()   || 'ITEMS_AND_SECTIONS',
            notes:                         $('#pd_notes').val()     || '',
        }, null, 'json')
        .done(function (res) {
            if (res && res.ok) { rsToast('Defaults saved. Reloading…', 'success'); setTimeout(function () { location.reload(); }, 500); }
            else               { rsToast('Save failed: ' + (res && res.msg || 'unknown'), 'error', 5000); }
        })
        .fail(function () { rsToast('Network error saving defaults.', 'error'); })
        .always(function () { $btn.prop('disabled', false).html('<i class="fas fa-save me-1"></i>Save defaults'); });
    });
});
</script>
<?php $this->end(); ?>
