<?php
// pages/reports.php
require_once __DIR__ . '/../config/auth_check.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reports - AdMob Analytics</title>
    <link rel="stylesheet" href="/assets/css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body>
    <?php include __DIR__ . '/../includes/sidebar.php'; ?>
    
    <div class="main-content">
        <?php include __DIR__ . '/../includes/header.php'; ?>
        
        <div class="content-wrapper">
            <div class="page-header">
                <h1>Reports</h1>
            </div>

            <!-- Report Filters -->
            <div class="card">
                <div class="card-header">
                    <h2><i class="fas fa-filter"></i> Report Filters</h2>
                </div>
                <div class="card-body">
                    <div class="filter-row">
                        <div class="form-group">
                            <label>Date Range</label>
                            <select id="date-range" onchange="updateDateInputs()">
                                <option value="today">Today</option>
                                <option value="yesterday">Yesterday</option>
                                <option value="last_7_days" selected>Last 7 Days</option>
                                <option value="last_30_days">Last 30 Days</option>
                                <option value="this_month">This Month</option>
                                <option value="last_month">Last Month</option>
                                <option value="custom">Custom Range</option>
                            </select>
                        </div>

                        <div class="form-group" id="custom-dates" style="display: none;">
                            <label>Start Date</label>
                            <input type="date" id="start-date" class="form-control">
                        </div>

                        <div class="form-group" id="custom-dates-end" style="display: none;">
                            <label>End Date</label>
                            <input type="date" id="end-date" class="form-control">
                        </div>

                        <div class="form-group">
                            <label>Dimension</label>
                            <select id="dimension">
                                <option value="date">Date</option>
                                <option value="app">App</option>
                                <option value="ad_unit">Ad Unit</option>
                                <option value="platform">Platform</option>
                                <option value="format">Ad Format</option>
                                <option value="country">Country</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label>Metrics</label>
                            <select id="metrics" multiple>
                                <option value="impressions" selected>Impressions</option>
                                <option value="clicks" selected>Clicks</option>
                                <option value="earnings" selected>Earnings</option>
                                <option value="ctr">CTR</option>
                                <option value="ecpm">eCPM</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label>&nbsp;</label>
                            <button class="btn btn-primary" onclick="generateReport()">
                                <i class="fas fa-chart-bar"></i> Generate Report
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Report Results -->
            <div class="card">
                <div class="card-header">
                    <h2>Report Results</h2>
                    <div class="card-actions">
                        <button class="btn btn-sm btn-secondary" onclick="exportReport('csv')">
                            <i class="fas fa-file-csv"></i> CSV
                        </button>
                        <button class="btn btn-sm btn-secondary" onclick="exportReport('json')">
                            <i class="fas fa-file-code"></i> JSON
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    <div id="report-container">
                        <div class="empty-state">
                            <i class="fas fa-chart-line fa-3x"></i>
                            <p>Select filters and click "Generate Report" to view data</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
    <script>
        let currentReportData = null;
        let reportChart = null;

        function updateDateInputs() {
            const rangeSelect = document.getElementById('date-range');
            const customDates = document.getElementById('custom-dates');
            const customDatesEnd = document.getElementById('custom-dates-end');
            
            if (rangeSelect.value === 'custom') {
                customDates.style.display = 'block';
                customDatesEnd.style.display = 'block';
            } else {
                customDates.style.display = 'none';
                customDatesEnd.style.display = 'none';
            }
        }

        async function generateReport() {
            const dateRange = document.getElementById('date-range').value;
            const dimension = document.getElementById('dimension').value;
            const metricsSelect = document.getElementById('metrics');
            const metrics = Array.from(metricsSelect.selectedOptions).map(opt => opt.value);
            
            let startDate, endDate;
            
            if (dateRange === 'custom') {
                startDate = document.getElementById('start-date').value;
                endDate = document.getElementById('end-date').value;
                
                if (!startDate || !endDate) {
                    alert('Please select both start and end dates');
                    return;
                }
            }

            const params = new URLSearchParams({
                action: 'generate',
                date_range: dateRange,
                dimension: dimension,
                metrics: metrics.join(',')
            });

            if (startDate && endDate) {
                params.append('start_date', startDate);
                params.append('end_date', endDate);
            }

            try {
                const response = await fetch('/api/reports.php?' + params);
                const data = await response.json();

                if (data.success) {
                    currentReportData = data.data;
                    displayReport(data.data);
                } else {
                    alert('Error: ' + data.error);
                }
            } catch (error) {
                console.error('Error generating report:', error);
                alert('Failed to generate report');
            }
        }

        function displayReport(reportData) {
            const container = document.getElementById('report-container');
            
            if (!reportData || !reportData.rows || reportData.rows.length === 0) {
                container.innerHTML = '<div class="empty-state"><p>No data available for the selected filters</p></div>';
                return;
            }

            // Create table
            let html = '<div class="table-responsive"><table class="data-table"><thead><tr>';
            
            reportData.headers.forEach(header => {
                html += `<th>${header}</th>`;
            });
            
            html += '</tr></thead><tbody>';
            
            reportData.rows.forEach(row => {
                html += '<tr>';
                row.forEach(cell => {
                    html += `<td>${cell}</td>`;
                });
                html += '</tr>';
            });
            
            html += '</tbody></table></div>';
            
            // Add summary
            if (reportData.totals) {
                html += '<div class="report-summary"><h3>Summary</h3>';
                html += '<div class="summary-grid">';
                
                for (const [key, value] of Object.entries(reportData.totals)) {
                    html += `<div class="summary-item"><span>${key}:</span> <strong>${value}</strong></div>`;
                }
                
                html += '</div></div>';
            }
            
            container.innerHTML = html;
        }

        function exportReport(format) {
            if (!currentReportData) {
                alert('Please generate a report first');
                return;
            }
            
            const dateRange = document.getElementById('date-range').value;
            const dimension = document.getElementById('dimension').value;
            
            window.location.href = `/api/reports.php?action=export&format=${format}&date_range=${dateRange}&dimension=${dimension}`;
        }
    </script>
</body>
</html>