<?php
// clients.php
// Loaded as a FRAGMENT into index.php's shared modal (same pattern as
// add_job.php / view_job.php). Lists all clients and lets the user add a
// new one or edit an existing one inline — no separate page, no navigation.
//
// Viewable by all three roles (Coordinator's job is client relations),
// but the add/edit actions themselves are blocked for Coordinator at
// save_client.php — see the note there.
require_once 'includes/auth.php';
require_role(['admin', 'inspector', 'coordinator'], true);

require_once 'db.php';

$me = current_user();
$canEdit = in_array($me['role'], ['admin', 'inspector'], true);

$stmt = $pdo->query("SELECT * FROM tbl_clients WHERE Deleted_At IS NULL ORDER BY Client_Name ASC");
$clients = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<div class="modal-header bg-primary text-white">
    <h5 class="modal-title"><i class="fa-solid fa-address-book me-2"></i> Clients Register</h5>
    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
    <div id="clientFormAlert"></div>

    <?php if ($canEdit): ?>
    <!-- Add New Client -->
    <div class="card mb-4 border-primary">
        <div class="card-header bg-light fw-bold"><i class="fa-solid fa-plus me-1"></i> Add New Client</div>
        <div class="card-body">
            <form id="addClientForm" class="row g-2">
                <div class="col-md-4">
                    <input type="text" name="client_name" class="form-control form-control-sm" placeholder="Client Name *" required>
                </div>
                <div class="col-md-3">
                    <input type="text" name="contact_person" class="form-control form-control-sm" placeholder="Contact Person">
                </div>
                <div class="col-md-3">
                    <input type="text" name="phone" class="form-control form-control-sm" placeholder="Phone">
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-sm btn-primary w-100">Add</button>
                </div>
                <div class="col-md-6">
                    <input type="email" name="email" class="form-control form-control-sm" placeholder="Email">
                </div>
                <div class="col-md-6">
                    <input type="text" name="address" class="form-control form-control-sm" placeholder="Address">
                </div>
            </form>
        </div>
    </div>
    <?php else: ?>
    <div class="alert alert-info py-2 small"><i class="fa-solid fa-circle-info me-1"></i> Read-only access — Coordinator role can view client details but not add or edit them.</div>
    <?php endif; ?>

    <!-- Existing Clients -->
    <div class="table-responsive">
        <table class="table table-sm table-hover align-middle" id="clientsTable">
            <thead class="table-light">
                <tr>
                    <th>Client Name</th>
                    <th>Contact Person</th>
                    <th>Phone</th>
                    <th>Email</th>
                    <th>Address</th>
                    <th class="text-center">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($clients as $c): ?>
                    <tr data-client-id="<?= (int) $c['ClientID']; ?>">
                        <td class="client-view fw-semibold"><?= htmlspecialchars($c['Client_Name']); ?></td>
                        <td class="client-view"><?= htmlspecialchars($c['Contact_Person'] ?? ''); ?></td>
                        <td class="client-view"><?= htmlspecialchars($c['Phone'] ?? ''); ?></td>
                        <td class="client-view"><?= htmlspecialchars($c['Email'] ?? ''); ?></td>
                        <td class="client-view"><?= htmlspecialchars($c['Address'] ?? ''); ?></td>
                        <td class="text-center">
                            <button type="button" class="btn btn-sm btn-outline-primary js-toggle-sites" data-target="sitesRow<?= (int) $c['ClientID']; ?>" title="Manage Sites">
                                <i class="fa-solid fa-map-location-dot"></i>
                            </button>
                            <?php if ($canEdit): ?>
                                <button type="button" class="btn btn-sm btn-outline-secondary js-edit-client">
                                    <i class="fa-solid fa-pen"></i>
                                </button>
                            <?php else: ?>
                                <span class="text-muted small">—</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <tr id="sitesRow<?= (int) $c['ClientID']; ?>" hidden>
                        <td colspan="6" class="bg-light p-0">
                            <div class="p-2 js-sites-panel" data-client-id="<?= (int) $c['ClientID']; ?>" data-can-edit="<?= $canEdit ? '1' : '0'; ?>" data-loaded="0">
                                <div class="small text-muted">Loading sites...</div>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
                <?php if (empty($clients)): ?>
                    <tr><td colspan="6" class="text-center text-muted py-3">No clients yet.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
(function () {
    var alertBox = document.getElementById('clientFormAlert');
    var addForm = document.getElementById('addClientForm');

    function showAlert(message, isError) {
        alertBox.innerHTML = '<div class="alert ' + (isError ? 'alert-danger' : 'alert-success') + ' py-2">' + message + '</div>';
        setTimeout(function () { alertBox.innerHTML = ''; }, 3000);
    }

    addForm.addEventListener('submit', function (e) {
        e.preventDefault();
        var formData = new FormData(addForm);
        formData.append('csrf_token', document.querySelector('meta[name="csrf-token"]').content);
        fetch('save_client.php', { method: 'POST', body: formData })
            .then(function (r) {
                if (r.status === 401) { window.location.href = 'login.php'; return Promise.reject(new Error('Session expired.')); }
                return r.text().then(function (text) {
                    try { return JSON.parse(text); }
                    catch (e) { throw new Error(text.substring(0, 150) || 'Unexpected server response.'); }
                });
            })
            .then(function (data) {
                if (data.status === 'success') {
                    showAlert('Client added.', false);
                    addForm.reset();
                    // Reload this same modal content to refresh the list in place.
                    fetch('clients.php').then(function (r) { return r.text(); }).then(function (html) {
                        window.injectHtmlWithScripts(document.getElementById('modalContentBody'), html);
                    });
                } else {
                    showAlert(data.message || 'Failed to add client.', true);
                }
            })
            .catch(function (err) {
                showAlert(err.message || 'Network or permission error.', true);
            });
    });

    document.querySelectorAll('.js-edit-client').forEach(function (btn) {
        btn.addEventListener('click', function () {
            var row = btn.closest('tr');
            var clientId = row.getAttribute('data-client-id');
            var cells = row.querySelectorAll('.client-view');
            var currentValues = Array.prototype.map.call(cells, function (td) { return td.textContent.trim(); });

            // HARDENING: previously built via string-concatenated innerHTML
            // with manual "only escape the quote character" regex — safe in
            // this exact spot today, but a fragile pattern that a future
            // edit could easily turn into a real XSS. Built via safe DOM
            // APIs instead: .value is never HTML-parsed, so no escaping is
            // needed or possible to get wrong.
            var types = ['text', 'text', 'text', 'email', 'text'];
            cells.forEach(function (cell, i) {
                var input = document.createElement('input');
                input.type = types[i];
                input.className = 'form-control form-control-sm';
                input.value = currentValues[i];
                cell.innerHTML = '';
                cell.appendChild(input);
            });

            btn.innerHTML = '<i class="fa-solid fa-check"></i>';
            btn.classList.replace('btn-outline-secondary', 'btn-success');
            btn.classList.remove('js-edit-client');
            btn.classList.add('js-save-client');

            btn.addEventListener('click', function saveHandler() {
                var inputs = row.querySelectorAll('input');
                var payload = new FormData();
                payload.append('csrf_token', document.querySelector('meta[name="csrf-token"]').content);
                payload.append('client_id', clientId);
                payload.append('client_name', inputs[0].value);
                payload.append('contact_person', inputs[1].value);
                payload.append('phone', inputs[2].value);
                payload.append('email', inputs[3].value);
                payload.append('address', inputs[4].value);

                fetch('save_client.php', { method: 'POST', body: payload })
                    .then(function (r) {
                        if (r.status === 401) { window.location.href = 'login.php'; return Promise.reject(new Error('Session expired.')); }
                        return r.text().then(function (text) {
                            try { return JSON.parse(text); }
                            catch (e) { throw new Error(text.substring(0, 150) || 'Unexpected server response.'); }
                        });
                    })
                    .then(function (data) {
                        if (data.status === 'success') {
                            fetch('clients.php').then(function (r) { return r.text(); }).then(function (html) {
                                window.injectHtmlWithScripts(document.getElementById('modalContentBody'), html);
                            });
                        } else {
                            showAlert(data.message || 'Failed to save client.', true);
                        }
                    })
                    .catch(function (err) {
                        showAlert(err.message || 'Network or permission error.', true);
                    });
            }, { once: true });
        });
    });
})();
</script>

<script>
(function () {
    var csrfMeta = document.querySelector('meta[name="csrf-token"]');
    var csrfToken = csrfMeta ? csrfMeta.content : '';

    function loadSitesPanel(panel) {
        var clientId = panel.getAttribute('data-client-id');
        var canEdit = panel.getAttribute('data-can-edit') === '1';

        fetch('get_client_sites.php?client_id=' + encodeURIComponent(clientId))
            .then(function (r) { return r.json(); })
            .then(function (data) {
                panel.innerHTML = '';
                if (data.status !== 'success') {
                    var errDiv = document.createElement('div');
                    errDiv.className = 'small text-danger';
                    errDiv.textContent = data.message || 'Failed to load sites.';
                    panel.appendChild(errDiv);
                    return;
                }

                var list = document.createElement('ul');
                list.className = 'list-group list-group-flush mb-2';

                if (data.sites.length === 0) {
                    var emptyLi = document.createElement('li');
                    emptyLi.className = 'list-group-item small text-muted bg-transparent';
                    emptyLi.textContent = 'No sites added yet.';
                    list.appendChild(emptyLi);
                }

                data.sites.forEach(function (site) {
                    var li = document.createElement('li');
                    li.className = 'list-group-item d-flex justify-content-between align-items-center bg-transparent small';

                    var nameSpan = document.createElement('span');
                    nameSpan.textContent = site.Site_Name;
                    li.appendChild(nameSpan);

                    if (canEdit) {
                        var delBtn = document.createElement('button');
                        delBtn.type = 'button';
                        delBtn.className = 'btn btn-sm btn-outline-danger py-0 px-1';
                        var delIcon = document.createElement('i');
                        delIcon.className = 'fa-solid fa-xmark';
                        delBtn.appendChild(delIcon);
                        delBtn.addEventListener('click', function () {
                            if (!confirm('Remove this site?')) return;
                            var fd = new FormData();
                            fd.append('site_id', site.SiteID);
                            fd.append('csrf_token', csrfToken);
                            fetch('delete_client_site.php', { method: 'POST', body: fd })
                                .then(function (r) { return r.json(); })
                                .then(function (d) {
                                    if (d.status === 'success') {
                                        panel.setAttribute('data-loaded', '0');
                                        loadSitesPanel(panel);
                                    } else {
                                        alert(d.message || 'Failed to remove site.');
                                    }
                                });
                        });
                        li.appendChild(delBtn);
                    }

                    list.appendChild(li);
                });

                panel.appendChild(list);

                if (canEdit) {
                    var form = document.createElement('form');
                    form.className = 'd-flex gap-2';

                    var input = document.createElement('input');
                    input.type = 'text';
                    input.className = 'form-control form-control-sm';
                    input.placeholder = 'New site name';
                    input.required = true;

                    var addBtn = document.createElement('button');
                    addBtn.type = 'submit';
                    addBtn.className = 'btn btn-sm btn-primary';
                    addBtn.textContent = 'Add';

                    form.appendChild(input);
                    form.appendChild(addBtn);
                    panel.appendChild(form);

                    form.addEventListener('submit', function (e) {
                        e.preventDefault();
                        var siteName = input.value.trim();
                        if (!siteName) return;
                        addBtn.disabled = true;
                        var fd = new FormData();
                        fd.append('client_id', clientId);
                        fd.append('site_name', siteName);
                        fd.append('csrf_token', csrfToken);
                        fetch('save_client_site.php', { method: 'POST', body: fd })
                            .then(function (r) { return r.json(); })
                            .then(function (d) {
                                addBtn.disabled = false;
                                if (d.status === 'success') {
                                    input.value = '';
                                    panel.setAttribute('data-loaded', '0');
                                    loadSitesPanel(panel);
                                } else {
                                    alert(d.message || 'Failed to add site.');
                                }
                            })
                            .catch(function () { addBtn.disabled = false; });
                    });
                }

                panel.setAttribute('data-loaded', '1');
            })
            .catch(function () {
                panel.innerHTML = '';
                var errDiv = document.createElement('div');
                errDiv.className = 'small text-danger';
                errDiv.textContent = 'Network error while loading sites.';
                panel.appendChild(errDiv);
            });
    }

    document.querySelectorAll('.js-toggle-sites').forEach(function (btn) {
        btn.addEventListener('click', function () {
            var row = document.getElementById(btn.getAttribute('data-target'));
            if (!row) return;
            row.hidden = !row.hidden;
            if (!row.hidden) {
                var panel = row.querySelector('.js-sites-panel');
                if (panel && panel.getAttribute('data-loaded') === '0') {
                    loadSitesPanel(panel);
                }
            }
        });
    });
})();
</script>
