<?php
// pages/ad-units.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>Ad Units - 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>Ad Units</h1>
                <div class="page-actions">
                    <button class="btn btn-secondary" onclick="filterAdUnits()">
                        <i class="fas fa-filter"></i> Filter
                    </button>
                    <button class="btn btn-primary" onclick="syncAdUnits()">
                        <i class="fas fa-sync-alt"></i> Sync with AdMob
                    </button>
                </div>
            </div>

            <!-- Filters -->
            <div class="card" id="filter-panel" style="display: none;">
                <div class="card-body">
                    <div class="filter-row">
                        <div class="form-group">
                            <label>App</label>
                            <select id="filter-app" onchange="applyFilters()">
                                <option value="">All Apps</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Format</label>
                            <select id="filter-format" onchange="applyFilters()">
                                <option value="">All Formats</option>
                                <option value="BANNER">Banner</option>
                                <option value="INTERSTITIAL">Interstitial</option>
                                <option value="REWARDED">Rewarded</option>
                                <option value="NATIVE">Native</option>
                                <option value="REWARDED_INTERSTITIAL">Rewarded Interstitial</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label>Status</label>
                            <select id="filter-status" onchange="applyFilters()">
                                <option value="">All Status</option>
                                <option value="active">Active</option>
                                <option value="inactive">Inactive</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Ad Units Table -->
            <div class="card">
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Ad Unit Name</th>
                                    <th>App</th>
                                    <th>Format</th>
                                    <th>Ad Unit ID</th>
                                    <th>Impressions</th>
                                    <th>Clicks</th>
                                    <th>Earnings</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody id="ad-units-tbody">
                                <tr>
                                    <td colspan="8" class="text-center">
                                        <i class="fas fa-spinner fa-spin"></i> Loading...
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Ad Unit Details Modal -->
    <div id="unit-modal" class="modal">
        <div class="modal-content modal-lg">
            <div class="modal-header">
                <h2 id="modal-unit-name">Ad Unit Details</h2>
                <button class="modal-close" onclick="closeUnitModal()">&times;</button>
            </div>
            <div class="modal-body" id="modal-unit-body">
                <!-- Details loaded dynamically -->
            </div>
        </div>
    </div>

    <script>
        let adUnitsData = [];
        let appsData = [];

        document.addEventListener('DOMContentLoaded', function() {
            loadApps();
            loadAdUnits();
        });

        async function loadApps() {
            try {
                const response = await fetch('/api/apps.php?action=list');
                const data = await response.json();

                if (data.success) {
                    appsData = data.data;
                    populateAppFilter(data.data);
                }
            } catch (error) {
                console.error('Error loading apps:', error);
            }
        }

        function populateAppFilter(apps) {
            const select = document.getElementById('filter-app');
            apps.forEach(app => {
                const option = document.createElement('option');
                option.value = app.app_id;
                option.textContent = app.app_name;
                select.appendChild(option);
            });
        }

        async function loadAdUnits() {
            try {
                const response = await fetch('/api/ad_units.php?action=list');
                const data = await response.json();

                if (data.success) {
                    adUnitsData = data.data;
                    displayAdUnits(data.data);
                } else {
                    showError(data.error);
                }
            } catch (error) {
                console.error('Error loading ad units:', error);
                showError('Failed to load ad units');
            }
        }

        function displayAdUnits(units) {
            const tbody = document.getElementById('ad-units-tbody');
            
            if (!units || units.length === 0) {
                tbody.innerHTML = '<tr><td colspan="8" class="text-center">No ad units found</td></tr>';
                return;
            }

            tbody.innerHTML = units.map(unit => `
                <tr>
                    <td>${unit.ad_unit_name}</td>
                    <td>${unit.app_name || 'Unknown'}</td>
                    <td><span class="badge badge-${getFormatColor(unit.format)}">${unit.format}</span></td>
                    <td><code>${unit.ad_unit_id}</code></td>
                    <td>${formatNumber(unit.impressions || 0)}</td>
                    <td>${formatNumber(unit.clicks || 0)}</td>
                    <td>$${(unit.earnings || 0).toFixed(2)}</td>
                    <td>
                        <button class="btn-icon" onclick="viewUnitDetails('${unit.ad_unit_id}')" title="View Details">
                            <i class="fas fa-eye"></i>
                        </button>
                    </td>
                </tr>
            `).join('');
        }

        async function syncAdUnits() {
            const btn = event.target;
            btn.disabled = true;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Syncing...';

            try {
                const response = await fetch('/api/ad_units.php?action=sync', {
                    method: 'POST'
                });
                const data = await response.json();

                if (data.success) {
                    alert('Ad units synced successfully! ' + data.message);
                    loadAdUnits();
                } else {
                    alert('Error: ' + data.error);
                }
            } catch (error) {
                console.error('Error syncing ad units:', error);
                alert('Failed to sync ad units');
            } finally {
                btn.disabled = false;
                btn.innerHTML = '<i class="fas fa-sync-alt"></i> Sync with AdMob';
            }
        }

        function filterAdUnits() {
            const panel = document.getElementById('filter-panel');
            panel.style.display = panel.style.display === 'none' ? 'block' : 'none';
        }

        function applyFilters() {
            const appFilter = document.getElementById('filter-app').value;
            const formatFilter = document.getElementById('filter-format').value;
            const statusFilter = document.getElementById('filter-status').value;

            let filtered = adUnitsData;

            if (appFilter) {
                filtered = filtered.filter(u => u.app_id === appFilter);
            }
            if (formatFilter) {
                filtered = filtered.filter(u => u.format === formatFilter);
            }
            if (statusFilter) {
                filtered = filtered.filter(u => u.status === statusFilter);
            }

            displayAdUnits(filtered);
        }

        async function viewUnitDetails(unitId) {
            try {
                const response = await fetch(`/api/ad_units.php?action=details&ad_unit_id=${unitId}`);
                const data = await response.json();

                if (data.success) {
                    showUnitModal(data.data);
                } else {
                    alert('Error: ' + data.error);
                }
            } catch (error) {
                console.error('Error loading unit details:', error);
                alert('Failed to load ad unit details');
            }
        }

        function showUnitModal(unit) {
            document.getElementById('modal-unit-name').textContent = unit.ad_unit_name;
            document.getElementById('modal-unit-body').innerHTML = `
                <div class="app-details">
                    <div class="detail-row">
                        <label>Ad Unit ID:</label>
                        <span><code>${unit.ad_unit_id}</code></span>
                    </div>
                    <div class="detail-row">
                        <label>App:</label>
                        <span>${unit.app_name}</span>
                    </div>
                    <div class="detail-row">
                        <label>Format:</label>
                        <span><span class="badge badge-${getFormatColor(unit.format)}">${unit.format}</span></span>
                    </div>
                    <div class="detail-row">
                        <label>Total Impressions:</label>
                        <span>${formatNumber(unit.impressions || 0)}</span>
                    </div>
                    <div class="detail-row">
                        <label>Total Clicks:</label>
                        <span>${formatNumber(unit.clicks || 0)}</span>
                    </div>
                    <div class="detail-row">
                        <label>Total Earnings:</label>
                        <span>$${(unit.earnings || 0).toFixed(2)}</span>
                    </div>
                    <div class="detail-row">
                        <label>CTR:</label>
                        <span>${((unit.clicks / unit.impressions) * 100 || 0).toFixed(2)}%</span>
                    </div>
                    <div class="detail-row">
                        <label>Last Updated:</label>
                        <span>${new Date(unit.last_updated).toLocaleString()}</span>
                    </div>
                </div>
                
                <div class="modal-actions">
                    <button class="btn btn-secondary" onclick="closeUnitModal()">Close</button>
                </div>
            `;
            
            document.getElementById('unit-modal').style.display = 'flex';
        }

        function closeUnitModal() {
            document.getElementById('unit-modal').style.display = 'none';
        }

        function getFormatColor(format) {
            const colors = {
                'BANNER': 'primary',
                'INTERSTITIAL': 'warning',
                'REWARDED': 'success',
                'NATIVE': 'info',
                'REWARDED_INTERSTITIAL': 'secondary'
            };
            return colors[format] || 'default';
        }

        function formatNumber(num) {
            if (num >= 1000000) return (num / 1000000).toFixed(2) + 'M';
            if (num >= 1000) return (num / 1000).toFixed(2) + 'K';
            return num.toString();
        }

        function showError(message) {
            const tbody = document.getElementById('ad-units-tbody');
            tbody.innerHTML = `<tr><td colspan="8" class="text-center text-error">${message}</td></tr>`;
        }

        // Close modal when clicking outside
        window.onclick = function(event) {
            const modal = document.getElementById('unit-modal');
            if (event.target === modal) {
                closeUnitModal();
            }
        }
    </script>
</body>
</html>