<?php $this->start('body');
    $rows   = $this->data['rows']   ?? [];
    $status = (string)($this->data['status'] ?? '');
    $statuses = ['DRAFT','ACTIVE','SUSPENDED','EXPIRED','TERMINATED'];
    $chip = [
        'DRAFT'      => ['#F1F5F9','#334155','Draft'],
        'ACTIVE'     => ['#EAF2E8','#3F5C43','Active'],
        'SUSPENDED'  => ['#FEF3E7','#8B6914','Suspended'],
        'EXPIRED'    => ['#F5EAE1','#C48579','Expired'],
        'TERMINATED' => ['#F5EAE1','#C48579','Terminated'],
    ];
?>
<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-handshake me-2 text-muted"></i>Service Contracts
            <span class="text-muted ms-2" style="font-weight:400;font-size:.7rem;"><?= count($rows); ?> total</span>
        </h5>
    </div>
    <button type="button" class="btn btn-sm" id="btn_add" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;font-weight:600;"><i class="fas fa-plus me-1"></i>New contract</button>
</div>

<div class="mb-2 d-flex flex-wrap gap-1">
    <a href="<?= PROOT; ?>ServiceContracts" class="badge <?= $status===''?'bg-dark':'bg-light text-muted'; ?>" style="text-decoration:none;padding:.35em .6em;">All</a>
    <?php foreach ($statuses as $s): ?>
        <a href="<?= PROOT; ?>ServiceContracts?status=<?= $s; ?>" class="badge <?= $status===$s?'bg-dark':'bg-light text-muted'; ?>" style="text-decoration:none;padding:.35em .6em;text-transform:capitalize;">
            <?= htmlspecialchars(strtolower($s)); ?>
        </a>
    <?php endforeach; ?>
</div>

<div class="card border-0 shadow-sm">
    <div class="table-responsive">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light">
                <tr>
                    <th>Contract #</th><th>Project</th><th>Customer</th>
                    <th class="text-end">Value</th><th class="text-end">Monthly</th>
                    <th class="text-end">Sites</th><th class="text-end">Assets</th><th class="text-end">PMs</th>
                    <th>Cadence</th><th>Spare policy</th><th>Dates</th><th>Status</th><th></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($rows as $r):
                    $c = $chip[$r['status']] ?? ['#F1F5F9','#334155',$r['status']];
                ?>
                    <tr>
                        <td><a href="<?= PROOT; ?>ServiceContracts/view/<?= (int)$r['c0d']; ?>" class="text-decoration-none"><strong><?= htmlspecialchars($r['contract_no']); ?></strong></a></td>
                        <td class="small text-muted"><?= htmlspecialchars((string)($r['project_no'] ?? '—')); ?></td>
                        <td class="small"><?= htmlspecialchars((string)($r['customer_name'] ?? '')); ?></td>
                        <td class="text-end small" style="font-weight:600;color:#334155;"><?= htmlspecialchars((string)$r['currency']); ?> <?= number_format((float)$r['contract_value']); ?></td>
                        <td class="text-end small text-muted"><?= $r['monthly_retainer'] !== null ? number_format((float)$r['monthly_retainer']) : '—'; ?></td>
                        <td class="text-end small"><?= (int)$r['site_count']; ?></td>
                        <td class="text-end small"><?= (int)$r['asset_count']; ?></td>
                        <td class="text-end small"><?= (int)$r['pm_count']; ?></td>
                        <td class="small text-muted" style="text-transform:capitalize;"><?= htmlspecialchars(strtolower(str_replace('_',' ', (string)$r['invoice_cadence']))); ?></td>
                        <td class="small text-muted" style="text-transform:capitalize;"><?= htmlspecialchars(strtolower(str_replace('_',' ', (string)$r['spare_policy']))); ?></td>
                        <td class="small text-muted" style="font-size:.62rem;">
                            <?= htmlspecialchars((string)($r['start_date'] ?? '—')); ?>
                            <?php if (!empty($r['end_date'])): ?><br>→ <?= htmlspecialchars((string)$r['end_date']); ?><?php endif; ?>
                        </td>
                        <td><span class="badge" style="background:<?= $c[0]; ?>;color:<?= $c[1]; ?>;border:1px solid <?= $c[1]; ?>;font-size:.62rem;text-transform:capitalize;"><?= htmlspecialchars($c[2]); ?></span></td>
                        <td class="text-end"><a href="<?= PROOT; ?>ServiceContracts/view/<?= (int)$r['c0d']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-right"></i></a></td>
                    </tr>
                <?php endforeach; ?>
                <?php if (empty($rows)): ?>
                    <tr><td colspan="13" class="text-center text-muted py-4">No contracts yet.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
(function () {
    var PROOT = '<?= PROOT; ?>';
    document.getElementById('btn_add').addEventListener('click', function () {
        $.confirm({
            title:'New Service Contract', columnClass:'col-md-8', type:'green',
            content: '<form id="sc_form">' +
                '<div class="row g-2 mb-2">' +
                  '<div class="col-6"><label class="form-label small">Project ID *</label><input name="project_id" type="number" class="form-control form-control-sm" placeholder="c_projects.c0d" required></div>' +
                  '<div class="col-6"><label class="form-label small">Customer name</label><input name="customer_name" class="form-control form-control-sm"></div>' +
                '</div>' +
                '<div class="row g-2 mb-2">' +
                  '<div class="col-3"><label class="form-label small">Start date</label><input name="start_date" type="date" class="form-control form-control-sm"></div>' +
                  '<div class="col-3"><label class="form-label small">End date</label><input name="end_date" type="date" class="form-control form-control-sm"></div>' +
                  '<div class="col-3"><label class="form-label small">Contract value</label><input name="contract_value" type="number" step="0.01" min="0" class="form-control form-control-sm"></div>' +
                  '<div class="col-3"><label class="form-label small">Monthly retainer</label><input name="monthly_retainer" type="number" step="0.01" min="0" class="form-control form-control-sm"></div>' +
                '</div>' +
                '<div class="row g-2 mb-2">' +
                  '<div class="col-3"><label class="form-label small">Currency</label><input name="currency" class="form-control form-control-sm" value="TZS"></div>' +
                  '<div class="col-3"><label class="form-label small">Payment terms (days)</label><input name="payment_terms_days" type="number" min="0" class="form-control form-control-sm" value="30"></div>' +
                  '<div class="col-3"><label class="form-label small">Spare policy</label><select name="spare_policy" class="form-select form-select-sm"><option value="COMPANY">Company supplies</option><option value="CLIENT">Client supplies</option><option value="CONSIGNMENT">Consignment</option><option value="FIXED_PACK">Fixed pack</option></select></div>' +
                  '<div class="col-3"><label class="form-label small">Invoice cadence</label><select name="invoice_cadence" class="form-select form-select-sm"><option value="MONTHLY_RETAINER">Monthly retainer</option><option value="PER_EVENT">Per event</option><option value="MILESTONE">Milestone</option><option value="CONSUMPTION">Consumption</option></select></div>' +
                '</div>' +
                '<div class="row g-2 mb-2">' +
                  '<div class="col-3"><label class="form-label small">Labour rate/hr</label><input name="labour_rate_per_hr" type="number" step="0.01" min="0" class="form-control form-control-sm"></div>' +
                  '<div class="col-3"><label class="form-label small">Callout fee</label><input name="callout_fee" type="number" step="0.01" min="0" class="form-control form-control-sm"></div>' +
                  '<div class="col-3"><label class="form-label small">Emergency ×</label><input name="emergency_multiplier" type="number" step="0.01" min="1" class="form-control form-control-sm" value="2"></div>' +
                  '<div class="col-3"><label class="form-label small">Parts markup %</label><input name="parts_markup_pct" type="number" step="0.01" min="0" class="form-control form-control-sm" value="25"></div>' +
                '</div>' +
                '<div class="row g-2 mb-2">' +
                  '<div class="col-3"><label class="form-label small">Mileage / km</label><input name="mileage_rate_per_km" type="number" step="0.01" min="0" class="form-control form-control-sm"></div>' +
                  '<div class="col-3"><label class="form-label small">Free callouts/mo</label><input name="free_callouts_per_month" type="number" min="0" class="form-control form-control-sm" value="0"></div>' +
                  '<div class="col-6"><label class="form-label small">Report cadence</label><select name="report_cadence" class="form-select form-select-sm"><option value="MONTHLY">Monthly</option><option value="QUARTERLY">Quarterly</option><option value="SEMI_ANNUAL">Semi-annual</option><option value="ANNUAL">Annual</option><option value="NONE">None</option></select></div>' +
                '</div>' +
                '<div class="mb-2"><label class="form-label small">Notes</label><input name="notes" class="form-control form-control-sm"></div>' +
            '</form>',
            buttons: {
                save: { text:'Create', btnClass:'btn-success', action: function () {
                    var f = document.getElementById('sc_form');
                    var p = {};
                    ['project_id','customer_name','start_date','end_date','contract_value','currency','monthly_retainer','spare_policy','invoice_cadence','payment_terms_days','labour_rate_per_hr','callout_fee','emergency_multiplier','parts_markup_pct','mileage_rate_per_km','free_callouts_per_month','report_cadence','notes'].forEach(function (k) { p[k] = f[k].value; });
                    $.post(PROOT + 'ServiceContracts/saveHeaderAj', p, function (r) {
                        if (r && r.ok) { rsToast('Created.','success'); setTimeout(function(){window.location.href = PROOT + 'ServiceContracts/view/' + r.id;}, 500); }
                        else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                    }, 'json');
                }}, cancel: function () {}
            }
        });
    });
})();
</script>
<?php $this->end(); ?>
