<?php $this->start('body');
    $c        = $this->data['contract'];
    $sites    = $this->data['sites']    ?? [];
    $assets   = $this->data['assets']   ?? [];
    $slas     = $this->data['slas']     ?? [];
    $schedule = $this->data['schedule'] ?? [];
    $types    = $this->data['asset_types'] ?? [];
    $cats     = $this->data['categories']  ?? [];
    $canEdit  = !empty($this->data['can_edit']);
    $canAct   = !empty($this->data['can_activate']);
    $chip = [
        'DRAFT'      => ['#F1F5F9','#334155','Draft'],
        'ACTIVE'     => ['#EAF2E8','#3F5C43','Active'],
        'SUSPENDED'  => ['#FEF3E7','#8B6914','Suspended'],
        'EXPIRED'    => ['#F5EAE1','#C48579','Expired'],
        'TERMINATED' => ['#F5EAE1','#C48579','Terminated'],
    ];
    $sc = $chip[$c['status']] ?? ['#F1F5F9','#334155',$c['status']];
?>
<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><?= htmlspecialchars($c['contract_no']); ?></h5>
        <div class="text-muted small mt-1" style="font-size:.72rem;">
            <?= htmlspecialchars((string)($c['customer_name'] ?? '')); ?>
            <?php if (!empty($c['project_no'])): ?> &middot; <?= htmlspecialchars($c['project_no']); ?><?php endif; ?>
            &middot; <?= htmlspecialchars((string)$c['currency']); ?> <?= number_format((float)$c['contract_value']); ?>
            <?php if (!empty($c['start_date'])): ?> &middot; <?= htmlspecialchars((string)$c['start_date']); ?> → <?= htmlspecialchars((string)($c['end_date'] ?? '')); ?><?php endif; ?>
        </div>
    </div>
    <div class="d-flex gap-2 align-items-center">
        <span class="badge" style="background:<?= $sc[0]; ?>;color:<?= $sc[1]; ?>;border:1px solid <?= $sc[1]; ?>;font-weight:600;text-transform:capitalize;padding:.4rem .55rem;font-size:.7rem;"><?= htmlspecialchars($sc[2]); ?></span>
        <?php if ($canAct): ?><button type="button" id="btn_activate" class="btn btn-sm" style="background:#3F5C43;border-color:#3F5C43;color:#fff;font-weight:600;"><i class="fas fa-play me-1"></i>Activate</button><?php endif; ?>
        <a href="<?= PROOT; ?>ServiceContracts" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i>Back</a>
    </div>
</div>

<div class="row g-2 mb-3">
    <div class="col"><div class="card border-0 shadow-sm"><div class="card-body p-2 text-center">
        <div class="text-muted small" style="font-size:.62rem;text-transform:capitalize;">Spare policy</div>
        <div style="font-weight:600;text-transform:capitalize;font-size:.85rem;color:#334155;"><?= htmlspecialchars(strtolower(str_replace('_',' ', $c['spare_policy']))); ?></div>
    </div></div></div>
    <div class="col"><div class="card border-0 shadow-sm"><div class="card-body p-2 text-center">
        <div class="text-muted small" style="font-size:.62rem;text-transform:capitalize;">Invoice cadence</div>
        <div style="font-weight:600;text-transform:capitalize;font-size:.85rem;color:#334155;"><?= htmlspecialchars(strtolower(str_replace('_',' ', $c['invoice_cadence']))); ?></div>
    </div></div></div>
    <div class="col"><div class="card border-0 shadow-sm"><div class="card-body p-2 text-center">
        <div class="text-muted small" style="font-size:.62rem;text-transform:capitalize;">Monthly retainer</div>
        <div style="font-weight:600;font-size:.85rem;color:#3F5C43;"><?= $c['monthly_retainer'] !== null ? htmlspecialchars((string)$c['currency']) . ' ' . number_format((float)$c['monthly_retainer']) : '—'; ?></div>
    </div></div></div>
    <div class="col"><div class="card border-0 shadow-sm"><div class="card-body p-2 text-center">
        <div class="text-muted small" style="font-size:.62rem;text-transform:capitalize;">Callout fee</div>
        <div style="font-weight:600;font-size:.85rem;color:#334155;"><?= $c['callout_fee'] !== null ? number_format((float)$c['callout_fee']) : '—'; ?></div>
    </div></div></div>
    <div class="col"><div class="card border-0 shadow-sm"><div class="card-body p-2 text-center">
        <div class="text-muted small" style="font-size:.62rem;text-transform:capitalize;">Parts markup</div>
        <div style="font-weight:600;font-size:.85rem;color:#334155;"><?= $c['parts_markup_pct'] !== null ? number_format((float)$c['parts_markup_pct'], 1) . '%' : '—'; ?></div>
    </div></div></div>
    <div class="col"><div class="card border-0 shadow-sm"><div class="card-body p-2 text-center">
        <div class="text-muted small" style="font-size:.62rem;text-transform:capitalize;">Labour rate/hr</div>
        <div style="font-weight:600;font-size:.85rem;color:#334155;"><?= $c['labour_rate_per_hr'] !== null ? number_format((float)$c['labour_rate_per_hr']) : '—'; ?></div>
    </div></div></div>
</div>

<?php
    $canBill = !empty($this->data['can_bill']);
    $billing = $this->data['billing_history'] ?? [];
?>
<ul class="nav nav-tabs mb-3" style="font-size:.85rem;">
    <li class="nav-item"><a class="nav-link active" data-bs-toggle="tab" href="#tab_sites">Sites (<?= count($sites); ?>)</a></li>
    <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tab_assets">Assets (<?= count($assets); ?>)</a></li>
    <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tab_slas">SLA overrides (<?= count($slas); ?>)</a></li>
    <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tab_schedule">PM schedule (<?= count($schedule); ?>)</a></li>
    <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tab_billing">Billing (<?= count($billing); ?>)</a></li>
</ul>

<div class="tab-content">
    <!-- SITES ─────────────────────────────────────────────────────────── -->
    <div class="tab-pane show active" id="tab_sites">
        <?php if ($canEdit): ?>
            <div class="d-flex justify-content-end mb-2"><button type="button" class="btn btn-sm" id="btn_add_site" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;"><i class="fas fa-plus me-1"></i>Add site</button></div>
        <?php endif; ?>
        <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>Site code</th><th>Name</th><th>Region/District</th><th>Contact</th><th class="text-end">Assets</th><th></th></tr></thead>
                    <tbody>
                        <?php foreach ($sites as $s): ?>
                            <tr data-id="<?= (int)$s['c0d']; ?>" data-json='<?= htmlspecialchars(json_encode($s), ENT_QUOTES); ?>'>
                                <td class="small"><code><?= htmlspecialchars((string)($s['site_code'] ?? '')); ?></code></td>
                                <td class="small"><strong><?= htmlspecialchars($s['name']); ?></strong><?php if (!empty($s['physical_address'])): ?><div class="text-muted" style="font-size:.6rem;"><?= htmlspecialchars(mb_strimwidth((string)$s['physical_address'], 0, 80, '…')); ?></div><?php endif; ?></td>
                                <td class="small text-muted"><?= htmlspecialchars(trim(($s['region'] ?? '') . ' · ' . ($s['district'] ?? ''), ' ·')); ?></td>
                                <td class="small text-muted"><?= htmlspecialchars((string)($s['site_contact_name'] ?? '')); ?><?php if (!empty($s['site_contact_phone'])): ?><div style="font-size:.6rem;"><?= htmlspecialchars((string)$s['site_contact_phone']); ?></div><?php endif; ?></td>
                                <td class="text-end small"><?= (int)$s['asset_count']; ?></td>
                                <td class="text-end">
                                    <?php if ($canEdit): ?>
                                        <button type="button" class="btn btn-sm btn-link p-0 me-2 site_edit"><i class="fas fa-pen" style="color:#7A8BA1;"></i></button>
                                        <button type="button" class="btn btn-sm btn-link p-0 site_del text-danger"><i class="fas fa-times"></i></button>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if (empty($sites)): ?><tr><td colspan="6" class="text-center text-muted py-4">No sites yet.</td></tr><?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- ASSETS ────────────────────────────────────────────────────────── -->
    <div class="tab-pane" id="tab_assets">
        <?php if ($canEdit): ?>
            <div class="d-flex justify-content-end mb-2"><button type="button" class="btn btn-sm" id="btn_add_asset" style="background:#7A9E7E;border-color:#7A9E7E;color:#fff;" <?= empty($sites) ? 'disabled title="Add a site first"' : ''; ?>><i class="fas fa-plus me-1"></i>Add asset</button></div>
        <?php endif; ?>
        <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>Site</th><th>Type</th><th>Asset #</th><th>Make/Model</th><th class="text-end">Size</th><th>Serial</th><th>Install</th><th></th></tr></thead>
                    <tbody>
                        <?php foreach ($assets as $a): ?>
                            <tr data-id="<?= (int)$a['c0d']; ?>" data-json='<?= htmlspecialchars(json_encode($a), ENT_QUOTES); ?>'>
                                <td class="small"><?= htmlspecialchars((string)$a['site_name']); ?></td>
                                <td class="small text-muted"><?php if (!empty($a['asset_icon'])): ?><i class="fas <?= htmlspecialchars($a['asset_icon']); ?> me-1"></i><?php endif; ?><?= htmlspecialchars((string)$a['asset_type_code']); ?></td>
                                <td class="small"><strong><?= htmlspecialchars((string)($a['asset_no'] ?? '')); ?></strong></td>
                                <td class="small text-muted"><?= htmlspecialchars(trim(($a['make'] ?? '') . ' ' . ($a['model'] ?? ''))); ?></td>
                                <td class="text-end small"><?= $a['size_value'] !== null ? number_format((float)$a['size_value']) . ' ' . htmlspecialchars((string)$a['size_unit']) : '—'; ?></td>
                                <td class="small text-muted"><?= htmlspecialchars((string)($a['serial_no'] ?? '—')); ?></td>
                                <td class="small text-muted"><?= htmlspecialchars((string)($a['install_date'] ?? '—')); ?></td>
                                <td class="text-end">
                                    <?php if ($canEdit): ?>
                                        <button type="button" class="btn btn-sm btn-link p-0 me-2 asset_edit"><i class="fas fa-pen" style="color:#7A8BA1;"></i></button>
                                        <button type="button" class="btn btn-sm btn-link p-0 asset_del text-danger"><i class="fas fa-times"></i></button>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if (empty($assets)): ?><tr><td colspan="8" class="text-center text-muted py-4">No assets yet.</td></tr><?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- SLAs ──────────────────────────────────────────────────────────── -->
    <div class="tab-pane" id="tab_slas">
        <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>Category</th><th class="text-end">Response SLA</th><th class="text-end">Restore SLA</th><th class="text-end">Penalty %/hr</th><th>Notes</th><?php if ($canEdit): ?><th></th><?php endif; ?></tr></thead>
                    <tbody>
                        <?php foreach ($cats as $ct):
                            $override = null;
                            foreach ($slas as $s) if ((int)$s['category_id'] === (int)$ct['c0d']) { $override = $s; break; }
                        ?>
                            <tr data-cat-id="<?= (int)$ct['c0d']; ?>">
                                <td class="small"><strong><?= htmlspecialchars($ct['code']); ?></strong> <span class="text-muted"><?= htmlspecialchars($ct['name']); ?></span></td>
                                <td class="text-end small">
                                    <?php if ($override): ?>
                                        <strong><?= (int)$override['sla_response_hrs']; ?>h</strong>
                                        <div class="text-muted" style="font-size:.6rem;">default <?= (int)$ct['sla_response_hrs']; ?>h</div>
                                    <?php else: ?>
                                        <span class="text-muted"><?= (int)$ct['sla_response_hrs']; ?>h (default)</span>
                                    <?php endif; ?>
                                </td>
                                <td class="text-end small">
                                    <?php if ($override): ?>
                                        <strong><?= (int)$override['sla_restoration_hrs']; ?>h</strong>
                                        <div class="text-muted" style="font-size:.6rem;">default <?= (int)$ct['sla_restoration_hrs']; ?>h</div>
                                    <?php else: ?>
                                        <span class="text-muted"><?= (int)$ct['sla_restoration_hrs']; ?>h (default)</span>
                                    <?php endif; ?>
                                </td>
                                <td class="text-end small"><?= $override && $override['penalty_pct_per_hr'] !== null ? number_format((float)$override['penalty_pct_per_hr'], 2) . '%' : '—'; ?></td>
                                <td class="small text-muted"><?= $override ? htmlspecialchars((string)($override['notes'] ?? '')) : ''; ?></td>
                                <?php if ($canEdit): ?><td class="text-end"><button type="button" class="btn btn-sm btn-link p-0 sla_edit"><i class="fas fa-pen" style="color:#7A8BA1;"></i></button></td><?php endif; ?>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- SCHEDULE ──────────────────────────────────────────────────────── -->
    <div class="tab-pane" id="tab_schedule">
        <?php if ($canEdit): ?>
            <div class="d-flex justify-content-end mb-2">
                <button type="button" class="btn btn-sm" id="btn_gen_schedule" style="background:#8B6914;border-color:#8B6914;color:#fff;font-weight:600;" <?= empty($assets) ? 'disabled title="Add assets first"' : ''; ?>><i class="fas fa-sync me-1"></i>Regenerate schedule</button>
            </div>
        <?php endif; ?>
        <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>Next due</th><th>Site · Asset</th><th>Type</th><th>Template</th><th>Interval</th></tr></thead>
                    <tbody>
                        <?php foreach ($schedule as $s):
                            $due = $s['next_due_on'];
                            $days = $due ? (int)floor((strtotime($due) - strtotime(date('Y-m-d'))) / 86400) : null;
                        ?>
                            <tr>
                                <td class="small">
                                    <?= htmlspecialchars((string)($due ?? '— hours-based —')); ?>
                                    <?php if ($days !== null): ?>
                                        <?php $col = $days < 0 ? '#C48579' : ($days <= 7 ? '#8B6914' : '#3F5C43'); ?>
                                        <div style="font-size:.6rem;color:<?= $col; ?>;font-weight:600;"><?= $days < 0 ? abs($days) . 'd overdue' : ($days === 0 ? 'today' : 'in ' . $days . 'd'); ?></div>
                                    <?php endif; ?>
                                </td>
                                <td class="small"><?= htmlspecialchars((string)$s['site_name']); ?> · <strong><?= htmlspecialchars((string)$s['asset_no']); ?></strong></td>
                                <td class="small text-muted"><?php if (!empty($s['asset_icon'])): ?><i class="fas <?= htmlspecialchars($s['asset_icon']); ?> me-1"></i><?php endif; ?><?= htmlspecialchars((string)$s['asset_type_code']); ?></td>
                                <td class="small"><strong><?= htmlspecialchars((string)$s['template_code']); ?></strong> <span class="text-muted">v<?= (int)$s['template_version']; ?></span><div class="text-muted" style="font-size:.6rem;"><?= htmlspecialchars((string)$s['template_name']); ?></div></td>
                                <td class="small text-muted"><?= $s['interval_months'] ? (int)$s['interval_months'] . ' months' : ($s['interval_hrs'] ? (int)$s['interval_hrs'] . ' hrs run' : '—'); ?></td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if (empty($schedule)): ?><tr><td colspan="5" class="text-center text-muted py-4">No PM schedule yet — click <strong>Regenerate schedule</strong>.</td></tr><?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- BILLING (Slice 8S-5) ─────────────────────────────────────────── -->
    <div class="tab-pane" id="tab_billing">
        <?php
            $invChip = [
                'DRAFT'      => ['#F1F5F9','#334155','Draft'],
                'PM_REVIEW'  => ['#EEF2F6','#7A8BA1','PM review'],
                'READY_TO_ISSUE' => ['#FEF3E7','#8B6914','Ready'],
                'ISSUED'     => ['#EAF2E8','#3F5C43','Issued'],
                'PART_PAID'  => ['#FEF3E7','#8B6914','Partly paid'],
                'OVERDUE'    => ['#F5EAE1','#C48579','Overdue'],
                'PAID'       => ['#EAF2E8','#3F5C43','Paid'],
                'PAID_LATE'  => ['#FEF3E7','#8B6914','Paid late'],
                'CREDITED'   => ['#EEF2F6','#7A8BA1','Credited'],
                'WRITTEN_OFF'=> ['#F5EAE1','#C48579','Write-off'],
            ];
        ?>
        <?php if ($canBill): ?>
        <div class="d-flex justify-content-between align-items-center mb-2">
            <div class="text-muted small" style="font-size:.72rem;">
                Cadence: <strong style="text-transform:capitalize;color:#334155;"><?= htmlspecialchars(strtolower(str_replace('_',' ', $c['invoice_cadence']))); ?></strong>
                <?php if ($c['invoice_cadence'] === 'CONSUMPTION' || $c['invoice_cadence'] === 'MONTHLY_RETAINER'): ?>
                    &middot; Calculator: retainer + callouts + labour + mileage + parts (with markup <?= number_format((float)$c['parts_markup_pct'], 1); ?>%)
                <?php endif; ?>
            </div>
            <div class="d-flex align-items-center gap-2">
                <select id="bill_period" class="form-select form-select-sm" style="width:auto;">
                    <?php
                        // Last 12 months
                        for ($i = 0; $i < 12; $i++) {
                            $t = strtotime('first day of ' . ($i === 0 ? 'this' : '-' . $i . ' months'));
                            $y = date('Y', $t); $m = date('n', $t);
                            $lbl = date('F Y', $t);
                            printf('<option value="%s-%s"%s>%s</option>' . "\n",
                                $y, $m, $i === 1 ? ' selected' : '', htmlspecialchars($lbl));
                        }
                    ?>
                </select>
                <button type="button" id="btn_preview" class="btn btn-sm btn-outline-secondary"><i class="fas fa-calculator me-1"></i>Preview</button>
                <button type="button" id="btn_report"  class="btn btn-sm" style="background:#7A8BA1;border-color:#7A8BA1;color:#fff;font-weight:600;"><i class="fas fa-file-pdf me-1"></i>Download PDF report</button>
                <button type="button" id="btn_draft"   class="btn btn-sm" style="background:#3F5C43;border-color:#3F5C43;color:#fff;font-weight:600;"><i class="fas fa-file-invoice me-1"></i>Draft invoice</button>
            </div>
        </div>
        <?php endif; ?>

        <div class="card border-0 shadow-sm">
            <div class="card-header py-2" style="background:#F8FAFC;font-weight:600;color:#334155;font-size:.85rem;">
                <i class="fas fa-history me-1 text-muted"></i>Invoice history (recent 24)
            </div>
            <div class="table-responsive">
                <table class="table table-sm mb-0 align-middle">
                    <thead class="table-light"><tr><th>Invoice #</th><th>Date</th><th>Due</th><th class="text-end">Total</th><th class="text-end">Paid</th><th class="text-end">Outstanding</th><th>Drafted by</th><th>Status</th><th></th></tr></thead>
                    <tbody>
                        <?php foreach ($billing as $b):
                            $ic = $invChip[$b['invoice_workflow_status']] ?? ['#F1F5F9','#334155',$b['invoice_workflow_status']];
                        ?>
                            <tr>
                                <td class="small"><a href="<?= PROOT; ?>Sales/view/<?= (int)$b['c0d']; ?>" class="text-decoration-none"><strong><?= htmlspecialchars((string)($b['sale_no'] ?: '—')); ?></strong></a></td>
                                <td class="small text-muted"><?= htmlspecialchars((string)$b['invoice_date']); ?></td>
                                <td class="small text-muted"><?= htmlspecialchars((string)($b['due_date'] ?? '—')); ?></td>
                                <td class="text-end small" style="font-weight:600;color:#334155;"><?= number_format((float)$b['total']); ?></td>
                                <td class="text-end small text-muted"><?= number_format((float)$b['amount_paid'] + (float)$b['wht_settled_amount']); ?></td>
                                <td class="text-end small" style="font-weight:600;color:<?= (float)$b['outstanding_amount'] > 0 ? '#8B6914' : '#3F5C43'; ?>;"><?= number_format((float)$b['outstanding_amount']); ?></td>
                                <td class="small text-muted"><?= htmlspecialchars((string)$b['drafted_by_name']); ?></td>
                                <td><span class="badge" style="background:<?= $ic[0]; ?>;color:<?= $ic[1]; ?>;border:1px solid <?= $ic[1]; ?>;font-size:.62rem;text-transform:capitalize;"><?= htmlspecialchars($ic[2]); ?></span></td>
                                <td class="text-end"><a href="<?= PROOT; ?>Sales/view/<?= (int)$b['c0d']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-right"></i></a></td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if (empty($billing)): ?>
                            <tr><td colspan="9" class="text-center text-muted py-4">No invoices yet.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script>
(function () {
    var CID    = <?= (int)$c['c0d']; ?>;
    var PROOT  = '<?= PROOT; ?>';
    var SITES  = <?= json_encode(array_map(fn($s) => ['c0d'=>(int)$s['c0d'],'name'=>$s['name']], $sites)); ?>;
    var TYPES  = <?= json_encode(array_map(fn($t) => ['c0d'=>(int)$t['c0d'],'code'=>$t['code'],'name'=>$t['name']], $types)); ?>;
    var CATS   = <?= json_encode(array_map(fn($c2) => ['c0d'=>(int)$c2['c0d'],'code'=>$c2['code'],'name'=>$c2['name'],'default_response'=>$c2['sla_response_hrs'],'default_restore'=>$c2['sla_restoration_hrs']], $cats)); ?>;
    var SLAS_BY_CAT = <?= json_encode(array_reduce($slas, fn($acc, $s) => $acc + [(int)$s['category_id'] => $s], [])); ?>;

    function esc(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { return ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]); }); }

    // Activate
    var actB = document.getElementById('btn_activate');
    if (actB) actB.addEventListener('click', function () {
        $.confirm({ title:'Activate contract?', type:'green', content:'Contract will flip DRAFT → ACTIVE.', buttons: {
            yes: { text:'Activate', btnClass:'btn-success', action: function () {
                $.post(PROOT + 'ServiceContracts/activateAj', { id: CID }, function (r) {
                    if (r && r.ok) { rsToast('Activated.','success'); setTimeout(function(){location.reload();}, 400); }
                    else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                }, 'json');
            }}, cancel: function () {}
        }});
    });

    // Site CRUD
    function siteForm(d) {
        d = d || {};
        return '<form id="site_form">' +
            '<input type="hidden" name="c0d" value="' + (d.c0d || '') + '">' +
            '<input type="hidden" name="contract_id" value="' + CID + '">' +
            '<div class="row g-2 mb-2">' +
              '<div class="col-4"><label class="form-label small">Site code</label><input name="site_code" class="form-control form-control-sm" value="' + esc(d.site_code||'') + '"></div>' +
              '<div class="col-8"><label class="form-label small">Name *</label><input name="name" class="form-control form-control-sm" value="' + esc(d.name||'') + '" required></div>' +
            '</div>' +
            '<div class="mb-2"><label class="form-label small">Physical address</label><input name="physical_address" class="form-control form-control-sm" value="' + esc(d.physical_address||'') + '"></div>' +
            '<div class="row g-2 mb-2">' +
              '<div class="col-4"><label class="form-label small">Region</label><input name="region" class="form-control form-control-sm" value="' + esc(d.region||'') + '"></div>' +
              '<div class="col-4"><label class="form-label small">District</label><input name="district" class="form-control form-control-sm" value="' + esc(d.district||'') + '"></div>' +
              '<div class="col-2"><label class="form-label small">Lat</label><input name="gps_lat" type="number" step="0.0000001" class="form-control form-control-sm" value="' + (d.gps_lat||'') + '"></div>' +
              '<div class="col-2"><label class="form-label small">Lng</label><input name="gps_lng" type="number" step="0.0000001" class="form-control form-control-sm" value="' + (d.gps_lng||'') + '"></div>' +
            '</div>' +
            '<div class="row g-2 mb-2">' +
              '<div class="col-6"><label class="form-label small">Contact name</label><input name="site_contact_name" class="form-control form-control-sm" value="' + esc(d.site_contact_name||'') + '"></div>' +
              '<div class="col-6"><label class="form-label small">Contact phone</label><input name="site_contact_phone" class="form-control form-control-sm" value="' + esc(d.site_contact_phone||'') + '"></div>' +
            '</div>' +
            '<div class="mb-2"><label class="form-label small">Access notes</label><input name="access_notes" class="form-control form-control-sm" value="' + esc(d.access_notes||'') + '"></div>' +
            '<div class="form-check"><input type="checkbox" name="is_active" class="form-check-input" ' + (parseInt(d.is_active==null?1:d.is_active)===1?'checked':'') + '><label class="form-check-label small">Active</label></div>' +
        '</form>';
    }
    function saveSite(d) {
        $.confirm({ title: d && d.c0d ? 'Edit site' : 'Add site', columnClass:'col-md-7', content: siteForm(d), type:'green', buttons: {
            save: { text:'Save', btnClass:'btn-success', action: function () {
                var f = document.getElementById('site_form');
                var p = {};
                ['c0d','contract_id','site_code','name','physical_address','region','district','gps_lat','gps_lng','site_contact_name','site_contact_phone','access_notes'].forEach(function (k) { p[k] = f[k].value; });
                p.is_active = f.is_active.checked ? 1 : 0;
                $.post(PROOT + 'ServiceContracts/saveSiteAj', p, function (r) {
                    if (r && r.ok) { rsToast('Saved.','success'); setTimeout(function(){location.reload();}, 400); }
                    else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                }, 'json');
            }}, cancel: function () {}
        }});
    }
    var addSiteB = document.getElementById('btn_add_site');
    if (addSiteB) addSiteB.addEventListener('click', function () { saveSite({}); });
    document.querySelectorAll('.site_edit, .site_del').forEach(function (b) {
        b.addEventListener('click', function () {
            var tr = b.closest('tr'); var data = JSON.parse(tr.getAttribute('data-json'));
            if (b.classList.contains('site_edit')) { saveSite(data); return; }
            $.confirm({ title:'Remove site?', type:'red', content: esc(data.name), buttons: {
                yes: { text:'Remove', btnClass:'btn-danger', action: function () {
                    $.post(PROOT + 'ServiceContracts/deleteSiteAj', { id: data.c0d }, function (r) {
                        if (r && r.ok) { rsToast('Removed.','success'); setTimeout(function(){location.reload();}, 300); }
                        else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                    }, 'json');
                }}, cancel: function () {}
            }});
        });
    });

    // Asset CRUD
    function assetForm(d) {
        d = d || {};
        var siteOpts = SITES.map(function (s) { return '<option value="' + s.c0d + '"' + ((d.site_id == s.c0d) ? ' selected' : '') + '>' + esc(s.name) + '</option>'; }).join('');
        var typeOpts = TYPES.map(function (t) { return '<option value="' + t.c0d + '"' + ((d.asset_type_id == t.c0d) ? ' selected' : '') + '>' + esc(t.code + ' · ' + t.name) + '</option>'; }).join('');
        return '<form id="ast_form">' +
            '<input type="hidden" name="c0d" value="' + (d.c0d || '') + '">' +
            '<input type="hidden" name="contract_id" value="' + CID + '">' +
            '<div class="row g-2 mb-2">' +
              '<div class="col-6"><label class="form-label small">Site *</label><select name="site_id" class="form-select form-select-sm" required>' + siteOpts + '</select></div>' +
              '<div class="col-6"><label class="form-label small">Asset type *</label><select name="asset_type_id" class="form-select form-select-sm" required>' + typeOpts + '</select></div>' +
            '</div>' +
            '<div class="row g-2 mb-2">' +
              '<div class="col-4"><label class="form-label small">Asset #</label><input name="asset_no" class="form-control form-control-sm" value="' + esc(d.asset_no||'') + '"></div>' +
              '<div class="col-4"><label class="form-label small">Serial #</label><input name="serial_no" class="form-control form-control-sm" value="' + esc(d.serial_no||'') + '"></div>' +
              '<div class="col-2"><label class="form-label small">Size</label><input name="size_value" type="number" min="0" class="form-control form-control-sm" value="' + (d.size_value||'') + '"></div>' +
              '<div class="col-2"><label class="form-label small">Unit</label><input name="size_unit" class="form-control form-control-sm" value="' + (d.size_unit||'kVA') + '"></div>' +
            '</div>' +
            '<div class="row g-2 mb-2">' +
              '<div class="col-6"><label class="form-label small">Make</label><input name="make" class="form-control form-control-sm" value="' + esc(d.make||'') + '"></div>' +
              '<div class="col-6"><label class="form-label small">Model</label><input name="model" class="form-control form-control-sm" value="' + esc(d.model||'') + '"></div>' +
            '</div>' +
            '<div class="row g-2 mb-2">' +
              '<div class="col-4"><label class="form-label small">Install date</label><input name="install_date" type="date" class="form-control form-control-sm" value="' + (d.install_date||'') + '"></div>' +
              '<div class="col-4"><label class="form-label small">Warranty end</label><input name="warranty_end" type="date" class="form-control form-control-sm" value="' + (d.warranty_end||'') + '"></div>' +
              '<div class="col-4"><label class="form-label small">Hours run</label><input name="hours_run" type="number" min="0" class="form-control form-control-sm" value="' + (d.hours_run||'') + '"></div>' +
            '</div>' +
            '<div class="form-check"><input type="checkbox" name="is_active" class="form-check-input" ' + (parseInt(d.is_active==null?1:d.is_active)===1?'checked':'') + '><label class="form-check-label small">Active</label></div>' +
        '</form>';
    }
    function saveAsset(d) {
        $.confirm({ title: d && d.c0d ? 'Edit asset' : 'Add asset', columnClass:'col-md-8', content: assetForm(d), type:'green', buttons: {
            save: { text:'Save', btnClass:'btn-success', action: function () {
                var f = document.getElementById('ast_form');
                var p = {};
                ['c0d','contract_id','site_id','asset_type_id','asset_no','serial_no','make','model','size_value','size_unit','install_date','warranty_end','hours_run'].forEach(function (k) { p[k] = f[k].value; });
                p.is_active = f.is_active.checked ? 1 : 0;
                $.post(PROOT + 'ServiceContracts/saveAssetAj', p, function (r) {
                    if (r && r.ok) { rsToast('Saved.','success'); setTimeout(function(){location.reload();}, 400); }
                    else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                }, 'json');
            }}, cancel: function () {}
        }});
    }
    var addAssetB = document.getElementById('btn_add_asset');
    if (addAssetB) addAssetB.addEventListener('click', function () { saveAsset({}); });
    document.querySelectorAll('.asset_edit, .asset_del').forEach(function (b) {
        b.addEventListener('click', function () {
            var tr = b.closest('tr'); var data = JSON.parse(tr.getAttribute('data-json'));
            if (b.classList.contains('asset_edit')) { saveAsset(data); return; }
            $.confirm({ title:'Remove asset?', type:'red', content: esc(data.asset_no || '(no number)'), buttons: {
                yes: { text:'Remove', btnClass:'btn-danger', action: function () {
                    $.post(PROOT + 'ServiceContracts/deleteAssetAj', { id: data.c0d }, function (r) {
                        if (r && r.ok) { rsToast('Removed.','success'); setTimeout(function(){location.reload();}, 300); }
                        else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                    }, 'json');
                }}, cancel: function () {}
            }});
        });
    });

    // SLA overrides
    document.querySelectorAll('.sla_edit').forEach(function (b) {
        b.addEventListener('click', function () {
            var tr = b.closest('tr'); var catId = parseInt(tr.getAttribute('data-cat-id'), 10);
            var cat = CATS.find(function (c) { return c.c0d === catId; });
            var cur = SLAS_BY_CAT[catId] || {};
            $.confirm({
                title:'Override SLA · ' + cat.name, columnClass:'col-md-6', type:'orange',
                content: '<form id="sla_form">' +
                    '<input type="hidden" name="contract_id" value="' + CID + '">' +
                    '<input type="hidden" name="category_id" value="' + catId + '">' +
                    '<div class="text-muted small mb-2" style="font-size:.65rem;">Defaults: response ' + cat.default_response + 'h · restore ' + cat.default_restore + 'h. Leave blank to fall back to default.</div>' +
                    '<div class="row g-2 mb-2">' +
                      '<div class="col-4"><label class="form-label small">Response (hrs)</label><input name="sla_response_hrs" type="number" min="0" class="form-control form-control-sm" value="' + (cur.sla_response_hrs || '') + '"></div>' +
                      '<div class="col-4"><label class="form-label small">Restore (hrs)</label><input name="sla_restoration_hrs" type="number" min="0" class="form-control form-control-sm" value="' + (cur.sla_restoration_hrs || '') + '"></div>' +
                      '<div class="col-4"><label class="form-label small">Penalty %/hr</label><input name="penalty_pct_per_hr" type="number" step="0.01" min="0" class="form-control form-control-sm" value="' + (cur.penalty_pct_per_hr || '') + '"></div>' +
                    '</div>' +
                    '<div class="mb-2"><label class="form-label small">Notes</label><input name="notes" class="form-control form-control-sm" value="' + esc(cur.notes||'') + '"></div>' +
                '</form>',
                buttons: {
                    save: { text:'Save', btnClass:'btn-warning', action: function () {
                        var f = document.getElementById('sla_form');
                        var p = { contract_id: f.contract_id.value, category_id: f.category_id.value, sla_response_hrs: f.sla_response_hrs.value, sla_restoration_hrs: f.sla_restoration_hrs.value, penalty_pct_per_hr: f.penalty_pct_per_hr.value, notes: f.notes.value };
                        $.post(PROOT + 'ServiceContracts/saveSlaAj', p, function (r) {
                            if (r && r.ok) { rsToast('Saved.','success'); setTimeout(function(){location.reload();}, 400); }
                            else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                        }, 'json');
                    }}, cancel: function () {}
                }
            });
        });
    });

    // Regenerate schedule
    var genB = document.getElementById('btn_gen_schedule');
    if (genB) genB.addEventListener('click', function () {
        $.confirm({ title:'Regenerate PM schedule?', type:'orange', content:'Existing schedule rows will be cleared and recomputed from each asset\'s templates. Executed PMs (Slice S3) are not touched.', buttons: {
            yes: { text:'Regenerate', btnClass:'btn-warning', action: function () {
                $.post(PROOT + 'ServiceContracts/generateScheduleAj', { id: CID }, function (r) {
                    if (r && r.ok) { rsToast('Regenerated (' + r.added + ' rows).','success'); setTimeout(function(){location.reload();}, 400); }
                    else $.alert({title:'Failed', content:(r && r.msg) || 'Server error', type:'red'});
                }, 'json');
            }}, cancel: function () {}
        }});
    });

    // Slice 8S-5 · Preview + Draft consumption invoice
    function parsePeriod() {
        var sel = document.getElementById('bill_period');
        if (!sel) return null;
        var parts = sel.value.split('-');
        return { year: parts[0], month: parts[1], label: sel.options[sel.selectedIndex].text };
    }
    function fmt(n) { return (parseFloat(n||0)).toLocaleString(undefined, {maximumFractionDigits:0}); }

    var prevB = document.getElementById('btn_preview');
    if (prevB) prevB.addEventListener('click', function () {
        var p = parsePeriod(); if (!p) return;
        $.get(PROOT + 'ServiceContracts/consumptionPreviewAj', { id: CID, year: p.year, month: p.month }, function (r) {
            if (!r || !r.ok) { $.alert({title:'Preview failed', content:(r && r.msg) || 'Server error', type:'red'}); return; }
            var rows = (r.lines || []).map(function (l) {
                return '<tr><td class="small">' + esc(l.description) + '</td><td class="text-end small">' + fmt(l.qty) + ' ' + esc(l.unit) + '</td><td class="text-end small">' + fmt(l.unit_price) + '</td><td class="text-end small" style="font-weight:600;">' + fmt(l.line_total) + '</td></tr>';
            }).join('');
            $.confirm({
                title: 'Consumption preview · ' + esc(p.label),
                columnClass: 'col-md-9',
                content:
                    '<div class="text-muted small mb-2" style="font-size:.65rem;">' + (r.callout_count || 0) + ' callout(s) resolved in period · currency ' + esc(r.currency) + '</div>' +
                    (rows ? '<div class="table-responsive"><table class="table table-sm mb-0"><thead class="table-light"><tr><th>Line</th><th class="text-end">Qty</th><th class="text-end">Unit price</th><th class="text-end">Total</th></tr></thead><tbody>' + rows + '</tbody><tfoot><tr><td colspan="3" class="text-end small text-muted">Subtotal</td><td class="text-end" style="font-weight:700;color:#334155;">' + esc(r.currency) + ' ' + fmt(r.subtotal) + '</td></tr></tfoot></table></div>' : '<div class="text-muted small">Nothing billable in that period.</div>'),
                buttons: { close: { text:'Close' } }
            });
        }, 'json');
    });

    // Slice 8S-8 · Download monthly compliance PDF
    var repB = document.getElementById('btn_report');
    if (repB) repB.addEventListener('click', function () {
        var p = parsePeriod(); if (!p) return;
        window.open(PROOT + 'ServiceContracts/reportPdf/' + CID + '?year=' + p.year + '&month=' + p.month, '_blank');
    });

    var draftB = document.getElementById('btn_draft');
    if (draftB) draftB.addEventListener('click', function () {
        var p = parsePeriod(); if (!p) return;
        $.confirm({
            title:'Draft invoice for ' + p.label + '?', type:'green',
            content:'A DRAFT invoice will be created with all callout, labour, mileage and part lines for the selected month. Idempotent — one draft per contract/month.',
            buttons: {
                yes: { text:'Draft', btnClass:'btn-success', action: function () {
                    $.post(PROOT + 'ServiceContracts/draftInvoiceAj', { id: CID, year: p.year, month: p.month }, function (r) {
                        if (r && r.ok) { rsToast('Drafted ' + r.lines + ' lines · ' + fmt(r.subtotal) + '.','success'); setTimeout(function(){window.location.href = PROOT + 'Sales/view/' + r.sale_id;}, 700); }
                        else $.alert({title:'Draft failed', content:(r && r.msg) || 'Server error', type:'red'});
                    }, 'json');
                }}, cancel: function () {}
            }
        });
    });
})();
</script>
<?php $this->end(); ?>
