{% extends "admin/layout.twig" %}

{% block content %}
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 28px;">
    <div>
        <h2 style="font-size: 1.5rem; color: #0f172a; margin-bottom: 8px;">Contact Submissions</h2>
        <p style="color: #64748b;">Manage and respond to contact form messages</p>
    </div>
    
    <!-- Stats Badge -->
    <div style="padding: 10px 20px; background: #f0eff7; border-radius: 30px; display: flex; align-items: center; gap: 10px;">
        <i class="fas fa-envelope" style="color: #393186;"></i>
        <span style="color: #393186; font-weight: 700;">{{ contacts|length }}</span>
        <span style="color: #64748b;">total messages</span>
    </div>
</div>

<!-- Filters Card -->
<div style="background: white; border-radius: 20px; padding: 20px; margin-bottom: 24px; border: 1px solid #edf2f7; display: flex; gap: 16px; align-items: center; flex-wrap: wrap;">
    <div style="position: relative; flex: 1; min-width: 250px;">
        <i class="fas fa-search" style="position: absolute; left: 16px; top: 50%; transform: translateY(-50%); color: #94a3b8;"></i>
        <input type="text" id="searchInput" placeholder="Search by name, email, phone or message..." 
               style="width: 100%; padding: 12px 16px 12px 46px; border: 1.5px solid #edf2f7; border-radius: 14px; font-size: 0.95rem; background: #fafbfc; transition: all 0.2s;"
               onfocus="this.style.borderColor='#393186'; this.style.background='white';"
               onblur="this.style.borderColor='#edf2f7'; this.style.background='#fafbfc';">
    </div>
    
    <div style="display: flex; gap: 12px;">
        <select id="serviceFilter" 
                style="padding: 12px 20px; border: 1.5px solid #edf2f7; border-radius: 14px; font-size: 0.95rem; color: #1e293b; background: #fafbfc; cursor: pointer; outline: none; min-width: 160px;"
                onfocus="this.style.borderColor='#393186'; this.style.background='white';"
                onblur="this.style.borderColor='#edf2f7'; this.style.background='#fafbfc';">
            <option value="all">All Services</option>
            <option value="ac-installation">AC Installation</option>
            <option value="ac-repair">AC Repair</option>
            <option value="waterproofing">Waterproofing</option>
            <option value="painting">Painting</option>
            <option value="maintenance">Maintenance</option>
            <option value="other">Other</option>
        </select>
        
        <select id="dateFilter" 
                style="padding: 12px 20px; border: 1.5px solid #edf2f7; border-radius: 14px; font-size: 0.95rem; color: #1e293b; background: #fafbfc; cursor: pointer; outline: none; min-width: 150px;"
                onfocus="this.style.borderColor='#393186'; this.style.background='white';"
                onblur="this.style.borderColor='#edf2f7'; this.style.background='#fafbfc';">
            <option value="all">All Dates</option>
            <option value="today">Today</option>
            <option value="week">This Week</option>
            <option value="month">This Month</option>
        </select>
        
        <button onclick="exportContacts()" 
                style="display: inline-flex; align-items: center; gap: 8px; padding: 12px 24px; background: white; color: #393186; border: 1.5px solid #393186; border-radius: 14px; font-weight: 600; font-size: 0.95rem; cursor: pointer; transition: all 0.2s;"
                onmouseover="this.style.background='#f0eff7';"
                onmouseout="this.style.background='white';">
            <i class="fas fa-download"></i>
            Export
        </button>
    </div>
</div>

<!-- Contacts Table -->
<div class="table-container" style="background: white; border-radius: 24px; border: 1px solid #edf2f7; overflow-x: auto;">
    <table style="width: 100%; border-collapse: collapse; min-width: 1200px;">
        <thead>
            <tr style="background: #f8fafc; border-bottom: 1px solid #edf2f7;">
                <th style="padding: 18px 24px; text-align: left; font-size: 0.85rem; font-weight: 600; color: #393186; text-transform: uppercase; letter-spacing: 0.5px;">Name</th>
                <th style="padding: 18px 24px; text-align: left; font-size: 0.85rem; font-weight: 600; color: #393186; text-transform: uppercase; letter-spacing: 0.5px;">Email</th>
                <th style="padding: 18px 24px; text-align: left; font-size: 0.85rem; font-weight: 600; color: #393186; text-transform: uppercase; letter-spacing: 0.5px;">Country</th>
                <th style="padding: 18px 24px; text-align: left; font-size: 0.85rem; font-weight: 600; color: #393186; text-transform: uppercase; letter-spacing: 0.5px;">Phone</th>
                <th style="padding: 18px 24px; text-align: left; font-size: 0.85rem; font-weight: 600; color: #393186; text-transform: uppercase; letter-spacing: 0.5px;">Service</th>
                <th style="padding: 18px 24px; text-align: left; font-size: 0.85rem; font-weight: 600; color: #393186; text-transform: uppercase; letter-spacing: 0.5px;">Message</th>
                <th style="padding: 18px 24px; text-align: left; font-size: 0.85rem; font-weight: 600; color: #393186; text-transform: uppercase; letter-spacing: 0.5px;">Date</th>
                <th style="padding: 18px 24px; text-align: center; font-size: 0.85rem; font-weight: 600; color: #393186; text-transform: uppercase; letter-spacing: 0.5px;">Action</th>
            </tr>
        </thead>
        <tbody>
            {% for contact in contacts %}
            <tr style="border-bottom: 1px solid #edf2f7; transition: background 0.2s;"
                onmouseover="this.style.background='#fafafc';"
                onmouseout="this.style.background='transparent';">
                
                <td style="padding: 20px 24px;">
                    <div style="display: flex; align-items: center; gap: 12px;">
                        <div style="width: 40px; height: 40px; background: #f0eff7; border-radius: 12px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas fa-user" style="color: #393186; font-size: 1rem;"></i>
                        </div>
                        <div>
                            <div style="font-weight: 600; color: #0f172a;">{{ contact.name }}</div>
                        </div>
                    </div>
                </td>
                
                <td style="padding: 20px 24px;">
                    <a href="mailto:{{ contact.email }}" style="color: #393186; text-decoration: none; display: flex; align-items: center; gap: 6px; font-weight: 500;"
                       onmouseover="this.style.textDecoration='underline';"
                       onmouseout="this.style.textDecoration='none';">
                        <i class="fas fa-envelope" style="font-size: 0.85rem; opacity: 0.7;"></i>
                        {{ contact.email }}
                    </a>
                </td>
                
                <!-- COUNTRY CODE COLUMN -->
                <td style="padding: 20px 24px;">
                    {% if contact.country_code %}
                    <span style="display: inline-flex; align-items: center; gap: 6px; background: #f0eff7; color: #393186; padding: 6px 12px; border-radius: 30px; font-weight: 600; font-size: 0.85rem;">
                        <i class="fas fa-globe"></i>
                        {{ contact.country_code }}
                    </span>
                    {% else %}
                    <span style="color: #94a3b8;">—</span>
                    {% endif %}
                </td>
                
                <!-- PHONE COLUMN WITH FULL NUMBER -->
                <td style="padding: 20px 24px;">
                    {% if contact.phone %}
                    <a href="tel:{{ contact.country_code }}{{ contact.phone }}" style="color: #475569; text-decoration: none; display: flex; flex-direction: column; gap: 2px;"
                       onmouseover="this.style.color='#393186';"
                       onmouseout="this.style.color='#475569';">
                        <span style="display: flex; align-items: center; gap: 6px;">
                            <i class="fas fa-phone-alt" style="font-size: 0.85rem; color: #393186; opacity: 0.7;"></i>
                            <span style="font-weight: 500;">{{ contact.country_code }} {{ contact.phone }}</span>
                        </span>
                    </a>
                    {% else %}
                    <span style="color: #94a3b8;">—</span>
                    {% endif %}
                </td>
                
                <!-- SERVICE COLUMN -->
                <td style="padding: 20px 24px;">
                    {% if contact.service %}
                        {% set service_name = '' %}
                        {% if contact.service == 'ac-installation' %}
                            {% set service_name = 'AC Installation' %}
                        {% elseif contact.service == 'ac-repair' %}
                            {% set service_name = 'AC Repair' %}
                        {% elseif contact.service == 'waterproofing' %}
                            {% set service_name = 'Waterproofing' %}
                        {% elseif contact.service == 'painting' %}
                            {% set service_name = 'Painting' %}
                        {% elseif contact.service == 'maintenance' %}
                            {% set service_name = 'Maintenance' %}
                        {% else %}
                            {% set service_name = contact.service|replace({'-': ' '})|title %}
                        {% endif %}
                        
                        <span style="display: inline-flex; align-items: center; gap: 6px; background: #f0eff7; color: #393186; padding: 6px 14px; border-radius: 30px; font-weight: 600; font-size: 0.8rem;">
                            <i class="fas fa-tools"></i>
                            {{ service_name }}
                        </span>
                    {% else %}
                        <span style="color: #94a3b8;">—</span>
                    {% endif %}
                </td>
                
                <td style="padding: 20px 24px;">
                    <div style="max-width: 200px;">
                        <p style="color: #475569; margin-bottom: 6px; line-height: 1.5; font-size: 0.95rem;">
                            {{ contact.message|slice(0, 50) }}...
                        </p>
                        <button onclick="viewFullMessage('{{ contact.message|escape('js') }}', '{{ contact.name|escape('js') }}', '{{ contact.email|escape('js') }}', '{{ contact.country_code|escape('js') }}', '{{ contact.phone|escape('js') }}', '{{ contact.service|escape('js') }}')"
                                style="background: none; border: none; color: #393186; font-size: 0.8rem; font-weight: 600; cursor: pointer; padding: 0; display: inline-flex; align-items: center; gap: 4px;"
                                onmouseover="this.style.textDecoration='underline';"
                                onmouseout="this.style.textDecoration='none';">
                            Read full message
                            <i class="fas fa-arrow-right" style="font-size: 0.7rem;"></i>
                        </button>
                    </div>
                </td>
                
                <td style="padding: 20px 24px;">
                    <div style="display: flex; flex-direction: column; gap: 4px;">
                        <span style="font-weight: 600; color: #0f172a;">{{ contact.created_at|date("d M, Y") }}</span>
                        <span style="font-size: 0.75rem; color: #64748b; display: flex; align-items: center; gap: 4px;">
                            <i class="far fa-clock" style="color: #393186; opacity: 0.7;"></i>
                            {{ contact.created_at|date("h:i A") }}
                        </span>
                    </div>
                </td>
                
                <td style="padding: 20px 24px; text-align: center;">
                    <form method="POST" action="{{ base_url }}/admin/contacts/delete/{{ contact.id }}"
                          onsubmit="return confirm('Are you sure you want to delete this message? This action cannot be undone.')"
                          style="display: inline-block;">
                        <button type="submit" 
                                style="display: inline-flex; align-items: center; gap: 8px; padding: 10px 20px; background: white; color: #ef4444; border: 1.5px solid #fee2e2; border-radius: 10px; font-weight: 600; font-size: 0.85rem; cursor: pointer; transition: all 0.2s;"
                                onmouseover="this.style.background='#fee2e2'; this.style.borderColor='#ef4444';"
                                onmouseout="this.style.background='white'; this.style.borderColor='#fee2e2';">
                            <i class="fas fa-trash"></i>
                            Delete
                        </button>
                    </form>
                </td>
            </tr>
            {% else %}
            <tr>
                <td colspan="8" style="padding: 60px 24px;">
                    <div style="text-align: center;">
                        <div style="width: 80px; height: 80px; background: #f0eff7; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 20px;">
                            <i class="fas fa-envelope-open-text" style="font-size: 2.5rem; color: #393186; opacity: 0.5;"></i>
                        </div>
                        <h3 style="color: #1e293b; font-size: 1.2rem; margin-bottom: 8px;">No messages yet</h3>
                        <p style="color: #64748b; margin-bottom: 0;">Contact form submissions will appear here</p>
                    </div>
                </td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</div>

<!-- Pagination -->
{% if total_pages > 1 %}
<div style="display: flex; justify-content: center; margin-top: 32px;">
    <div style="display: flex; gap: 8px;">
        {% for i in 1..total_pages %}
            <a href="{{ base_url }}/admin/contacts?page={{ i }}" 
               style="padding: 10px 18px; border-radius: 12px; background: {{ current_page == i ? '#393186' : 'white' }}; color: {{ current_page == i ? 'white' : '#475569' }}; text-decoration: none; border: 1.5px solid {{ current_page == i ? '#393186' : '#edf2f7' }}; font-weight: 600; transition: all 0.2s;"
               onmouseover="this.style.borderColor='#393186'; {% if current_page != i %}this.style.background='#f0eff7';{% endif %}"
               onmouseout="this.style.borderColor='{{ current_page == i ? '#393186' : '#edf2f7' }}'; {% if current_page != i %}this.style.background='white';{% endif %}">
                {{ i }}
            </a>
        {% endfor %}
    </div>
</div>
{% endif %}

<!-- Message Modal - UPDATED WITH COUNTRY CODE & SERVICE -->
<div id="messageModal" style="display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 1000; align-items: center; justify-content: center;"
     onclick="if(event.target === this) closeModal()">
    <div style="background: white; border-radius: 24px; padding: 32px; max-width: 600px; width: 90%; max-height: 80vh; overflow-y: auto; position: relative; box-shadow: 0 25px 50px -12px rgba(0,0,0,0.25);">
        <button onclick="closeModal()" 
                style="position: absolute; top: 20px; right: 20px; background: #f1f5f9; border: none; width: 36px; height: 36px; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: #64748b; cursor: pointer; transition: all 0.2s;"
                onmouseover="this.style.background='#e2e8f0'; this.style.color='#0f172a';"
                onmouseout="this.style.background='#f1f5f9'; this.style.color='#64748b';">
            <i class="fas fa-times"></i>
        </button>
        
        <div style="display: flex; align-items: center; gap: 16px; margin-bottom: 24px;">
            <div style="width: 56px; height: 56px; background: #f0eff7; border-radius: 16px; display: flex; align-items: center; justify-content: center;">
                <i class="fas fa-envelope" style="font-size: 1.8rem; color: #393186;"></i>
            </div>
            <div>
                <h3 style="color: #0f172a; font-size: 1.3rem; margin-bottom: 4px;">Contact Details</h3>
                <p id="modalSenderInfo" style="color: #64748b; font-size: 0.9rem;"></p>
            </div>
        </div>
        
        <!-- Contact Details Grid -->
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 24px;">
            <div style="background: #f8fafc; padding: 16px; border-radius: 16px;">
                <span style="display: block; font-size: 0.7rem; color: #64748b; text-transform: uppercase; margin-bottom: 4px;">📞 Phone</span>
                <span id="modalPhone" style="font-weight: 600; color: #0f172a;"></span>
            </div>
            <div style="background: #f8fafc; padding: 16px; border-radius: 16px;">
                <span style="display: block; font-size: 0.7rem; color: #64748b; text-transform: uppercase; margin-bottom: 4px;">🌍 Country Code</span>
                <span id="modalCountryCode" style="font-weight: 600; color: #393186;"></span>
            </div>
            <div style="background: #f8fafc; padding: 16px; border-radius: 16px; grid-column: span 2;">
                <span style="display: block; font-size: 0.7rem; color: #64748b; text-transform: uppercase; margin-bottom: 4px;">🔧 Service</span>
                <span id="modalService" style="display: inline-block; background: #f0eff7; color: #393186; padding: 6px 16px; border-radius: 30px; font-weight: 600;"></span>
            </div>
        </div>
        
        <div style="margin-bottom: 16px;">
            <span style="display: block; font-size: 0.8rem; color: #64748b; margin-bottom: 8px;">📝 Message</span>
            <div style="background: #f8fafc; border-radius: 16px; padding: 24px; border: 1px solid #edf2f7;">
                <p id="modalMessage" style="color: #1e293b; line-height: 1.8; font-size: 1rem; white-space: pre-wrap; margin: 0;"></p>
            </div>
        </div>
        
        <div style="display: flex; gap: 16px; margin-top: 24px; justify-content: flex-end;">
            <a id="modalReplyBtn" href="#" target="_blank" 
               style="display: inline-flex; align-items: center; gap: 8px; padding: 12px 24px; background: #393186; color: white; border-radius: 12px; font-weight: 600; text-decoration: none; transition: all 0.2s;"
               onmouseover="this.style.background='#2e2770';"
               onmouseout="this.style.background='#393186';">
                <i class="fas fa-reply"></i>
                Reply
            </a>
            <button onclick="closeModal()"
                    style="padding: 12px 24px; background: white; color: #475569; border: 1.5px solid #edf2f7; border-radius: 12px; font-weight: 600; cursor: pointer; transition: all 0.2s;"
                    onmouseover="this.style.borderColor='#94a3b8';"
                    onmouseout="this.style.borderColor='#edf2f7';">
                Close
            </button>
        </div>
    </div>
</div>

<script>
// Search functionality - UPDATED with more fields
document.getElementById('searchInput')?.addEventListener('keyup', filterTable);

function filterTable() {
    const searchText = document.getElementById('searchInput')?.value.toLowerCase() || '';
    const rows = document.querySelectorAll('tbody tr');
    
    rows.forEach(row => {
        if (row.querySelector('td[colspan]')) return;
        
        const name = row.cells[0]?.textContent.toLowerCase() || '';
        const email = row.cells[1]?.textContent.toLowerCase() || '';
        const countryCode = row.cells[2]?.textContent.toLowerCase() || '';
        const phone = row.cells[3]?.textContent.toLowerCase() || '';
        const service = row.cells[4]?.textContent.toLowerCase() || '';
        const message = row.cells[5]?.textContent.toLowerCase() || '';
        
        const matches = name.includes(searchText) || 
                       email.includes(searchText) || 
                       phone.includes(searchText) || 
                       countryCode.includes(searchText) ||
                       service.includes(searchText) ||
                       message.includes(searchText);
        
        row.style.display = matches ? '' : 'none';
    });
}

// Service filter
document.getElementById('serviceFilter')?.addEventListener('change', function() {
    const filterValue = this.value;
    const rows = document.querySelectorAll('tbody tr');
    
    rows.forEach(row => {
        if (row.querySelector('td[colspan]')) return;
        
        const serviceCell = row.cells[4]?.textContent.toLowerCase().trim() || '';
        let show = false;
        
        if (filterValue === 'all') {
            show = true;
        } else {
            show = serviceCell.includes(filterValue.replace('-', ' '));
        }
        
        row.style.display = show ? '' : 'none';
    });
});

// Date filter
document.getElementById('dateFilter')?.addEventListener('change', function() {
    const filter = this.value;
    if (filter === 'all') {
        filterTable();
        return;
    }
    
    const rows = document.querySelectorAll('tbody tr');
    const now = new Date();
    
    rows.forEach(row => {
        if (row.querySelector('td[colspan]')) return;
        
        const dateText = row.cells[6]?.querySelector('span:first-child')?.textContent || '';
        const rowDate = new Date(dateText);
        let show = false;
        
        if (filter === 'today') {
            show = rowDate.toDateString() === now.toDateString();
        } else if (filter === 'week') {
            const weekAgo = new Date(now);
            weekAgo.setDate(weekAgo.getDate() - 7);
            show = rowDate >= weekAgo;
        } else if (filter === 'month') {
            show = rowDate.getMonth() === now.getMonth() && rowDate.getFullYear() === now.getFullYear();
        }
        
        row.style.display = show ? '' : 'none';
    });
});

// Updated Modal function with country code and service
function viewFullMessage(message, name, email, countryCode, phone, service) {
    const modal = document.getElementById('messageModal');
    const modalMessage = document.getElementById('modalMessage');
    const modalSenderInfo = document.getElementById('modalSenderInfo');
    const modalPhone = document.getElementById('modalPhone');
    const modalCountryCode = document.getElementById('modalCountryCode');
    const modalService = document.getElementById('modalService');
    const modalReplyBtn = document.getElementById('modalReplyBtn');
    
    modalMessage.textContent = message;
    modalSenderInfo.innerHTML = `<i class="fas fa-user" style="margin-right: 6px;"></i> ${name} · <i class="fas fa-envelope" style="margin-right: 6px;"></i> ${email}`;
    modalPhone.textContent = countryCode ? `${countryCode} ${phone}` : phone || 'Not provided';
    modalCountryCode.textContent = countryCode || 'Not provided';
    
    // Format service name
    if (service) {
        let serviceName = service.replace(/-/g, ' ');
        serviceName = serviceName.split(' ').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ');
        modalService.textContent = serviceName;
    } else {
        modalService.textContent = 'Not specified';
    }
    
    // Set reply button
    modalReplyBtn.href = `mailto:${email}?subject=Re: Contact from ${name}`;
    
    modal.style.display = 'flex';
}

function closeModal() {
    document.getElementById('messageModal').style.display = 'none';
}

// Export functionality - UPDATED with new columns
function exportContacts() {
    const rows = [];
    rows.push(['Name', 'Email', 'Country Code', 'Phone', 'Service', 'Message', 'Date']);
    
    {% for contact in contacts %}
    rows.push([
        '{{ contact.name|escape('js') }}',
        '{{ contact.email|escape('js') }}',
        '{{ contact.country_code|escape('js') }}',
        '{{ contact.phone|escape('js') }}',
        '{{ contact.service|escape('js') }}',
        '{{ contact.message|escape('js') }}',
        '{{ contact.created_at }}'
    ]);
    {% endfor %}
    
    const csvContent = rows.map(row => row.map(cell => `"${cell}"`).join(',')).join('\n');
    
    const blob = new Blob([csvContent], { type: 'text/csv' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'contact-submissions-{{ "now"|date("Y-m-d") }}.csv';
    a.click();
    window.URL.revokeObjectURL(url);
}

// Close modal with Escape key
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        closeModal();
    }
});
</script>

<style>
/* Responsive adjustments */
@media (max-width: 1024px) {
    .table-container {
        overflow-x: auto;
    }
    
    table {
        min-width: 1300px;
    }
}

@media (max-width: 768px) {
    div[style*="display: flex; gap: 16px; align-items: center; flex-wrap: wrap;"] {
        flex-direction: column;
        align-items: stretch !important;
    }
    
    div[style*="position: relative; flex: 1;"] {
        min-width: 100%;
    }
}

/* Custom scrollbar */
::-webkit-scrollbar {
    width: 8px;
    height: 8px;
}

::-webkit-scrollbar-track {
    background: #f1f5f9;
    border-radius: 10px;
}

::-webkit-scrollbar-thumb {
    background: #cbd5e1;
    border-radius: 10px;
}

::-webkit-scrollbar-thumb:hover {
    background: #94a3b8;
}

/* Animations */
@keyframes fadeIn {
    from { opacity: 0; transform: translateY(10px); }
    to { opacity: 1; transform: translateY(0); }
}

tr {
    animation: fadeIn 0.3s ease;
}

/* Service badge */
.service-badge {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    background: #f0eff7;
    color: #393186;
    padding: 6px 14px;
    border-radius: 30px;
    font-weight: 600;
    font-size: 0.8rem;
}
</style>
{% endblock %}