{% extends "base.html" %}

{% block title %}Consent Management{% endblock %}
{% block page_id %}consent{% endblock %}
{% block page_title %}Consent{% endblock %}
{% block eyebrow %}Management{% endblock %}

{% block head %}
<style>
    /* ── Role Buttons ───────────────────────────────────────────────────── */
    .consent-role-bar {
        display: flex;
        gap: 12px;
        flex-wrap: wrap;
        margin-bottom: 24px;
    }
    .consent-role-btn {
        padding: 12px 28px;
        border-radius: 12px;
        font-size: 14px;
        font-weight: 700;
        cursor: pointer;
        border: 2px solid transparent;
        transition: all 0.2s ease;
        display: flex;
        align-items: center;
        gap: 8px;
    }
    .consent-role-btn.visitor     { background: #dbeafe; color: #1e40af; border-color: #93c5fd; }
    .consent-role-btn.admin       { background: #fef3c7; color: #92400e; border-color: #fcd34d; }
    .consent-role-btn.photographer{ background: #d1fae5; color: #065f46; border-color: #6ee7b7; }
    .consent-role-btn:hover { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0,0,0,0.1); }

    /* ── Stat Cards ─────────────────────────────────────────────────────── */
    .consent-stats {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 16px;
        margin-bottom: 24px;
    }
    .consent-stat-card {
        background: #ffffff;
        border-radius: 14px;
        border: 1px solid #e2e8f0;
        padding: 20px 24px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.05);
    }
    .consent-stat-label { font-size: 12px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; color: #64748b; display: block; margin-bottom: 8px; }
    .consent-stat-value { font-size: 36px; font-weight: 800; color: #0f172a; line-height: 1; display: block; }
    .consent-stat-sub   { font-size: 12px; color: #94a3b8; margin-top: 6px; display: block; }

    /* ── Logs Section ───────────────────────────────────────────────────── */
    .consent-controls {
        display: flex;
        align-items: center;
        gap: 12px;
        flex-wrap: wrap;
        margin-bottom: 16px;
    }
    .consent-search-form {
        display: flex;
        align-items: center;
        gap: 8px;
        flex: 1;
    }
    .consent-search-input {
        flex: 1;
        max-width: 360px;
        padding: 10px 16px;
        border: 1.5px solid #cbd5e1;
        border-radius: 10px;
        font-size: 14px;
        color: #0f172a;
        background: #ffffff;
    }
    .consent-search-input:focus { outline: none; border-color: #2c7da0; box-shadow: 0 0 0 3px rgba(44,125,160,0.1); }
    .consent-search-input::placeholder { color: #94a3b8; }
    .consent-search-btn {
        padding: 10px 18px; background: #2c7da0; color: #ffffff;
        border: none; border-radius: 10px; font-size: 14px; font-weight: 700; cursor: pointer;
    }
    .consent-search-btn:hover { background: #1a5f7a; }
    .consent-clear-link {
        padding: 10px 14px; background: #f1f5f9; color: #64748b;
        border: 1.5px solid #cbd5e1; border-radius: 10px; font-size: 14px;
        font-weight: 600; text-decoration: none;
    }
    .consent-show { display: flex; align-items: center; gap: 8px; font-size: 14px; font-weight: 600; color: #475569; flex-shrink: 0; }
    .consent-show select { padding: 8px 12px; border: 1.5px solid #cbd5e1; border-radius: 10px; background: #ffffff; font-size: 14px; cursor: pointer; }

    /* Table */
    .consent-table-wrap { overflow-x: auto; border-radius: 12px; border: 1px solid #e2e8f0; background: #ffffff; }
    .consent-table { width: 100%; border-collapse: collapse; font-size: 14px; }
    .consent-table thead tr { background: #f8fafc; border-bottom: 2px solid #e2e8f0; }
    .consent-table th { padding: 13px 18px; text-align: left; font-size: 12px; font-weight: 700; color: #334155; text-transform: uppercase; letter-spacing: 0.5px; white-space: nowrap; }
    .consent-table td { padding: 13px 18px; border-bottom: 1px solid #f1f5f9; vertical-align: middle; }
    .consent-table tbody tr:last-child td { border-bottom: none; }
    .consent-table tbody tr:hover td { background: #f8fafc; }
    .agreed-badge { display: inline-block; padding: 4px 12px; border-radius: 20px; font-size: 12px; font-weight: 700; }
    .agreed-yes { background: #dcfce7; color: #15803d; }
    .agreed-no  { background: #fee2e2; color: #b91c1c; }

    /* Pagination */
    .consent-pagination { display: flex; gap: 8px; justify-content: center; margin-top: 20px; flex-wrap: wrap; }
    .cp-link { padding: 9px 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; }
    .cp-link:hover { background: #f8fafc; border-color: #2c7da0; }
    .cp-link.active { background: #0f2b3d; border-color: #0f2b3d; color: #fff; }
    .consent-footer { text-align: center; padding: 12px 0 4px; font-size: 13px; color: #64748b; }

    /* ── Consent Modal ──────────────────────────────────────────────────── */
    .cm-modal {
        display: none; position: fixed; inset: 0;
        background: rgba(15,23,42,0.65); backdrop-filter: blur(6px);
        z-index: 1000; align-items: center; justify-content: center; padding: 16px;
    }
    .cm-modal.active { display: flex; }
    .cm-modal-content {
        background: #ffffff; border-radius: 18px; width: 100%; max-width: 580px;
        box-shadow: 0 25px 60px rgba(0,0,0,0.25); overflow: hidden;
        animation: cmIn 0.2s ease;
    }
    @keyframes cmIn { from { opacity:0; transform:translateY(-16px) scale(0.97); } to { opacity:1; transform:translateY(0) scale(1); } }
    .cm-modal-header {
        padding: 16px 20px; display: flex; align-items: center; justify-content: space-between;
        background: linear-gradient(135deg, #0f2b3d, #1b5e7a);
    }
    .cm-modal-header h3 { margin: 0; color: #ffffff !important; font-size: 16px; font-weight: 700; }
    .cm-modal-close {
        background: rgba(255,255,255,0.15); border: 1.5px solid rgba(255,255,255,0.3);
        color: #ffffff; width: 32px; height: 32px; border-radius: 8px;
        cursor: pointer; font-size: 18px; display: flex; align-items: center; justify-content: center; padding: 0;
    }
    .cm-modal-close:hover { background: rgba(255,255,255,0.3); }
    .cm-modal-body { padding: 20px; }
    .cm-modal-body label { font-size: 12px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; color: #475569; display: block; margin-bottom: 8px; }
    .cm-modal-body textarea {
        width: 100%; padding: 12px 14px; border: 1.5px solid #e2e8f0; border-radius: 10px;
        font-size: 14px; color: #0f172a; background: #f8fafc; resize: vertical;
        min-height: 140px; font-family: inherit; box-sizing: border-box; line-height: 1.6;
    }
    .cm-modal-body textarea:focus { outline: none; border-color: #2c7da0; background: #ffffff; box-shadow: 0 0 0 3px rgba(44,125,160,0.12); }
    .cm-modal-buttons { display: flex; gap: 10px; padding-top: 14px; }
    .cm-save-btn { flex:1; padding:12px 20px; background:#2c7da0; color:blueviolet   !important; border:none; border-radius:10px; font-size:14px; font-weight:700; cursor:pointer; transition:all 0.2s; }
    .cm-save-btn:hover { background:#1a5f7a; }
    .cm-cancel-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; }
    .cm-cancel-btn:hover { background:#f1f5f9; }

    @media (max-width: 768px) {
        .consent-stats { grid-template-columns: 1fr; }
        .consent-role-bar { flex-direction: column; }
        .cm-modal-content { max-width: 100%; }
    }
</style>
{% endblock %}

{% block content %}
<section class="panel-stack">
    <article class="glass-card panel-card">
        <div class="panel-header">
            <div>
                <p class="eyebrow">Consent</p>
                <h3>Manage Consent</h3>
            </div>
        </div>

        <div class="panel-body">

            <!-- Role Buttons -->
            <div class="consent-role-bar">
                <button class="consent-role-btn visitor" onclick="openConsentModal('visitor')">
                    👥 Visitor Consent
                </button>
                <button class="consent-role-btn admin" onclick="openConsentModal('admin')">
                    🔐 Admin Consent
                </button>
                <button class="consent-role-btn photographer" onclick="openConsentModal('photographer')">
                    📷 Photographer Consent
                </button>
            </div>

            <!-- Stat Cards -->
            <div class="consent-stats">
                <div class="consent-stat-card">
                    <span class="consent-stat-label">Total Visitors</span>
                    <span class="consent-stat-value">{{ total_visitors }}</span>
                    <span class="consent-stat-sub">visitors_registration table</span>
                </div>
                <div class="consent-stat-card">
                    <span class="consent-stat-label">Consented Users</span>
                    <span class="consent-stat-value">{{ consented_users }}</span>
                    <span class="consent-stat-sub">agreed in consent_logs</span>
                </div>
                <div class="consent-stat-card">
                    <span class="consent-stat-label">Remaining</span>
                    <span class="consent-stat-value">{{ total_visitors - consented_users }}</span>
                    <span class="consent-stat-sub">Total Visitors − Consented</span>
                </div>
            </div>

            <!-- Controls -->
            <div class="consent-controls">
                <form method="GET" action="{{ url_for('admin.consent_page') }}" class="consent-search-form">
                    <input type="text" name="search" value="{{ search }}" placeholder="Search by username or email..." class="consent-search-input" autocomplete="off">
                    <input type="hidden" name="limit" value="{{ limit }}">
                    <input type="hidden" name="page" value="1">
                    <button type="submit" class="consent-search-btn">Search</button>
                    {% if search %}
                    <a href="{{ url_for('admin.consent_page', limit=limit) }}" class="consent-clear-link">Clear</a>
                    {% endif %}
                </form>
                <form method="GET" action="{{ url_for('admin.consent_page') }}" class="consent-show">
                    <label>Show</label>
                    <select name="limit" onchange="this.form.submit()">
                        <option value="10"  {% if limit == 10  %}selected{% endif %}>10</option>
                        <option value="25"  {% if limit == 25  %}selected{% endif %}>25</option>
                        <option value="50"  {% if limit == 50  %}selected{% endif %}>50</option>
                    </select>
                    <input type="hidden" name="search" value="{{ search }}">
                    <input type="hidden" name="page" value="1">
                </form>
            </div>

            <!-- Consent Logs Table -->
            {% if logs %}
            <div class="consent-table-wrap">
                <table class="consent-table">
                    <thead>
                        <tr>
                            <th>Sl No</th>
                            <th>Username</th>
                            <th>Email</th>
                            <th>Agreed</th>
                            <th>Agreed At</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for log in logs %}
                        <tr>
                            <td style="color:#94a3b8;font-weight:700;">{{ loop.index + ((page-1)*limit) }}</td>
                            <td style="font-weight:600;color:#0f172a;">{{ log.username or '—' }}</td>
                            <td style="color:#475569;font-size:13px;">{{ log.user_email or '—' }}</td>
                            <td>
                                <span class="agreed-badge {% if log.agreed %}agreed-yes{% else %}agreed-no{% endif %}">
                                    {% if log.agreed %}✓ Yes{% else %}✗ No{% endif %}
                                </span>
                            </td>
                            <td style="font-size:13px;color:#64748b;">
                                {{ log.agreed_at.strftime('%Y-%m-%d %H:%M') if log.agreed_at else '—' }}
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>

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

            <div class="consent-footer">Showing page {{ page }} of {{ total_pages }} ({{ total_logs }} total logs)</div>

            {% else %}
            <div style="text-align:center;padding:50px 20px;color:#94a3b8;">
                <p style="font-size:18px;margin-bottom:6px;">No consent logs found</p>
                <p style="font-size:14px;">{% if search %}No results for "{{ search }}"{% else %}No users have submitted consent yet{% endif %}</p>
            </div>
            {% endif %}

        </div>
    </article>
</section>

<!-- CONSENT MESSAGE MODAL -->
<div id="consentModal" class="cm-modal">
    <div class="cm-modal-content">
        <div class="cm-modal-header">
            <h3 id="cmModalTitle">Consent Message</h3>
            <button class="cm-modal-close" onclick="closeConsentModal()">&times;</button>
        </div>
        <div class="cm-modal-body">
            <label id="cmRoleLabel">ROLE CONSENT MESSAGE</label>
            <textarea id="cmTextarea" placeholder="Enter consent message..."></textarea>
            <div class="cm-modal-buttons">
                <button class="cm-cancel-btn" onclick="closeConsentModal()">Cancel</button>
                <button class="cm-save-btn" onclick="saveConsentMsg()">Save</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    let _currentRole = '';

    const roleLabels = {
        visitor:      '👥 Visitor Consent Message',
        admin:        '🔐 Admin Consent Message',
        photographer: '📷 Photographer Consent Message',
    };

    // ── Open modal, load existing message ────────────────────────────────
    async function openConsentModal(role) {
        _currentRole = role;
        document.getElementById('cmModalTitle').textContent = roleLabels[role];
        document.getElementById('cmRoleLabel').textContent  = role.toUpperCase() + ' CONSENT MESSAGE';
        document.getElementById('cmTextarea').value         = 'Loading...';
        document.getElementById('consentModal').classList.add('active');

        try {
            const res  = await fetch(`/admin/api/consent/message/${role}`);
            const data = await res.json();
            document.getElementById('cmTextarea').value = data.consent_msg || '';
            document.getElementById('cmTextarea').focus();
        } catch (e) {
            document.getElementById('cmTextarea').value = '';
        }
    }

    function closeConsentModal() {
        document.getElementById('consentModal').classList.remove('active');
        _currentRole = '';
    }

    // ── Save consent message ──────────────────────────────────────────────
    async function saveConsentMsg() {
        const msg = document.getElementById('cmTextarea').value.trim();
        if (!msg) { showToast('error', 'Consent message cannot be empty'); return; }

        const btn = document.querySelector('.cm-save-btn');
        btn.disabled = true; btn.textContent = 'Saving...';

        try {
            const res  = await fetch(`/admin/api/consent/message/${_currentRole}`, {
                method:  'POST',
                headers: { 'Content-Type': 'application/json' },
                body:    JSON.stringify({ consent_msg: msg })
            });
            const data = await res.json();
            if (data.success) {
                showToast('success', data.message);
                closeConsentModal();
            } else {
                showToast('error', data.error || 'Failed to save');
            }
        } catch (e) {
            showToast('error', 'Network error. Please try again.');
        } finally {
            btn.disabled = false; btn.textContent = 'Save';
        }
    }

    // ── Toast ─────────────────────────────────────────────────────────────
    function showToast(type, message) {
        const t = document.createElement('div');
        t.style.cssText = `
            position:fixed; top:20px; right:20px; z-index:9999;
            padding:14px 20px; border-radius:10px; font-size:14px; font-weight:600;
            color:#fff; box-shadow:0 4px 12px rgba(0,0,0,0.2);
            background:${type==='success' ? 'linear-gradient(135deg,#16a34a,#15803d)' : 'linear-gradient(135deg,#dc2626,#b91c1c)'};
            animation: slideIn 0.3s ease;
        `;
        t.textContent = message;
        document.body.appendChild(t);
        setTimeout(() => t.remove(), 4000);
    }

    // Backdrop & Escape close
    document.getElementById('consentModal').addEventListener('click', e => {
        if (e.target === document.getElementById('consentModal')) closeConsentModal();
    });
    document.addEventListener('keydown', e => {
        if (e.key === 'Escape') closeConsentModal();
    });
</script>
{% endblock %}