<?php
$contract    = $contract ?? [];
$lines       = old('lines', $lines ?? []);
$milestones  = old('milestones', $milestones ?? []);
$assignments = $assignments ?? [];
$companies   = $companies ?? [];
$employees   = $employees ?? [];
$employeeSearch = $employeeSearch ?? '';

if (! is_array($lines) || count($lines) === 0) {
    $lines = [['item_code' => '', 'item_name' => '', 'quantity' => '1', 'unit' => 'pcs', 'unit_price' => '']];
}
if (! is_array($milestones) || count($milestones) === 0) {
    $milestones = [['title' => '', 'due_date' => '', 'amount' => '', 'status' => 'pending']];
}

$assignedIds = [];
$assignmentMap = [];
$oldEmployees = old('employees');
if (is_array($oldEmployees)) {
    foreach ($oldEmployees as $row) {
        if (is_array($row)) {
            $eid = (int) ($row['employee_id'] ?? 0);
            if ($eid > 0) {
                $assignedIds[] = $eid;
                $assignmentMap[$eid] = $row;
            }
        } else {
            $eid = (int) $row;
            if ($eid > 0) {
                $assignedIds[] = $eid;
            }
        }
    }
} else {
    foreach ($assignments as $a) {
        $eid = (int) ($a['employee_id'] ?? 0);
        if ($eid > 0) {
            $assignedIds[] = $eid;
            $assignmentMap[$eid] = $a;
        }
    }
}

$companyTypes = [];
foreach ($companies as $c) {
    $companyTypes[(string) $c['id']] = $c['customer_type'] ?? '';
}

$selectedCompanyId = (string) old('company_id', $contract['company_id'] ?? ($preselectCompanyId ?? ''));
$selectedType = (string) old('contract_type', $contract['contract_type'] ?? ($preselectType ?? ''));
if ($selectedType === '' && $selectedCompanyId !== '' && isset($companyTypes[$selectedCompanyId])) {
    $selectedType = $companyTypes[$selectedCompanyId];
}
?>
<div class="enterprise-settings-fields">
    <div class="enterprise-field">
        <label class="enterprise-field-label">Customer <span class="text-danger">*</span></label>
        <select name="company_id" id="contract-company" class="form-select" required>
            <option value="">— Select customer —</option>
            <?php foreach ($companies as $c): ?>
                <option value="<?= $c['id'] ?>"
                        data-type="<?= esc($c['customer_type'] ?? '') ?>"
                        <?= $selectedCompanyId === (string) $c['id'] ? 'selected' : '' ?>>
                    <?= esc($c['name']) ?> (<?= esc(ucfirst($c['customer_type'] ?? 'unset')) ?><?= ! empty($c['is_one_time']) ? ', one-time' : '' ?>)
                </option>
            <?php endforeach; ?>
        </select>
    </div>
    <div class="enterprise-field">
        <label class="enterprise-field-label">Contract Type</label>
        <input type="hidden" name="contract_type" id="contract-type" value="<?= esc($selectedType) ?>">
        <input type="text" id="contract-type-label" class="form-control" readonly
               value="<?= esc($selectedType ? ucfirst($selectedType) . ' based' : 'Select a customer') ?>">
    </div>
    <div class="enterprise-field">
        <label class="enterprise-field-label">Title <span class="text-danger">*</span></label>
        <input type="text" name="title" class="form-control" required
               value="<?= esc(old('title', $contract['title'] ?? '')) ?>">
    </div>
    <div class="enterprise-field">
        <label class="enterprise-field-label">Status</label>
        <select name="status" class="form-select">
            <?php foreach (['draft', 'active', 'expired', 'terminated', 'cancelled'] as $s): ?>
                <option value="<?= $s ?>" <?= old('status', $contract['status'] ?? 'draft') === $s ? 'selected' : '' ?>><?= ucfirst($s) ?></option>
            <?php endforeach; ?>
        </select>
    </div>
    <div class="enterprise-field">
        <label class="enterprise-field-label">Start Date</label>
        <input type="date" name="start_date" class="form-control" value="<?= esc(old('start_date', $contract['start_date'] ?? '')) ?>">
    </div>
    <div class="enterprise-field">
        <label class="enterprise-field-label">End Date</label>
        <input type="date" name="end_date" class="form-control" value="<?= esc(old('end_date', $contract['end_date'] ?? '')) ?>">
    </div>
    <div class="enterprise-field">
        <label class="enterprise-field-label">Contract Value</label>
        <input type="number" name="value" id="contract-value" class="form-control" step="0.01" min="0"
               value="<?= esc(old('value', $contract['value'] ?? '')) ?>"
               placeholder="Auto from lines / hours × rate if left blank on create">
    </div>

    <div id="section-product" class="contract-type-section" style="grid-column: 1 / -1; display:none;">
        <h3 class="h6 text-uppercase text-muted mb-2">Product lines</h3>
        <div class="d-flex align-items-center justify-content-between mb-2">
            <span class="small text-muted">Items purchased under this contract</span>
            <button type="button" class="btn btn-sm btn-outline-secondary" id="product-lines-add">
                <i class="fa-solid fa-plus me-1"></i>Add line
            </button>
        </div>
        <div class="table-responsive">
            <table class="enterprise-data-table" id="product-lines-table">
                <thead>
                    <tr>
                        <th>Code</th>
                        <th>Item</th>
                        <th style="width:100px;">Qty</th>
                        <th style="width:90px;">Unit</th>
                        <th style="width:120px;">Unit Price</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($lines as $i => $line): ?>
                        <tr>
                            <td><input type="text" name="lines[<?= (int) $i ?>][item_code]" class="form-control form-control-sm" value="<?= esc($line['item_code'] ?? '') ?>"></td>
                            <td><input type="text" name="lines[<?= (int) $i ?>][item_name]" class="form-control form-control-sm" value="<?= esc($line['item_name'] ?? '') ?>"></td>
                            <td><input type="number" name="lines[<?= (int) $i ?>][quantity]" class="form-control form-control-sm" step="0.001" min="0" value="<?= esc($line['quantity'] ?? '1') ?>"></td>
                            <td><input type="text" name="lines[<?= (int) $i ?>][unit]" class="form-control form-control-sm" value="<?= esc($line['unit'] ?? 'pcs') ?>"></td>
                            <td><input type="number" name="lines[<?= (int) $i ?>][unit_price]" class="form-control form-control-sm" step="0.01" min="0" value="<?= esc($line['unit_price'] ?? '') ?>"></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

    <div id="section-service" class="contract-type-section" style="grid-column: 1 / -1; display:none;">
        <h3 class="h6 text-uppercase text-muted mb-2">Service details</h3>
        <div class="enterprise-settings-fields">
            <div class="enterprise-field">
                <label class="enterprise-field-label">Total Hours <span class="text-danger">*</span></label>
                <input type="number" name="total_hours" id="total-hours" class="form-control" step="0.01" min="0"
                       value="<?= esc(old('total_hours', $contract['total_hours'] ?? '')) ?>">
            </div>
            <div class="enterprise-field">
                <label class="enterprise-field-label">Hourly Rate <span class="text-danger">*</span></label>
                <input type="number" name="hourly_rate" id="hourly-rate" class="form-control" step="0.01" min="0"
                       value="<?= esc(old('hourly_rate', $contract['hourly_rate'] ?? '')) ?>">
            </div>
            <div class="enterprise-field" style="grid-column: 1 / -1;">
                <label class="enterprise-field-label">Location <span class="text-danger">*</span></label>
                <input type="text" name="location" class="form-control"
                       value="<?= esc(old('location', $contract['location'] ?? '')) ?>"
                       placeholder="Site / office / remote location">
            </div>
        </div>
        <h3 class="h6 text-uppercase text-muted mt-3 mb-2">Assigned employees <span class="text-danger">*</span></h3>
        <p class="text-muted small">Only assigned staff are listed here. Search by name or number to add more employees.</p>
        <div class="row g-2 align-items-end mb-3">
            <div class="col-md-6">
                <label class="enterprise-field-label">Find employee</label>
                <input type="text" name="employee_q" class="form-control form-control-sm" value="<?= esc($employeeSearch ?? '') ?>"
                       placeholder="Name or employee number">
            </div>
            <div class="col-auto">
                <button type="submit" class="btn btn-sm btn-outline-secondary" formmethod="get">Search</button>
            </div>
        </div>
        <div class="table-responsive">
            <table class="enterprise-data-table">
                <thead>
                    <tr>
                        <th style="width:48px;"></th>
                        <th>Employee</th>
                        <th>Role on contract</th>
                        <th style="width:160px;">Transport leg</th>
                        <th style="width:120px;">Hours allocated</th>
                    </tr>
                </thead>
                <tbody id="contract-employee-rows">
                    <?php foreach ($employees as $i => $emp): ?>
                        <?php
                        $eid = (int) $emp['id'];
                        $checked = in_array($eid, $assignedIds, true);
                        $meta = $assignmentMap[$eid] ?? [];
                        ?>
                        <tr>
                            <td>
                                <input type="checkbox" class="form-check-input emp-check"
                                       name="employees[<?= $i ?>][employee_id]" value="<?= $eid ?>"
                                       <?= $checked ? 'checked' : '' ?>>
                            </td>
                            <td>
                                <?= esc($emp['full_name']) ?>
                                <div class="text-muted small"><?= esc($emp['employee_number'] ?? '') ?><?= ! empty($emp['job_title']) ? ' · ' . esc($emp['job_title']) : '' ?></div>
                            </td>
                            <td>
                                <input type="text" name="employees[<?= $i ?>][role_on_contract]" class="form-control form-control-sm"
                                       value="<?= esc($meta['role_on_contract'] ?? '') ?>" <?= $checked ? '' : 'disabled' ?>>
                            </td>
                            <td>
                                <?php $leg = $meta['transport_leg'] ?? 'both'; ?>
                                <select name="employees[<?= $i ?>][transport_leg]" class="form-select form-select-sm" <?= $checked ? '' : 'disabled' ?>>
                                    <option value="both" <?= $leg === 'both' ? 'selected' : '' ?>>Both (morning &amp; return)</option>
                                    <option value="outbound_only" <?= $leg === 'outbound_only' ? 'selected' : '' ?>>Outbound only</option>
                                    <option value="return_only" <?= $leg === 'return_only' ? 'selected' : '' ?>>Return only</option>
                                </select>
                            </td>
                            <td>
                                <input type="number" name="employees[<?= $i ?>][hours_allocated]" class="form-control form-control-sm" step="0.01" min="0"
                                       value="<?= esc($meta['hours_allocated'] ?? '') ?>" <?= $checked ? '' : 'disabled' ?>>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    <?php if (count($employees) === 0): ?>
                        <tr><td colspan="5" class="text-muted">Search above to find employees, then check the ones to assign.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <div id="section-project" class="contract-type-section" style="grid-column: 1 / -1; display:none;">
        <h3 class="h6 text-uppercase text-muted mb-2">Project details</h3>
        <div class="enterprise-settings-fields">
            <div class="enterprise-field" style="grid-column: 1 / -1;">
                <label class="enterprise-field-label">Project Name <span class="text-danger">*</span></label>
                <input type="text" name="project_name" class="form-control"
                       value="<?= esc(old('project_name', $contract['project_name'] ?? '')) ?>">
            </div>
            <div class="enterprise-field" style="grid-column: 1 / -1;">
                <label class="enterprise-field-label">Project Description</label>
                <textarea name="project_description" class="form-control" rows="3"><?= esc(old('project_description', $contract['project_description'] ?? '')) ?></textarea>
            </div>
        </div>
        <div class="d-flex align-items-center justify-content-between mt-3 mb-2">
            <h3 class="h6 text-uppercase text-muted mb-0">Milestones (optional)</h3>
            <button type="button" class="btn btn-sm btn-outline-secondary" id="milestones-add">
                <i class="fa-solid fa-plus me-1"></i>Add milestone
            </button>
        </div>
        <div class="table-responsive">
            <table class="enterprise-data-table" id="milestones-table">
                <thead>
                    <tr>
                        <th>Title</th>
                        <th style="width:140px;">Due date</th>
                        <th style="width:120px;">Amount</th>
                        <th style="width:110px;">Status</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($milestones as $i => $m): ?>
                        <tr>
                            <td><input type="text" name="milestones[<?= (int) $i ?>][title]" class="form-control form-control-sm" value="<?= esc($m['title'] ?? '') ?>"></td>
                            <td><input type="date" name="milestones[<?= (int) $i ?>][due_date]" class="form-control form-control-sm" value="<?= esc($m['due_date'] ?? '') ?>"></td>
                            <td><input type="number" name="milestones[<?= (int) $i ?>][amount]" class="form-control form-control-sm" step="0.01" min="0" value="<?= esc($m['amount'] ?? '') ?>"></td>
                            <td>
                                <select name="milestones[<?= (int) $i ?>][status]" class="form-select form-select-sm">
                                    <?php foreach (['pending', 'done'] as $ms): ?>
                                        <option value="<?= $ms ?>" <?= ($m['status'] ?? 'pending') === $ms ? 'selected' : '' ?>><?= ucfirst($ms) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

    <div class="enterprise-field" style="grid-column: 1 / -1;">
        <label class="enterprise-field-label">Notes</label>
        <textarea name="notes" class="form-control" rows="3"><?= esc(old('notes', $contract['notes'] ?? '')) ?></textarea>
    </div>
</div>

<script>
(function () {
    var companySelect = document.getElementById('contract-company');
    var typeInput = document.getElementById('contract-type');
    var typeLabel = document.getElementById('contract-type-label');
    var sections = {
        product: document.getElementById('section-product'),
        service: document.getElementById('section-service'),
        project: document.getElementById('section-project')
    };

    function showType(type) {
        Object.keys(sections).forEach(function (key) {
            if (sections[key]) sections[key].style.display = key === type ? 'block' : 'none';
        });
        typeInput.value = type || '';
        typeLabel.value = type ? (type.charAt(0).toUpperCase() + type.slice(1) + ' based') : 'Select a customer';
    }

    function syncFromCompany() {
        var opt = companySelect.options[companySelect.selectedIndex];
        var type = opt ? (opt.getAttribute('data-type') || '') : '';
        showType(type);
    }

    if (companySelect) {
        companySelect.addEventListener('change', syncFromCompany);
        syncFromCompany();
    }

    var hours = document.getElementById('total-hours');
    var rate = document.getElementById('hourly-rate');
    var valueInput = document.getElementById('contract-value');
    function suggestValue() {
        if (!hours || !rate || !valueInput) return;
        var h = parseFloat(hours.value || '0');
        var r = parseFloat(rate.value || '0');
        if (h > 0 && r >= 0 && (!valueInput.dataset.touched || valueInput.value === '')) {
            valueInput.value = (h * r).toFixed(2);
        }
    }
    if (valueInput) {
        valueInput.addEventListener('input', function () { valueInput.dataset.touched = '1'; });
    }
    if (hours) hours.addEventListener('input', suggestValue);
    if (rate) rate.addEventListener('input', suggestValue);

    document.querySelectorAll('.emp-check').forEach(function (cb) {
        cb.addEventListener('change', function () {
            var row = cb.closest('tr');
            row.querySelectorAll('input[type="text"], input[type="number"], select').forEach(function (inp) {
                inp.disabled = !cb.checked;
            });
        });
    });

    function cloneRow(btnId, tableId, prefix) {
        var btn = document.getElementById(btnId);
        var table = document.getElementById(tableId);
        if (!btn || !table) return;
        btn.addEventListener('click', function () {
            var tbody = table.querySelector('tbody');
            var rows = tbody.querySelectorAll('tr');
            var last = rows[rows.length - 1];
            if (!last) return;
            var clone = last.cloneNode(true);
            var next = rows.length;
            clone.querySelectorAll('input, select').forEach(function (el) {
                var name = el.getAttribute('name') || '';
                el.setAttribute('name', name.replace(new RegExp(prefix + '\\[\\d+\\]'), prefix + '[' + next + ']'));
                if (el.tagName === 'SELECT') {
                    el.selectedIndex = 0;
                } else if (el.type === 'number' && name.indexOf('quantity') !== -1) {
                    el.value = '1';
                } else if (name.indexOf('[unit]') !== -1) {
                    el.value = 'pcs';
                } else if (name.indexOf('[status]') === -1) {
                    el.value = '';
                }
            });
            tbody.appendChild(clone);
        });
    }
    cloneRow('product-lines-add', 'product-lines-table', 'lines');
    cloneRow('milestones-add', 'milestones-table', 'milestones');
})();
</script>
