<?php
// pages/apps.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>Apps - 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>Apps</h1>
                <div class="page-actions">
                    <button class="btn btn-primary" onclick="syncApps()">
                        <i class="fas fa-sync-alt"></i> Sync with AdMob
                    </button>
                </div>
            </div>

            <!-- Apps Grid -->
            <div id="apps-container" class="apps-grid">
                <div class="loading-state">
                    <i class="fas fa-spinner fa-spin fa-2x"></i>
                    <p>Loading apps...</p>
                </div>
            </div>
        </div>
    </div>

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

    <script>
        let appsData = [];

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

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

                if (data.success) {
                    appsData = data.data;
                    displayApps(data.data);
                } else {
                    showError(data.error);
                }
            } catch (error) {
                console.error('Error loading apps:', error);
                showError('Failed to load apps');
            }
        }

        function displayApps(apps) {
            const container = document.getElementById('apps-container');
            
            if (!apps || apps.length === 0) {
                container.innerHTML = '<div class="empty-state"><i class="fas fa-mobile-alt fa-3x"></i><p>No apps found. Click "Sync with AdMob" to import your apps.</p></div>';
                return;
            }

            container.innerHTML = apps.map(app => `
                <div class="app-card" onclick="viewAppDetails('${app.app_id}')">
                    <div class="app-icon">
                        <i class="fab fa-${app.platform === 'Android' ? 'android' : 'apple'}"></i>
                    </div>
                    <div class="app-info">
                        <h3>${app.app_name}</h3>
                        <p class="app-package">${app.package_name || app.bundle_id}</p>
                        <div class="app-stats">
                            <span><i class="fas fa-ad"></i> ${app.ad_unit_count || 0} Units</span>
                            <span><i class="fas fa-dollar-sign"></i> $${(app.total_earnings || 0).toFixed(2)}</span>
                        </div>
                    </div>
                    <div class="app-platform-badge ${app.platform.toLowerCase()}">${app.platform}</div>
                </div>
            `).join('');
        }

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

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

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

        async function viewAppDetails(appId) {
            try {
                const response = await fetch(`/api/apps.php?action=details&app_id=${appId}`);
                const data = await response.json();

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

        function showAppModal(app) {
            document.getElementById('modal-app-name').textContent = app.app_name;
            document.getElementById('modal-app-body').innerHTML = `
                <div class="app-details">
                    <div class="detail-row">
                        <label>Package Name:</label>
                        <span>${app.package_name || app.bundle_id}</span>
                    </div>
                    <div class="detail-row">
                        <label>Platform:</label>
                        <span>${app.platform}</span>
                    </div>
                    <div class="detail-row">
                        <label>Ad Units:</label>
                        <span>${app.ad_unit_count || 0}</span>
                    </div>
                    <div class="detail-row">
                        <label>Total Earnings:</label>
                        <span>$${(app.total_earnings || 0).toFixed(2)}</span>
                    </div>
                    <div class="detail-row">
                        <label>Last Updated:</label>
                        <span>${new Date(app.last_updated).toLocaleString()}</span>
                    </div>
                </div>
                
                <div class="modal-actions">
                    <button class="btn btn-primary" onclick="viewAppAdUnits('${app.app_id}')">
                        View Ad Units
                    </button>
                    <button class="btn btn-secondary" onclick="closeAppModal()">
                        Close
                    </button>
                </div>
            `;
            
            document.getElementById('app-modal').style.display = 'flex';
        }

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

        function viewAppAdUnits(appId) {
            window.location.href = `/pages/ad-units.php?app_id=${appId}`;
        }

        function showError(message) {
            const container = document.getElementById('apps-container');
            container.innerHTML = `<div class="error-state"><i class="fas fa-exclamation-triangle fa-3x"></i><p>${message}</p></div>`;
        }

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