<?php

/**
 * Orestbida Cookie Consent SaaS - All-in-One Dashboard & API
 * This single file serves the HTML dashboard and handles all API requests.
 */

// --- Main API Router ---
// Check if the request is for a public or internal API endpoint.
if (strpos($_SERVER['REQUEST_URI'], '/api/') !== false || isset($_GET['api'])) {
    // --- API LOGIC ---

    // --- Error Reporting ---
    ini_set('log_errors', 1);
    ini_set('error_log', __DIR__ . '/php_error.log');
    error_reporting(E_ALL);

    // --- Database Configuration ---
    $db_host = 'localhost';
    $db_name = 'cookie';
    $db_user = 'cookie';
    $db_pass = 'ebenGUBA!!';
    $db_charset = 'utf8mb4';

    // --- CORS Configuration ---
    $allowed_origins = ['https://joeykeller.com', 'http://localhost', 'null'];
    $http_origin = $_SERVER['HTTP_ORIGIN'] ?? '';

    if (in_array($http_origin, $allowed_origins)) {
        header("Access-Control-Allow-Origin: " . $http_origin);
    }
    header("Access-Control-Allow-Headers: Content-Type");
    header("Access-Control-Allow-Methods: GET, POST, OPTIONS");

    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
        http_response_code(204);
        exit;
    }

    // --- Helper Functions ---
    function get_db_connection($host, $name, $user, $pass, $charset) {
        $dsn = "mysql:host=$host;dbname=$name;charset=$charset";
        $options = [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES   => false,
        ];
        return new PDO($dsn, $user, $pass, $options);
    }

    function send_json_response($data, $status_code = 200) {
        header('Content-Type: application/json');
        http_response_code($status_code);
        echo json_encode($data);
        exit;
    }

    // --- API Handlers ---
    function handle_get_config($pdo, $site_id) {
        $stmt = $pdo->prepare("SELECT domain, config_json, overlay_icon_url FROM sites WHERE id = ?");
        $stmt->execute([$site_id]);
        $result = $stmt->fetch();

        if ($result && !empty($result['config_json'])) {
            $config = json_decode($result['config_json'], true);
            if (!empty($result['overlay_icon_url'])) {
                $config['customSaaSConfig']['overlayButton']['enabled'] = true;
                $config['customSaaSConfig']['overlayButton']['imageUrl'] = $result['overlay_icon_url'];
            }
            send_json_response($config);
        } else {
            send_json_response(['status' => 'error', 'message' => 'Configuration not found.'], 404);
        }
    }

    function handle_log_consent($pdo) {
        $data = json_decode(file_get_contents('php://input'), true);
        if (empty($data['siteId']) || empty($data['consentId']) || !isset($data['acceptedCategories'])) {
            send_json_response(['status' => 'error', 'message' => 'Invalid consent data.'], 400);
        }
        $sql = "INSERT INTO consent_logs (site_id, consent_id, accepted_categories, revision, timestamp, ip_address) VALUES (?, ?, ?, ?, ?, ?)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$data['siteId'], $data['consentId'], json_encode($data['acceptedCategories']), $data['revision'] ?? 0, (new DateTime())->format('Y-m-d H:i:s'), $_SERVER['REMOTE_ADDR']]);
        send_json_response(['status' => 'success', 'message' => 'Consent logged.']);
    }

    function handle_get_consent_logs($pdo, $site_id) {
        $stmt = $pdo->prepare("SELECT timestamp, consent_id, accepted_categories, revision, ip_address FROM consent_logs WHERE site_id = ? ORDER BY timestamp DESC LIMIT 100");
        $stmt->execute([$site_id]);
        $logs = $stmt->fetchAll();
        foreach ($logs as &$log) {
            $log['accepted_categories'] = json_decode($log['accepted_categories']);
        }
        send_json_response($logs);
    }

    function handle_get_settings($pdo, $site_id) {
        $stmt = $pdo->prepare("SELECT domain, config_json, overlay_icon_url FROM sites WHERE id = ?");
        $stmt->execute([$site_id]);
        $site = $stmt->fetch();
        if (!$site) {
            send_json_response(['status' => 'error', 'message' => 'Site not found.'], 404);
        }
        $settings = [
            'domain'         => $site['domain'],
            'configJson'     => json_decode($site['config_json']),
            'overlayIconUrl' => $site['overlay_icon_url'] ?? ''
        ];
        send_json_response($settings);
    }

    function handle_save_settings($pdo, $site_id) {
        $newSettings = json_decode(file_get_contents('php://input'), true);
        if (!$newSettings || !isset($newSettings['configJson'])) {
            send_json_response(['status' => 'error', 'message' => 'Invalid JSON.'], 400);
        }
        $pdo->beginTransaction();
        $stmt1 = $pdo->prepare("UPDATE sites SET config_json = ? WHERE id = ?");
        $stmt1->execute([json_encode($newSettings['configJson']), $site_id]);
        $stmt2 = $pdo->prepare("UPDATE sites SET overlay_icon_url = ? WHERE id = ?");
        $stmt2->execute([$newSettings['overlayIconUrl'], $site_id]);
        $pdo->commit();
        send_json_response(['status' => 'success', 'message' => 'Settings saved.']);
    }

    function handle_get_chart_data($pdo, $site_id) {
        $stmt = $pdo->prepare("
            SELECT
                DATE(timestamp) as date,
                COUNT(*) as necessary_count,
                SUM(JSON_CONTAINS(accepted_categories, '\"analytics\"')) as analytics_count,
                SUM(JSON_CONTAINS(accepted_categories, '\"marketing\"')) as marketing_count
            FROM consent_logs 
            WHERE site_id = ? AND timestamp >= CURDATE() - INTERVAL 6 DAY 
            GROUP BY DATE(timestamp) 
            ORDER BY date ASC
        ");
        $stmt->execute([$site_id]);
        $results = $stmt->fetchAll();
        
        $chartData = [
            'labels'   => [], 
            'datasets' => ['necessary' => [], 'analytics' => [], 'marketing' => []]
        ];
        $period = new DatePeriod(new DateTime('-6 days'), new DateInterval('P1D'), new DateTime('+1 day'));
        $dbData = array_column($results, null, 'date');

        foreach ($period as $date) {
            $day = $date->format('Y-m-d');
            $chartData['labels'][] = $date->format('M j');
            $chartData['datasets']['necessary'][] = (int) ($dbData[$day]['necessary_count'] ?? 0);
            $chartData['datasets']['analytics'][] = (int) ($dbData[$day]['analytics_count'] ?? 0);
            $chartData['datasets']['marketing'][] = (int) ($dbData[$day]['marketing_count'] ?? 0);
        }
        
        send_json_response($chartData);
    }

    // --- API ROUTER ---
    try {
        $pdo = get_db_connection($db_host, $db_name, $db_user, $db_pass, $db_charset);
        $request_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
        $method = $_SERVER['REQUEST_METHOD'];

        // Handle public config endpoint (path-based ID)
        if (preg_match('#/api/config/([\w-]+)#', $request_path, $matches)) {
            handle_get_config($pdo, $matches[1]);
            exit;
        }
        
        // Handle public log endpoint (no ID needed)
        if ($request_path === '/api/log-consent') {
            handle_log_consent($pdo);
            exit;
        }

        // Handle dashboard API endpoints (query parameter-based ID)
        $endpoint = $_GET['api'] ?? '';
        $site_id = $_GET['site_id'] ?? null;

        if ($endpoint && !$site_id) {
            send_json_response(['status' => 'error', 'message' => 'site_id parameter is required for this endpoint.'], 400);
        }

        switch ($endpoint) {
            case 'logs':
                handle_get_consent_logs($pdo, $site_id);
                break;
            case 'settings':
                if ($method === 'GET') handle_get_settings($pdo, $site_id);
                if ($method === 'POST') handle_save_settings($pdo, $site_id);
                break;
            case 'chart-data':
                handle_get_chart_data($pdo, $site_id);
                break;
            default:
                // This will only be hit if the URL contains ?api=... but the endpoint is unknown
                send_json_response(['status' => 'error', 'message' => 'API endpoint not found.'], 404);
                break;
        }
    } catch (Exception $e) {
        error_log("API Error: " . $e->getMessage());
        send_json_response(['status' => 'error', 'message' => 'An internal server error occurred.'], 500);
    }
    exit;
}

// --- HTML DASHBOARD ---
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cookie Consent SaaS Dashboard</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body { font-family: 'Inter', sans-serif; }
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
        .sidebar-link { transition: all 0.2s ease-in-out; }
        .sidebar-link:hover, .sidebar-link.active { background-color: #f0f0f0; color: #111; }
        .loader { border: 4px solid #f3f3f3; border-top: 4px solid #3498db; border-radius: 50%; width: 40px; height: 40px; animation: spin 1s linear infinite; }
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
        #config-json { font-family: monospace; }
    </style>
</head>
<body class="bg-gray-100">

    <div class="flex h-screen">
        <!-- Sidebar Navigation -->
        <aside class="w-64 bg-white shadow-md flex flex-col">
            <div class="p-6 border-b">
                <h1 class="text-2xl font-bold text-gray-800">CookieSaaS</h1>
                <p id="sidebar-domain" class="text-sm text-gray-500">Loading...</p>
            </div>
            <nav class="flex-1 p-4">
                <a href="#dashboard" class="sidebar-link active flex items-center p-3 rounded-lg text-gray-600 font-medium" data-page="dashboard">
                    <svg class="w-6 h-6 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h7"></path></svg>
                    Dashboard
                </a>
                <a href="#consent-log" class="sidebar-link flex items-center p-3 rounded-lg text-gray-600 font-medium" data-page="consent-log">
                    <svg class="w-6 h-6 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path></svg>
                    Consent Log
                </a>
                <a href="#settings" class="sidebar-link flex items-center p-3 rounded-lg text-gray-600 font-medium" data-page="settings">
                    <svg class="w-6 h-6 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0 3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"></path><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path></svg>
                    Settings
                </a>
            </nav>
        </aside>

        <!-- Main Content -->
        <main class="flex-1 p-8 overflow-y-auto">
            <div id="loading-indicator" class="flex justify-center items-center h-full"><div class="loader"></div></div>

            <!-- Page: Dashboard -->
            <div id="dashboard-page" class="page hidden">
                <h2 class="text-3xl font-bold text-gray-800 mb-6">Consent Analytics</h2>
                <div class="bg-white p-6 rounded-lg shadow-md">
                    <h3 class="text-xl font-semibold text-gray-700 mb-4">Daily Consents by Category (Last 7 Days)</h3>
                    <div class="h-96"><canvas id="consentChart"></canvas></div>
                </div>
            </div>

            <!-- Page: Consent Log -->
            <div id="consent-log-page" class="page hidden">
                <h2 class="text-3xl font-bold text-gray-800 mb-6">Consent Log</h2>
                <div class="bg-white p-6 rounded-lg shadow-md">
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Timestamp</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Consent ID</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Accepted Categories</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">IP Address</th>
                                </tr>
                            </thead>
                            <tbody id="consent-log-table" class="bg-white divide-y divide-gray-200"></tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Page: Settings -->
            <div id="settings-page" class="page hidden">
                <h2 class="text-3xl font-bold text-gray-800 mb-6">Banner Settings</h2>
                <div class="bg-white p-6 rounded-lg shadow-md">
                    <form id="settings-form">
                        <div class="space-y-6">
                            <div>
                                <label for="overlay-icon-url" class="block text-sm font-medium text-gray-700">Overlay Icon URL</label>
                                <input type="text" id="overlay-icon-url" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm" placeholder="https://.../icon.png">
                            </div>
                            <div>
                                <label for="config-json" class="block text-sm font-medium text-gray-700">Full Configuration (JSON)</label>
                                <textarea id="config-json" rows="20" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm"></textarea>
                                <p class="mt-2 text-sm text-gray-500">Edit the raw JSON configuration for the cookie banner.</p>
                            </div>
                            <div class="flex justify-end">
                                <button type="submit" class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                                    Save Settings
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </main>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', async () => {
            // --- CONFIGURATION ---
            const SITE_ID = 'df0216fe-6494-11f0-98eb-00163e255213'; // IMPORTANT: Replace with a real Site ID from your database
            const API_BASE_URL = 'https://cookie.joeykeller.com/dashboard.php';

            const pages = document.querySelectorAll('.page');
            const navLinks = document.querySelectorAll('.sidebar-link');
            const loadingIndicator = document.getElementById('loading-indicator');

            // --- API FUNCTIONS ---
            async function fetchData(endpoint) {
                try {
                    const response = await fetch(`${API_BASE_URL}?api=${endpoint}&site_id=${SITE_ID}`);
                    if (!response.ok) throw new Error(`Network response was not ok: ${response.statusText}`);
                    return await response.json();
                } catch (error) {
                    console.error(`Failed to fetch ${endpoint}:`, error);
                    alert(`Error loading data for ${endpoint}. Check the console for details.`);
                    return null;
                }
            }
            
            async function postData(endpoint, data) {
                try {
                    const response = await fetch(`${API_BASE_URL}?api=${endpoint}&site_id=${SITE_ID}`, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify(data)
                    });
                    if (!response.ok) throw new Error(`Network response was not ok: ${response.statusText}`);
                    return await response.json();
                } catch (error) {
                    console.error(`Failed to post to ${endpoint}:`, error);
                    alert(`Error saving data. Check the console for details.`);
                }
            }

            // --- PAGE NAVIGATION ---
            function showPage(pageId) {
                pages.forEach(page => page.classList.add('hidden'));
                const activePage = document.getElementById(`${pageId}-page`);
                if (activePage) activePage.classList.remove('hidden');
                
                navLinks.forEach(link => link.classList.remove('active'));
                const activeLink = document.querySelector(`a[data-page="${pageId}"]`);
                if (activeLink) activeLink.classList.add('active');
            }

            navLinks.forEach(link => {
                link.addEventListener('click', (event) => {
                    event.preventDefault();
                    const pageId = event.currentTarget.getAttribute('data-page');
                    showPage(pageId);
                    window.location.hash = pageId;
                });
            });

            // --- DATA RENDERING ---
            async function renderConsentLog() {
                const logs = await fetchData('logs');
                if (!logs) return;

                const categoryColors = {
                    necessary: 'bg-gray-100 text-gray-800',
                    analytics: 'bg-blue-100 text-blue-800',
                    marketing: 'bg-purple-100 text-purple-800',
                    default: 'bg-yellow-100 text-yellow-800'
                };

                const getCategoryBadge = (category) => {
                    const colorClass = categoryColors[category] || categoryColors.default;
                    return `<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${colorClass}">${category}</span>`;
                };
                
                const tableBody = document.getElementById('consent-log-table');
                tableBody.innerHTML = logs.map(log => `
                    <tr>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${new Date(log.timestamp).toLocaleString()}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 font-mono">${log.consent_id.substring(0, 12)}...</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            ${(log.accepted_categories || []).map(getCategoryBadge).join(' ')}
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${log.ip_address}</td>
                    </tr>
                `).join('');
            }

            async function renderSettings() {
                const settings = await fetchData('settings');
                if (!settings) return;

                document.getElementById('overlay-icon-url').value = settings.overlayIconUrl;
                document.getElementById('config-json').value = JSON.stringify(settings.configJson, null, 2);
                document.getElementById('sidebar-domain').textContent = settings.domain || 'Your Site';
            }
            
            document.getElementById('settings-form').addEventListener('submit', async (event) => {
                event.preventDefault();
                const configJsonText = document.getElementById('config-json').value;
                let configJson;

                try {
                    configJson = JSON.parse(configJsonText);
                } catch (e) {
                    alert('Error: The configuration is not valid JSON. Please correct it and try again.');
                    return;
                }

                const newSettings = {
                    overlayIconUrl: document.getElementById('overlay-icon-url').value,
                    configJson: configJson
                };
                
                const result = await postData('settings', newSettings);
                if (result && result.status === 'success') {
                    alert('Settings saved successfully!');
                }
            });

            async function renderChart() {
                const chartData = await fetchData('chart-data');
                
                if (!chartData || !chartData.datasets || !chartData.datasets.analytics) {
                    console.error("Received invalid or incomplete data for the chart.", chartData);
                    const chartArea = document.getElementById('consentChart').parentElement;
                    chartArea.innerHTML = '<p class="text-red-500 text-center">Could not load chart data. Please check the API response.</p>';
                    return;
                }
                
                const ctx = document.getElementById('consentChart').getContext('2d');
                new Chart(ctx, {
                    type: 'bar',
                    data: {
                        labels: chartData.labels,
                        datasets: [
                            {
                                label: 'Necessary',
                                data: chartData.datasets.necessary,
                                backgroundColor: 'rgba(156, 163, 175, 0.8)', // Gray
                                borderWidth: 1,
                                borderRadius: 5
                            },
                            {
                                label: 'Analytics',
                                data: chartData.datasets.analytics,
                                backgroundColor: 'rgba(59, 130, 246, 0.8)', // Blue
                                borderWidth: 1,
                                borderRadius: 5
                            },
                            {
                                label: 'Marketing',
                                data: chartData.datasets.marketing,
                                backgroundColor: 'rgba(168, 85, 247, 0.8)', // Purple
                                borderWidth: 1,
                                borderRadius: 5
                            }
                        ]
                    },
                    options: {
                        scales: { 
                            x: { stacked: false }, // Changed to false
                            y: { stacked: false, beginAtZero: true, ticks: { stepSize: 1 } } // Changed to false
                        },
                        responsive: true,
                        maintainAspectRatio: false
                    }
                });
            }

            // --- INITIALIZATION ---
            async function initializeDashboard() {
                loadingIndicator.classList.remove('hidden');
                
                await Promise.all([
                    renderConsentLog(),
                    renderSettings(),
                    renderChart()
                ]);

                loadingIndicator.classList.add('hidden');
                const initialPage = window.location.hash.substring(1) || 'dashboard';
                showPage(initialPage);
            }

            initializeDashboard();
        });
    </script>

</body>
</html>
