{% extends "base.html" %}

{% block title %}Visitors Management{% endblock %}
{% block page_id %}visitors{% endblock %}
{% block page_title %}Visitors{% endblock %}
{% block eyebrow %}Management{% endblock %}

{% block content %}
    <section class="panel-stack">
        <article class="glass-card panel-card">
            <div class="panel-header">
                <div>
                    <p class="eyebrow">Visitor Registry</p>
                    <h3>Manage Visitors</h3>
                </div>
                <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap;">
                    <span class="pill">{{ total }} total</span>
                    <button onclick="downloadTemplate()" class="vt-btn">⬇ Template</button>
                    <label class="vt-btn" style="cursor:pointer;margin:0;">
                        ⬆ Import
                        <input type="file" id="importFile" accept=".csv" style="display:none;" onchange="importVisitors(this)">
                    </label>
                    <button onclick="exportVisitors()" class="vt-btn">📤 Export</button>
                    <button onclick="openAddUserModal()" class="vt-btn vt-btn-primary">+ Add visitor</button>
                </div>
            </div>

            <div class="panel-body">
                <form method="GET" action="{{ url_for('admin.visitors_page') }}" class="visitors-controls">
                    <div class="controls-row">
                        <div class="search-box">
                            <input type="text" name="search" placeholder="Search by name, mobile, or email..." value="{{ search }}">
                        </div>
                        <div class="control-group">
                            <label class="control-label">Show</label>
                            <select name="limit" onchange="this.form.submit()">
                                <option value="25" {% if limit == 25 %}selected{% endif %}>25</option>
                                <option value="50" {% if limit == 50 %}selected{% endif %}>50</option>
                                <option value="100" {% if limit == 100 %}selected{% endif %}>100</option>
                            </select>
                        </div>
                    </div>
                </form>

                {% if visitors %}
                <div class="vt-table-wrapper">
                    <table class="vt-table">
                        <thead>
                            <tr>
                                <th>Face Reg. Date</th>
                                <th>Visitor</th>
                                <th>Mobile</th>
                                <th>Email</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for v in visitors %}
                            <tr>
                                <!-- Date: blank if not face-registered -->
                                <td class="vt-date">
                                    {% if v.face_registered_at %}
                                        {{ v.face_registered_at.strftime('%Y-%m-%d') }}
                                    {% else %}
                                        <span class="vt-not-registered">—</span>
                                    {% endif %}
                                </td>

                                <!-- Visitor: photo + name -->
                                <td class="vt-visitor-cell">
                                    <div class="vt-avatar">
                                        {% if v.face_photo %}
                                            <img src="{{ v.face_photo }}" alt="{{ v.name }}" onerror="this.src='/admin/static/no photo.png'">
                                        {% else %}
                                            <img src="/admin/static/no photo.png" alt="No photo">
                                        {% endif %}
                                    </div>
                                    <span class="vt-name">{{ v.name }}</span>
                                </td>

                                <!-- Mobile -->
                                <td class="vt-mobile">{{ v.mobile_number or '—' }}</td>

                                <!-- Email -->
                                <td class="vt-email">{{ v.email or '—' }}</td>

                                <!-- Actions -->
                                <td>
                                    <a href="{{ url_for('admin.edit_visitor', visitor_id=v.id) }}" class="vt-edit-btn">Edit</a>
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>

                {% if total_pages > 1 %}
                <div class="pagination">
                    {% if page > 1 %}
                        <a href="{{ url_for('admin.visitors_page', page=page-1, limit=limit, search=search) }}" class="page-link">&laquo; Previous</a>
                    {% endif %}
                    {% for p in range(1, total_pages + 1) %}
                        {% if p == page %}
                            <span class="page-link active">{{ p }}</span>
                        {% elif p <= 3 or p > total_pages - 2 or (p >= page - 1 and p <= page + 1) %}
                            <a href="{{ url_for('admin.visitors_page', page=p, limit=limit, search=search) }}" class="page-link">{{ p }}</a>
                        {% endif %}
                    {% endfor %}
                    {% if page < total_pages %}
                        <a href="{{ url_for('admin.visitors_page', page=page+1, limit=limit, search=search) }}" class="page-link">Next &raquo;</a>
                    {% endif %}
                </div>
                {% endif %}

                <div class="table-footer">
                    Showing page {{ page }} of {{ total_pages }} ({{ total }} total visitors)
                </div>

                {% else %}
                <div class="empty-state"><p>No visitors found</p></div>
                {% endif %}
            </div>
        </article>
    </section>
{% endblock %}

{% block head %}
<style>
    /* ── Top Buttons ─────────────────────────────────────────────────────── */
    .vt-btn {
        padding: 8px 14px;
        font-size: 13px;
        font-weight: 600;
        border: 1.5px solid #cbd5e1;
        border-radius: 10px;
        background: #ffffff;
        color: #0f2b3d;
        cursor: pointer;
        transition: all 0.2s;
        display: inline-flex;
        align-items: center;
        gap: 4px;
    }
    .vt-btn:hover { background: #f1f5f9; border-color: #94a3b8; }
    .vt-btn-primary {
        background: linear-gradient(135deg, #2c7da0, #1a5f7a);
        color: #ffffff;
        border: none;
    }
    .vt-btn-primary:hover { background: linear-gradient(135deg, #1a5f7a, #0f3a47); color: #ffffff; }

    /* ── Table ───────────────────────────────────────────────────────────── */
    .vt-table-wrapper {
        overflow-x: auto;
        border-radius: 12px;
        border: 1px solid #e2e8f0;
        margin-bottom: 20px;
    }
    .vt-table {
        width: 100%;
        border-collapse: collapse;
        background: #ffffff;
    }
    .vt-table thead tr {
        background: #f8fafc;
        border-bottom: 2px solid #e2e8f0;
    }
    .vt-table th {
        padding: 14px 18px;
        text-align: left;
        font-size: 12px;
        font-weight: 700;
        color: #334155;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        white-space: nowrap;
    }
    .vt-table td {
        padding: 14px 18px;
        border-bottom: 1px solid #f1f5f9;
        vertical-align: middle;
        font-size: 14px;
        color: #0f172a;
    }
    .vt-table tbody tr:last-child td { border-bottom: none; }
    .vt-table tbody tr:hover td { background: #f8fafc; }

    /* Date column */
    .vt-date {
        font-size: 13px;
        font-weight: 600;
        color: #334155;
        white-space: nowrap;
    }
    .vt-not-registered {
        color: #cbd5e1;
        font-size: 18px;
    }

    /* Visitor cell: photo + name */
    .vt-visitor-cell {
        display: flex;
        align-items: center;
        gap: 12px;
        min-width: 180px;
    }
    .vt-avatar {
        width: 42px;
        height: 42px;
        border-radius: 50%;
        overflow: hidden;
        flex-shrink: 0;
        border: 2px solid #e2e8f0;
        background: #f1f5f9;
    }
    .vt-avatar img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        display: block;
    }
    .vt-name {
        font-weight: 700;
        color: #0f172a;
        font-size: 14px;
    }

    /* Mobile / Email */
    .vt-mobile, .vt-email {
        font-size: 13px;
        color: #475569;
    }

    /* Edit button */
    .vt-edit-btn {
        padding: 6px 14px;
        font-size: 13px;
        font-weight: 600;
        border: 1.5px solid #cbd5e1;
        border-radius: 8px;
        background: #ffffff;
        color: #334155;
        text-decoration: none;
        transition: all 0.2s;
        display: inline-block;
        white-space: nowrap;
    }
    .vt-edit-btn:hover { background: #f8fafc; border-color: #2c7da0; color: #2c7da0; }

    /* Pagination */
    .pagination { display: flex; gap: 8px; justify-content: center; margin: 20px 0; flex-wrap: wrap; }
    .page-link { padding: 10px 16px; border: 1.5px solid #cbd5e1; border-radius: 10px; background: #fff; color: #334155; text-decoration: none; font-size: 14px; font-weight: 600; transition: all 0.2s; }
    .page-link:hover { background: #f8fafc; border-color: #2c7da0; }
    .page-link.active { background: #0f2b3d; border-color: #0f2b3d; color: #fff; font-weight: 700; }
    .table-footer { text-align: center; padding: 14px 0; font-size: 13px; color: #64748b; font-weight: 500; }
    .empty-state { text-align: center; padding: 60px 20px; color: #64748b; }

    /* Search controls */
    .visitors-controls { margin-bottom: 24px; }
    .controls-row { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; }
    .search-box { flex: 1; min-width: 200px; }
    .search-box input { width: 100%; padding: 12px 16px; border: 1.5px solid #cbd5e1; border-radius: 12px; background: #ffffff !important; color: #0f172a !important; font-size: 14px; }
    .search-box input:focus { outline: none; border-color: #2c7da0; box-shadow: 0 0 0 3px rgba(44,125,160,0.1); }
    .control-group { display: flex; align-items: center; gap: 8px; }
    .control-label { font-size: 14px; color: #475569; font-weight: 600; white-space: nowrap; }
    .control-group select { padding: 10px 14px; border: 1.5px solid #cbd5e1; border-radius: 10px; background: #ffffff !important; color: #0f172a !important; font-size: 14px; cursor: pointer; }

    /* ── Add Visitor Modal ───────────────────────────────────────────────── */
    .add-user-modal { display: none; position: fixed; z-index: 1000; inset: 0; background: rgba(15,23,42,0.65); backdrop-filter: blur(6px); align-items: center; justify-content: center; }
    .add-user-modal.active { display: flex; }
    .add-user-modal-content { background: #ffffff; border-radius: 16px; width: 90%; max-width: 450px; box-shadow: 0 25px 60px rgba(0,0,0,0.25); overflow: hidden; animation: modalSlideIn 0.25s ease; }
    @keyframes modalSlideIn { from { opacity:0; transform:translateY(-20px) scale(0.97); } to { opacity:1; transform:translateY(0) scale(1); } }
    .add-user-modal-content h3 { margin:0; padding:18px 24px; color:#ffffff !important; font-size:18px; font-weight:700; background:linear-gradient(135deg,#0f2b3d,#1b5e7a); display:flex; align-items:center; justify-content:space-between; }
    .modal-close-btn { background:rgba(255,255,255,0.15); border:1.5px solid rgba(255,255,255,0.4); font-size:16px; color:#ffffff !important; cursor:pointer; width:30px; height:30px; display:flex; align-items:center; justify-content:center; border-radius:8px; padding:0; font-weight:700; }
    .modal-close-btn:hover { background:rgba(255,255,255,0.3); }
    #addUserForm { padding: 24px; }
    .form-field { margin-bottom:16px; display:flex; flex-direction:column; gap:5px; }
    .form-field label { font-size:12px; font-weight:700; text-transform:uppercase; letter-spacing:0.6px; color:#475569 !important; }
    .add-user-modal-content input { width:100% !important; padding:11px 14px !important; border:1.5px solid #e2e8f0 !important; border-radius:10px !important; font-size:14px !important; color:#0f172a !important; background:#f8fafc !important; box-sizing:border-box !important; }
    .add-user-modal-content input:focus { outline:none !important; border-color:#2c7da0 !important; background:#ffffff !important; box-shadow:0 0 0 3px rgba(44,125,160,0.12) !important; }
    .add-user-modal-content input::placeholder { color:#b0bec5 !important; }
    .error-msg { font-size:12px; color:#dc2626 !important; min-height:14px; }
    .helper-text { font-size:12px; color:#64748b !important; min-height:14px; }
    .add-user-modal-buttons { display:flex; gap:10px; padding-top:6px; }
    .add-user-modal-buttons .primary-btn { flex:1; padding:12px 20px; background:#2c7da0 !important; color:#ffffff !important; border:none !important; border-radius:10px; font-size:14px; font-weight:700; cursor:pointer; transition:all 0.2s; }
    .add-user-modal-buttons .primary-btn:hover { background:#1a5f7a !important; transform:translateY(-1px); }
    .add-user-modal-buttons .secondary-btn { flex:1; padding:12px 20px; background:#ffffff; color:#475569 !important; border:1.5px solid #cbd5e1; border-radius:10px; font-size:14px; font-weight:600; cursor:pointer; transition:all 0.2s; }
    .add-user-modal-buttons .secondary-btn:hover { background:#f1f5f9; }

    /* Popups */
    .visitor-popup { position:fixed; top:20px; right:20px; background:white; border-radius:12px; padding:16px 20px; min-width:300px; max-width:380px; box-shadow:0 20px 25px -5px rgba(0,0,0,0.15); z-index:10000; opacity:0; transform:translateX(400px); transition:all 0.3s ease; display:flex; gap:12px; align-items:flex-start; }
    .visitor-popup.show { opacity:1; transform:translateX(0); }
    .popup-icon { width:40px; height:40px; border-radius:50%; display:flex; align-items:center; justify-content:center; font-size:18px; flex-shrink:0; }
    .success-icon { background:#d1fae5; color:#059669; }
    .error-icon { background:#fee2e2; color:#dc2626; }
    .popup-title { font-weight:700; font-size:14px; color:#0f172a; margin-bottom:2px; }
    .popup-message { font-size:13px; color:#475569; }
</style>

<!-- Add User Modal -->
<div id="addUserModal" class="add-user-modal">
    <div class="add-user-modal-content">
        <h3>
            👤 Add New Visitor
            <button class="modal-close-btn" onclick="closeAddUserModal()">&times;</button>
        </h3>
        <form id="addUserForm" onsubmit="return false;">
            <div class="form-field">
                <label>Name *</label>
                <input type="text" id="add_user_name" placeholder="e.g. John Doe" required oninput="validateName(this)">
                <span class="error-msg" id="name-error"></span>
            </div>
            <div class="form-field">
                <label>Mobile Number (10 digits)</label>
                <input type="text" id="add_user_mobile" placeholder="e.g. 9876543210" maxlength="10" inputmode="numeric" oninput="validateMobile(this)">
                <span class="helper-text" id="mobile-helper"></span>
                <span class="error-msg" id="mobile-error"></span>
            </div>
            <div class="form-field">
                <label>Email</label>
                <input type="email" id="add_user_email" placeholder="e.g. john@example.com" oninput="validateEmailField(this)">
                <span class="helper-text" id="email-helper"></span>
                <span class="error-msg" id="email-error"></span>
            </div>
            <div class="add-user-modal-buttons">
                <button type="button" class="secondary-btn" onclick="closeAddUserModal()">Cancel</button>
                <button type="button" class="primary-btn" onclick="saveUser()">Save Visitor</button>
            </div>
        </form>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
// ── Add Visitor Modal ─────────────────────────────────────────────────────
function openAddUserModal() {
    document.getElementById('addUserModal').classList.add('active');
    setTimeout(() => document.getElementById('add_user_name').focus(), 100);
}
function closeAddUserModal() {
    document.getElementById('addUserModal').classList.remove('active');
    document.getElementById('addUserForm').reset();
    ['name-error','mobile-error','email-error','mobile-helper','email-helper'].forEach(id => {
        const el = document.getElementById(id);
        if (el) el.textContent = '';
    });
}

function validateName(input) {
    const errorEl = document.getElementById('name-error');
    input.value = input.value.replace(/[^a-zA-Z\s]/g, '');
    errorEl.textContent = '';
}

function validateMobile(input) {
    input.value = input.value.replace(/[^0-9]/g, '');
    const helperEl = document.getElementById('mobile-helper');
    const errorEl = document.getElementById('mobile-error');
    if (input.value.length === 0) {
        helperEl.textContent = ''; input.style.borderColor = '';
    } else if (input.value.length < 10) {
        helperEl.textContent = `${10 - input.value.length} more digits needed`;
        helperEl.style.color = '#f97316'; input.style.borderColor = '#f97316';
    } else {
        helperEl.textContent = '✓ Valid'; helperEl.style.color = '#059669'; input.style.borderColor = '#059669';
    }
    errorEl.textContent = '';
}

function validateEmailField(input) {
    const helperEl = document.getElementById('email-helper');
    const errorEl = document.getElementById('email-error');
    const ok = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(input.value);
    if (!input.value) { helperEl.textContent = ''; errorEl.textContent = ''; input.style.borderColor = ''; }
    else if (!ok) { errorEl.textContent = 'Invalid email format'; helperEl.textContent = ''; input.style.borderColor = '#dc2626'; }
    else { helperEl.textContent = '✓ Valid'; helperEl.style.color = '#059669'; errorEl.textContent = ''; input.style.borderColor = '#059669'; }
}

function saveUser() {
    const name   = document.getElementById('add_user_name').value.trim();
    const mobile = document.getElementById('add_user_mobile').value.trim();
    const email  = document.getElementById('add_user_email').value.trim();
    if (!name) { showPopup('error', 'Name is required'); return; }
    if (mobile && mobile.length !== 10) { showPopup('error', 'Mobile number must be 10 digits'); return; }
    if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) { showPopup('error', 'Please enter a valid email'); return; }
    if (!email && !mobile) { showPopup('error', 'Please provide email or mobile number'); return; }

    const btn = document.querySelector('#addUserForm .primary-btn');
    btn.disabled = true; btn.textContent = 'Saving...';

    fetch('/admin/api/visitors/add', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name, mobile, email })
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            showPopup('success', data.message || 'Visitor added successfully');
            setTimeout(() => { closeAddUserModal(); window.location.reload(); }, 1500);
        } else {
            showPopup('error', data.message || 'Error adding visitor');
        }
    })
    .catch(() => showPopup('error', 'Error adding visitor. Please try again.'))
    .finally(() => { btn.disabled = false; btn.textContent = 'Save Visitor'; });
}

window.onclick = e => { if (e.target.id === 'addUserModal') closeAddUserModal(); };
document.addEventListener('DOMContentLoaded', () => {
    document.getElementById('addUserForm').addEventListener('keypress', e => {
        if (e.key === 'Enter' && e.target.tagName === 'INPUT') saveUser();
    });
});

// ── Popup helper ──────────────────────────────────────────────────────────
function showPopup(type, message) {
    const popup = document.createElement('div');
    popup.className = 'visitor-popup';
    popup.innerHTML = `
        <div class="popup-icon ${type === 'success' ? 'success-icon' : 'error-icon'}">${type === 'success' ? '✓' : '✕'}</div>
        <div>
            <div class="popup-title">${type === 'success' ? 'Success' : 'Error'}</div>
            <div class="popup-message">${message}</div>
        </div>`;
    document.body.appendChild(popup);
    setTimeout(() => popup.classList.add('show'), 10);
    setTimeout(() => { popup.classList.remove('show'); setTimeout(() => popup.remove(), 300); }, type === 'success' ? 2000 : 3000);
}

// ── Template Download ─────────────────────────────────────────────────────
function downloadTemplate() {
    const csv = 'Name,Mobile Number,Email\nJohn Doe,9876543210,john@example.com\n';
    const blob = new Blob([csv], { type: 'text/csv' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a'); a.href = url; a.download = 'visitors_template.csv'; a.click();
    URL.revokeObjectURL(url);
}

// ── Import CSV ────────────────────────────────────────────────────────────
function importVisitors(input) {
    const file = input.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = async function(e) {
        const lines = e.target.result.trim().split('\n');
        if (lines.length < 2) { showPopup('error', 'CSV is empty or has no data rows.'); return; }
        const headers = lines[0].toLowerCase().split(',').map(h => h.trim());
        const nameIdx   = headers.indexOf('name');
        const mobileIdx = headers.findIndex(h => h.includes('mobile'));
        const emailIdx  = headers.indexOf('email');
        if (nameIdx === -1) { showPopup('error', 'CSV must have a "Name" column.'); return; }
        let ok = 0, fail = 0;
        for (let i = 1; i < lines.length; i++) {
            const cols = lines[i].split(',').map(c => c.trim().replace(/^"|"$/g, ''));
            const name   = cols[nameIdx] || '';
            const mobile = mobileIdx >= 0 ? cols[mobileIdx] || '' : '';
            const email  = emailIdx  >= 0 ? cols[emailIdx]  || '' : '';
            if (!name) continue;
            try {
                const res = await fetch('/admin/api/visitors/add', { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({name, mobile, email}) });
                const d = await res.json();
                if (d.success) ok++; else fail++;
            } catch { fail++; }
        }
        input.value = '';
        showPopup('success', `Imported ${ok} visitors${fail > 0 ? `, ${fail} failed` : ''}.`);
        setTimeout(() => window.location.reload(), 1800);
    };
    reader.readAsText(file);
}

// ── Export CSV ────────────────────────────────────────────────────────────
function exportVisitors() {
    fetch('/admin/api/visitors/export')
        .then(r => r.json())
        .then(data => {
            if (!data.visitors?.length) { showPopup('error', 'No visitors to export.'); return; }
            const rows = [['ID','Name','Mobile Number','Email']];
            data.visitors.forEach(v => rows.push([v.id, v.name, v.mobile_number||'', v.email||'']));
            const csv  = rows.map(r => r.map(c => `"${c}"`).join(',')).join('\n');
            const blob = new Blob([csv], { type: 'text/csv' });
            const url  = URL.createObjectURL(blob);
            const a    = document.createElement('a');
            a.href = url; a.download = `visitors_${new Date().toISOString().slice(0,10)}.csv`; a.click();
            URL.revokeObjectURL(url);
        })
        .catch(() => showPopup('error', 'Failed to export visitors.'));
}
</script>
{% endblock %}