<?php
declare(strict_types=1);

require_once __DIR__ . '/../security/auth_guard_web.php';
require_once __DIR__ . '/../partials/main.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php includeFileWithVariables('../partials/title-meta.php', ['title' => 'Leads']); ?>
<?php include '../partials/head-css.php'; ?>

<style>
/* List message: 3-line wrap */
.lead-message {
    max-width: 420px;
    white-space: normal;
    word-break: break-word;
    display: -webkit-box;
   
    -webkit-box-orient: vertical;
    overflow: hidden;
}

/* Source URL wrap */
.lead-source-url {
    max-width: 300px;
    white-space: normal;
    word-break: break-word;
    overflow-wrap: anywhere;
}


/* Modal message: full wrap */
.modal-message {
    white-space: normal;
    word-break: break-word;
}

.table td {
    vertical-align: center;
}
</style>
</head>

<body>
<div id="layout-wrapper">

<?php include '../partials/header.php'; ?>
<?php include '../partials/sidebar.php'; ?>
<?php include '../partials/horizontal.php'; ?>

<main class="app-wrapper">
<div class="container-fluid">

<?php includeFileWithVariables('../partials/page-title.php', [
    'title_sub' => 'CRM',
    'title'     => 'Leads'
]); ?>

<!-- ================= FILTER ================= -->
<div class="card mb-4">
<div class="card-body">
<div class="row g-3 align-items-end">

<div class="col-md-4">
    <label class="form-label">Search</label>
    <input type="text" id="search" class="form-control"
           placeholder="Name / Phone / Email">
</div>

<div class="col-md-2">
    <button class="btn btn-primary w-100" onclick="loadLeads(1)">
        Apply
    </button>
</div>

</div>
</div>
</div>

<!-- ================= LIST ================= -->
<div class="card">
<div class="card-body table-responsive">

<table class="table align-middle text-nowrap">
<thead>
<tr>
    <th>#</th>
    <th>Created</th>
    <th>Name</th>
    <th>Contact</th>
    <th>Location</th>
    <th>Purpose</th>
    <th style="width:450px">Message</th>
    <th>Source Type</th>
    <th style="width:300px">Source URL</th>
    <th>Action</th>
</tr>
</thead>

<tbody id="leadRows">
<tr>
    <td colspan="10" class="text-center text-muted">
        Loading leads…
    </td>
</tr>
</tbody>
</table>

<div class="d-flex justify-content-between align-items-center mt-3">
    <div id="paginationInfo" class="text-muted"></div>
    <ul class="pagination pagination-primary mb-0" id="pagination"></ul>
</div>

</div>
</div>

</div>
</main>

<?php include '../partials/footer.php'; ?>
</div>

<?php include '../partials/vendor-scripts.php'; ?>

<!-- ================= VIEW MODAL ================= -->
<div class="modal fade" id="leadViewModal" tabindex="-1">
<div class="modal-dialog modal-lg modal-dialog-scrollable">
<div class="modal-content">

<div class="modal-header">
    <h5 class="modal-title">Lead Details</h5>
    <button class="btn-close" data-bs-dismiss="modal"></button>
</div>

<div class="modal-body">
<dl class="row" id="leadDetails"></dl>
</div>

</div>
</div>
</div>

<script>
const LIST_API = "<?= ADMIN_BASE_URL ?>api/leads/list.php";
const VIEW_API = "<?= ADMIN_BASE_URL ?>api/leads/view.php";

let currentPage = 1;
let viewModal;

/* INIT */
document.addEventListener('DOMContentLoaded', () => {
    viewModal = new bootstrap.Modal(document.getElementById('leadViewModal'));
    loadLeads(1);
});

/* LOAD LEADS */
function loadLeads(page = 1) {
    currentPage = page;
    const params = new URLSearchParams({ page });

    if (search.value.trim() !== '') {
        params.append('search', search.value.trim());
    }

    fetch(LIST_API + '?' + params.toString(), { credentials: 'include' })
        .then(r => r.json())
        .then(res => {
            if (res.status !== 'success') return alert(res.message);

            const rows = document.getElementById('leadRows');
            rows.innerHTML = '';

            const leads = res.data.list;
            const p = res.data.pagination;

            if (!leads.length) {
                rows.innerHTML = `
                    <tr>
                        <td colspan="10" class="text-center text-muted">
                            No leads found
                        </td>
                    </tr>`;
                return;
            }

            leads.forEach((l, i) => {
                rows.innerHTML += `
<tr>
<td>${(p.page - 1) * p.limit + i + 1}</td>
<td>${l.created_at}</td>
<td>
    <strong>${esc(l.name)}</strong><br>
    <small class="text-muted">${esc(l.email ?? '-')}</small>
</td>
<td>${esc(l.phone)}</td>
<td>${esc(l.city ?? '-')} , ${esc(l.state ?? '-')}</td>
<td>${esc(l.product_purpose ?? '-')}</td>
<td class="lead-message">${esc(l.message ?? '-')}</td>
<td>${esc(l.source_type ?? '-')}</td>
<td class="lead-source-url">
    ${l.source_url
        ? `<a href="${esc(l.source_url)}" target="_blank">${esc(l.source_url)}</a>`
        : '-'}
</td>
<td>
    <button class="btn btn-sm btn-light-info"
            onclick="viewLead(${l.id})">
        <i class="bi bi-eye"></i>
    </button>
</td>
</tr>`;
            });

            renderPagination(p.pages, p.page);
            paginationInfo.innerText =
                `Showing page ${p.page} of ${p.pages}`;
        });
}

/* VIEW LEAD */
function viewLead(id) {
    fetch(VIEW_API + '?id=' + id, { credentials: 'include' })
        .then(r => r.json())
        .then(res => {
            if (res.status !== 'success') return alert(res.message);

            const l = res.data.lead;

            leadDetails.innerHTML = `
<dt class="col-4">Name</dt><dd class="col-8">${esc(l.name)}</dd>
<dt class="col-4">Phone</dt><dd class="col-8">${esc(l.phone)}</dd>
<dt class="col-4">Email</dt><dd class="col-8">${esc(l.email ?? '-')}</dd>
<dt class="col-4">Purpose</dt><dd class="col-8">${esc(l.product_purpose ?? '-')}</dd>
<dt class="col-4">Message</dt>
<dd class="col-8 modal-message">${esc(l.message ?? '-')}</dd>
<dt class="col-4">Source Type</dt><dd class="col-8">${esc(l.source_type ?? '-')}</dd>
<dt class="col-4">Source URL</dt><dd class="col-8">${esc(l.source_url ?? '-')}</dd>
<dt class="col-4">Created</dt><dd class="col-8">${l.created_at}</dd>
`;

            viewModal.show();
        });
}

/* HELPERS */
function renderPagination(total, page) {
    pagination.innerHTML = '';
    for (let i = 1; i <= total; i++) {
        pagination.innerHTML += `
        <li class="page-item ${i === page ? 'active' : ''}">
            <a class="page-link"
               href="javascript:void(0)"
               onclick="loadLeads(${i})">${i}</a>
        </li>`;
    }
}

function esc(str) {
    return String(str ?? '')
        .replace(/&/g,"&amp;")
        .replace(/</g,"&lt;")
        .replace(/>/g,"&gt;")
        .replace(/"/g,"&quot;")
        .replace(/'/g,"&#039;");
}
</script>

</body>
</html>
