<?php
session_start();
require_once "../config.php";

function e($v): string {
    return htmlspecialchars((string)($v ?? ''), ENT_QUOTES, 'UTF-8');
}

function bindParamsDynamic(mysqli_stmt $stmt, string $types, array $params): void {
    if ($types === '' || empty($params)) {
        return;
    }
    $bindNames = [$types];
    foreach ($params as $k => $v) {
        $bindNames[] = &$params[$k];
    }
    call_user_func_array([$stmt, 'bind_param'], $bindNames);
}

function roleKey(string $rawRole): string {
    return strtolower(preg_replace('/[^a-z0-9]/', '', $rawRole));
}

function canDeleteExecutive(mysqli $conn, int $loggedUserId, string $role, int $execId): bool
{
    $role = roleKey($role);

    if ($role === 'admin') {
        return true;
    }

    if ($role === 'agency') {
        $sql = "
            SELECT 1
            FROM users u
            LEFT JOIN users m ON u.manager_id = m.id
            WHERE u.id = ? AND u.role = 'medical_representative' AND m.agency_id = ?
            LIMIT 1
        ";
        $stmt = $conn->prepare($sql);
        if (!$stmt) return false;
        $stmt->bind_param("ii", $execId, $loggedUserId);
        $stmt->execute();
        $res = $stmt->get_result();
        $ok = $res && $res->num_rows > 0;
        $stmt->close();
        return $ok;
    }

    if ($role === 'salesmanager' || $role === 'sales_manager') {
        $sql = "
            SELECT 1
            FROM users u
            WHERE u.id = ? AND u.role = 'medical_representative' AND u.manager_id = ?
            LIMIT 1
        ";
        $stmt = $conn->prepare($sql);
        if (!$stmt) return false;
        $stmt->bind_param("ii", $execId, $loggedUserId);
        $stmt->execute();
        $res = $stmt->get_result();
        $ok = $res && $res->num_rows > 0;
        $stmt->close();
        return $ok;
    }

    if ($role === 'salesexecutive' || $role === 'sales_executive') {
        return $execId === $loggedUserId;
    }

    return false;
}

function buildWhereClause(string $role, int $loggedUserId, string $q, array &$params, string &$types): string {
    $conditions = ["u.role = ?"];
    $params[] = 'medical_representative';
    $types .= 's';

    $role = roleKey($role);

    if ($role === 'agency') {
        $conditions[] = "m.agency_id = ?";
        $params[] = $loggedUserId;
        $types .= 'i';
    } elseif ($role === 'salesmanager' || $role === 'sales_manager') {
        $conditions[] = "u.manager_id = ?";
        $params[] = $loggedUserId;
        $types .= 'i';
    } elseif ($role === 'salesexecutive' || $role === 'sales_executive') {
        $conditions[] = "u.id = ?";
        $params[] = $loggedUserId;
        $types .= 'i';
    }

    $q = trim($q);
    if ($q !== '') {
        $conditions[] = "(u.name LIKE ? OR u.email LIKE ? OR m.name LIKE ?)";
        $like = '%' . $q . '%';
        $params[] = $like;
        $params[] = $like;
        $params[] = $like;
        $types .= 'sss';
    }

    return implode(' AND ', $conditions);
}

function fetchExecutives(mysqli $conn, string $role, int $loggedUserId, string $q, int $page, int $limit): array {
    $params = [];
    $types = '';
    $where = buildWhereClause($role, $loggedUserId, $q, $params, $types);
    $offset = max(0, ($page - 1) * $limit);

    $countSql = "
        SELECT COUNT(*) AS total
        FROM users u
        LEFT JOIN users m ON u.manager_id = m.id
        WHERE $where
    ";
    $countStmt = $conn->prepare($countSql);
    if (!$countStmt) {
        return [[], 0, 'Prepare failed: ' . $conn->error];
    }
    bindParamsDynamic($countStmt, $types, $params);
    if (!$countStmt->execute()) {
        $err = 'Execute failed: ' . $countStmt->error;
        $countStmt->close();
        return [[], 0, $err];
    }
    $totalRow = $countStmt->get_result()->fetch_assoc();
    $total = (int)($totalRow['total'] ?? 0);
    $countStmt->close();

    $dataSql = "
        SELECT
            u.id AS exec_id,
            u.name AS exec_name,
            u.email AS exec_email,
            u.is_approved AS exec_approved,
            m.name AS manager_name
        FROM users u
        LEFT JOIN users m ON u.manager_id = m.id
        WHERE $where
        ORDER BY u.id DESC
        LIMIT ? OFFSET ?
    ";

    $dataStmt = $conn->prepare($dataSql);
    if (!$dataStmt) {
        return [[], $total, 'Prepare failed: ' . $conn->error];
    }

    $params2 = $params;
    $params2[] = $limit;
    $params2[] = $offset;
    $types2 = $types . 'ii';
    bindParamsDynamic($dataStmt, $types2, $params2);

    if (!$dataStmt->execute()) {
        $err = 'Execute failed: ' . $dataStmt->error;
        $dataStmt->close();
        return [[], $total, $err];
    }

    $res = $dataStmt->get_result();
    $rows = [];
    while ($row = $res->fetch_assoc()) {
        $rows[] = $row;
    }
    $dataStmt->close();

    return [$rows, $total, ''];
}

function renderRows(array $executives, int $offset, string $csrfToken): string {
    if (empty($executives)) {
        return '<tr><td colspan="6"><div class="empty-state">No Medical Representative found.</div></td></tr>';
    }

    $i = $offset + 1;
    $html = '';

    foreach ($executives as $ex) {
        $statusApproved = ((int)($ex['exec_approved'] ?? 0) === 1);
        $execId = (int)($ex['exec_id'] ?? 0);

        $html .= '<tr>';
        $html .= '<td class="serial">' . $i++ . '</td>';
        $html .= '<td><div class="name-cell"><div class="name-main">' . e($ex['exec_name']) . '</div></div></td>';
        $html .= '<td>' . e($ex['exec_email']) . '</td>';
        $html .= '<td>' . (!empty($ex['manager_name']) ? e($ex['manager_name']) : '<span class="muted">Not assigned</span>') . '</td>';
        $html .= '<td><span class="badge ' . ($statusApproved ? 'approved' : 'pending') . '">' . ($statusApproved ? 'Approved' : 'Pending') . '</span></td>';
        $html .= '<td>';
        $html .= '<form method="post" class="inline-form" onsubmit="return confirm(\'Are you sure you want to remove this medical representative?\');">';
        $html .= '<input type="hidden" name="csrf_token" value="' . e($csrfToken) . '">';
        $html .= '<input type="hidden" name="delete_id" value="' . $execId . '">';
        $html .= '<button type="submit" class="delete-btn"><i class="fa-solid fa-trash"></i> Remove</button>';
        $html .= '</form>';
        $html .= '</td>';
        $html .= '</tr>';
    }

    return $html;
}

function renderPagination(int $page, int $totalPages): string {
    if ($totalPages <= 1) return '';

    $html = '<div class="pagination">';

    if ($page > 1) {
        $html .= '<a href="#" data-page="' . ($page - 1) . '" class="page-link">Prev</a>';
    }

    $start = max(1, $page - 2);
    $end = min($totalPages, $page + 2);

    if ($start > 1) {
        $html .= '<a href="#" data-page="1" class="page-link">1</a>';
        if ($start > 2) {
            $html .= '<span class="dots">…</span>';
        }
    }

    for ($i = $start; $i <= $end; $i++) {
        $active = $i === $page ? ' active' : '';
        $html .= '<a href="#" data-page="' . $i . '" class="page-link' . $active . '">' . $i . '</a>';
    }

    if ($end < $totalPages) {
        if ($end < $totalPages - 1) {
            $html .= '<span class="dots">…</span>';
        }
        $html .= '<a href="#" data-page="' . $totalPages . '" class="page-link">' . $totalPages . '</a>';
    }

    if ($page < $totalPages) {
        $html .= '<a href="#" data-page="' . ($page + 1) . '" class="page-link">Next</a>';
    }

    $html .= '</div>';
    return $html;
}

if (!isset($_SESSION['user_id'])) {
    header("Location: ../login.php");
    exit;
}

$logged_user_id = (int)$_SESSION['user_id'];
$role = roleKey((string)($_SESSION['role'] ?? ''));

if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(16));
}
$csrfToken = $_SESSION['csrf_token'];

$flashMessage = $_SESSION['flash_message'] ?? '';
$flashType = $_SESSION['flash_type'] ?? 'success';
unset($_SESSION['flash_message'], $_SESSION['flash_type']);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_id'])) {
    if (!isset($_POST['csrf_token']) || !hash_equals($csrfToken, (string)$_POST['csrf_token'])) {
        $_SESSION['flash_message'] = 'Invalid request.';
        $_SESSION['flash_type'] = 'error';
        header("Location: " . $_SERVER['PHP_SELF']);
        exit;
    }

    $deleteId = (int)$_POST['delete_id'];

    if (!canDeleteExecutive($conn, $logged_user_id, $role, $deleteId)) {
        $_SESSION['flash_message'] = 'You do not have permission to remove this record.';
        $_SESSION['flash_type'] = 'error';
        header("Location: " . $_SERVER['PHP_SELF']);
        exit;
    }

    $stmt = $conn->prepare("DELETE FROM users WHERE id = ? AND role = 'medical_representative'");
    if (!$stmt) {
        $_SESSION['flash_message'] = 'Delete failed: ' . $conn->error;
        $_SESSION['flash_type'] = 'error';
        header("Location: " . $_SERVER['PHP_SELF']);
        exit;
    }

    $stmt->bind_param("i", $deleteId);
    if ($stmt->execute()) {
        $_SESSION['flash_message'] = 'Medical Representative removed successfully.';
        $_SESSION['flash_type'] = 'success';
    } else {
        $_SESSION['flash_message'] = 'Delete failed: ' . $stmt->error;
        $_SESSION['flash_type'] = 'error';
    }
    $stmt->close();

    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

$q = trim((string)($_GET['q'] ?? ''));
$page = max(1, (int)($_GET['page'] ?? 1));
$limit = 10;

[$executives, $total, $db_error] = fetchExecutives($conn, $role, $logged_user_id, $q, $page, $limit);
$totalPages = max(1, (int)ceil($total / $limit));

if ($page > $totalPages) {
    $page = $totalPages;
    [$executives, $total, $db_error] = fetchExecutives($conn, $role, $logged_user_id, $q, $page, $limit);
}

$offset = ($page - 1) * $limit;

if (isset($_GET['ajax'])) {
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode([
        'rows' => renderRows($executives, $offset, $csrfToken),
        'pagination' => renderPagination($page, $totalPages),
        'error' => $db_error,
        'total' => $total,
        'page' => $page,
        'pages' => $totalPages,
    ]);
    exit;
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Medical Representatives</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<style>
:root{
    --bg:#eef2f7;
    --card:#ffffff;
    --text:#0f172a;
    --muted:#64748b;
    --primary:#1e3a8a;
    --primary-dark:#0f172a;
    --border:#e2e8f0;
    --success-bg:#dcfce7;
    --success-text:#166534;
    --danger-bg:#fee2e2;
    --danger-text:#991b1b;
}

/* RESET */
*{
    margin:0;
    padding:0;
    box-sizing:border-box;
}

/* BODY */
body{
    font-family:Inter,Arial,sans-serif;
    background:linear-gradient(180deg,#eef2f7 0%, #e9eef6 100%);
    color:var(--text);
}

/* ✅ MAIN CONTAINER FIX (IMPORTANT) */
.container{
    margin-left:260px;
    padding:85px 30px 20px; /* ⬅️ pushed down */
    min-height:100vh;
}

/* CARD */
.card{
    background:var(--card);
    border-radius:20px;
    padding:28px;
    box-shadow:0 15px 50px rgba(0,0,0,0.08);
    border:1px solid rgba(148,163,184,.15);
    margin-top:20px;
}

/* HEADER FIX */
.page-head{
    display:flex;
    justify-content:space-between;
    align-items:center;
    margin-bottom:22px;
}

.title-wrap h2{
    font-size:26px;
    font-weight:700;
    color:#0f172a;
}

.title-wrap p{
    font-size:14px;
    color:var(--muted);
    margin-top:6px;
}

/* TOOLBAR */
.toolbar{
    display:flex;
    gap:12px;
    margin:20px 0;
    padding:14px;
    background:#f8fafc;
    border-radius:14px;
    border:1px solid var(--border);
}

/* SEARCH */
.search-box{
    flex:1;
    position:relative;
}

.search-box i{
    position:absolute;
    left:12px;
    top:50%;
    transform:translateY(-50%);
    color:#94a3b8;
}

.search-input{
    width:100%;
    padding:12px 14px 12px 38px;
    border-radius:10px;
    border:1px solid #cbd5e1;
    font-size:14px;
}

.search-input:focus{
    border-color:#2563eb;
    box-shadow:0 0 0 2px rgba(37,99,235,.15);
    outline:none;
}

/* BUTTON */
.btn{
    background:#1e293b;
    color:#fff;
    border:none;
    border-radius:10px;
    padding:11px 16px;
    font-weight:600;
    cursor:pointer;
    display:flex;
    align-items:center;
    gap:6px;
}

/* META */
.meta-line{
    display:flex;
    justify-content:space-between;
    margin-bottom:12px;
    font-size:13px;
    color:var(--muted);
}
/* TABLE WRAP */
.table-wrap{
    background:#fff;
    border-radius:16px;
    padding:0;
    overflow:hidden;
    box-shadow:0 10px 30px rgba(0,0,0,0.06);
}

/* TABLE */
.table{
    width:100%;
    border-collapse:separate;  /* ✅ FIX */
    border-spacing:0;
    table-layout:fixed;        /* ✅ FIX alignment */
}

/* HEADER */
.table thead th{
    background:#1e293b;
    color:#fff;
    padding:16px 18px;
    font-size:13px;
    text-align:left;
    white-space:nowrap;
}

/* FIRST + LAST HEADER ROUND */
.table thead th:first-child{
    border-top-left-radius:14px;
}
.table thead th:last-child{
    border-top-right-radius:14px;
}

/* BODY */
.table tbody td{
    padding:16px 18px;
    font-size:14px;
    color:#0f172a;
    border-bottom:1px solid #f1f5f9;
    vertical-align:middle;
}

/* ROW HOVER */
.table tbody tr:hover td{
    background:#f8fafc;
}

/* COLUMN WIDTH FIX */
.table th:nth-child(1),
.table td:nth-child(1){
    width:60px;
    text-align:center;
}

.table th:nth-child(2){
    width:22%;
}
.table th:nth-child(3){
    width:25%;
}
.table th:nth-child(4){
    width:18%;
}
.table th:nth-child(5){
    width:15%;
}
.table th:nth-child(6){
    width:120px;
    text-align:center;
}

/* ALIGN BUTTON CENTER */
.table td:last-child{
    text-align:center;
}

/* TEXT VISIBILITY FIX */
.name-main{
    font-weight:600;
    font-size:15px;
    color:#0f172a;
}

.table td{
    word-break:break-word;
}

/* BADGE IMPROVE */
.badge{
    padding:7px 14px;
    border-radius:999px;
    font-size:12px;
    font-weight:700;
    display:inline-block;
}

/* DELETE BUTTON IMPROVE */
.delete-btn{
    border:none;
    border-radius:8px;
    padding:8px 14px;
    background:#0f172a;
    color:#fff;
    font-size:13px;
    cursor:pointer;
    transition:0.2s;
}

.delete-btn:hover{
    background:#dc2626;
}

/* MOBILE FIX */
@media (max-width:900px){
    .table{
        min-width:850px; /* scroll instead of breaking */
    }
}

/* PAGINATION */
.pagination{
    display:flex;
    justify-content:center;
    gap:8px;
    margin-top:20px;
}

.page-link{
    padding:8px 12px;
    border-radius:8px;
    border:1px solid #e2e8f0;
    background:#fff;
    font-weight:600;
}

.page-link.active{
    background:#1e293b;
    color:#fff;
}

/* ALERT */
.alert{
    padding:12px;
    border-radius:10px;
    margin-bottom:15px;
}

.alert.success{
    background:#dcfce7;
    color:#166534;
}

.alert.error{
    background:#fee2e2;
    color:#991b1b;
}

/* MOBILE */
@media(max-width:900px){
    .container{
        margin-left:0;
        padding:100px 15px 30px;
    }

    .toolbar{
        flex-direction:column;
    }
}
@keyframes shimmer{
    0%{background-position:200% 0}
    100%{background-position:-200% 0}
}

.loading-row td{
    padding:18px 16px;
}

@media (max-width:900px){
    .container{
        margin-left:0;
        padding:45px 12px 24px;
    }

    .card{
        padding:18px;
        border-radius:18px;
    }

    .title-wrap h2{
        font-size:24px;
    }

    .toolbar{
        flex-direction:column;
        align-items:stretch;
    }

    .search-box{
        min-width:100%;
    }

    .btn{
        width:100%;
        justify-content:center;
    }

    .table{
        min-width:760px;
    }
}
/* STATUS BADGE BASE */
.badge{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    padding:6px 14px;
    border-radius:999px;
    font-size:12px;
    font-weight:700;
    letter-spacing:0.3px;
    min-width:90px;
}

/* ✅ APPROVED (Green Professional) */
.approved{
    background:linear-gradient(135deg,#22c55e,#16a34a);
    color:#fff;
    box-shadow:0 4px 10px rgba(34,197,94,0.25);
}

/* ❌ PENDING (Orange) */
.pending{
    background:linear-gradient(135deg,#f59e0b,#d97706);
    color:#fff;
    box-shadow:0 4px 10px rgba(245,158,11,0.25);
}

/* ❌ REJECTED (Optional) */
.rejected{
    background:linear-gradient(135deg,#ef4444,#dc2626);
    color:#fff;
    box-shadow:0 4px 10px rgba(239,68,68,0.25);
}
</style>
</head>
<body>

<?php if (file_exists("agencysidebar.php")) include "agencysidebar.php"; ?>
<?php if (file_exists("../header.php")) include "../header.php"; ?>

<div class="container">
    <div class="card" style="margin-top:10px;">
        <div class="page-head">
            <div class="title-wrap">
                <h2>Medical Representative & Their Managers</h2>
                <p>Search, browse, remove records, and review assigned managers with live filtering.</p>
            </div>
        </div>

        <?php if ($flashMessage !== ''): ?>
            <div class="alert <?php echo $flashType === 'error' ? 'error' : 'success'; ?>">
                <?php echo e($flashMessage); ?>
            </div>
        <?php endif; ?>

        <?php if(!empty($db_error)): ?>
            <div class="debug">Database error: <?php echo e($db_error); ?></div>
        <?php endif; ?>

        <div class="toolbar">
            <div class="search-box">
                <i class="fa-solid fa-magnifying-glass"></i>
                <input
                    type="search"
                    id="searchInput"
                    class="search-input"
                    placeholder="Search representative or manager..."
                    value="<?php echo e($q); ?>"
                    autocomplete="off"
                >
            </div>
            <a href="<?php echo e($_SERVER['PHP_SELF']); ?>" class="btn" id="resetBtn">
                <i class="fa-solid fa-rotate-left"></i> Reset
            </a>
        </div>

        <div class="meta-line">
            <div id="resultInfo">Showing <?php echo (int)count($executives); ?> of <?php echo (int)$total; ?> records</div>
            <div>Live search enabled</div>
        </div>

        <div class="table-wrap">
            <table class="table" aria-describedby="exec-desc">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Medical Representative</th>
                        <th>Email</th>
                        <th>Sales Manager</th>
                        <th>Status</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody id="tableBody">
                    <?php echo renderRows($executives, $offset, $csrfToken); ?>
                </tbody>
            </table>
        </div>

        <div id="paginationWrap">
            <?php echo renderPagination($page, $totalPages); ?>
        </div>
    </div>
</div>

<script>
(function(){
    const searchInput = document.getElementById('searchInput');
    const tableBody = document.getElementById('tableBody');
    const paginationWrap = document.getElementById('paginationWrap');
    const resultInfo = document.getElementById('resultInfo');
    const resetBtn = document.getElementById('resetBtn');

    let timer = null;

    function setLoading() {
        tableBody.innerHTML = `
            <tr class="loading-row"><td colspan="6"><div class="skeleton"></div></td></tr>
            <tr class="loading-row"><td colspan="6"><div class="skeleton"></div></td></tr>
            <tr class="loading-row"><td colspan="6"><div class="skeleton"></div></td></tr>
        `;
    }

    async function loadData(page = 1) {
        const q = searchInput.value.trim();
        setLoading();

        const url = new URL(window.location.href);
        url.searchParams.set('ajax', '1');
        url.searchParams.set('q', q);
        url.searchParams.set('page', page);

        try {
            const res = await fetch(url.toString(), { headers: { 'X-Requested-With': 'XMLHttpRequest' } });
            const data = await res.json();

            if (data.error) {
                tableBody.innerHTML = `<tr><td colspan="6"><div class="debug">${data.error}</div></td></tr>`;
                paginationWrap.innerHTML = '';
                resultInfo.textContent = 'Something went wrong';
                return;
            }

            tableBody.innerHTML = data.rows;
            paginationWrap.innerHTML = data.pagination || '';
            resultInfo.textContent = `Showing ${data.total === 0 ? 0 : Math.min(<?php echo (int)$limit; ?>, data.total)} of ${data.total} records`;
        } catch (err) {
            tableBody.innerHTML = `<tr><td colspan="6"><div class="debug">Unable to load data.</div></td></tr>`;
            paginationWrap.innerHTML = '';
            resultInfo.textContent = 'Unable to load data';
        }
    }

    searchInput.addEventListener('input', function(){
        clearTimeout(timer);
        timer = setTimeout(() => loadData(1), 250);
    });

    paginationWrap.addEventListener('click', function(e){
        const link = e.target.closest('.page-link');
        if (!link) return;
        e.preventDefault();
        const page = parseInt(link.dataset.page || '1', 10);
        if (page > 0) loadData(page);
    });

    resetBtn.addEventListener('click', function(e){
        if (searchInput.value.trim() !== '') {
            e.preventDefault();
            searchInput.value = '';
            loadData(1);
            history.replaceState(null, '', window.location.p<div class="card">athname);
        }
    });
})();
</script>

</body>
</html>