<?php
require_once '../config.php';
require_once '../lib.php';

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

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

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        $type = $_GET['type'] ?? 'overview';
        
        switch ($type) {
            case 'overview':
                // Get latest metrics
                $stmt = $pdo->prepare("
                    SELECT * FROM analytics_daily_metrics 
                    ORDER BY date DESC LIMIT 1
                ");
                $stmt->execute();
                $latest = $stmt->fetch(PDO::FETCH_ASSOC);
                
                // Get 7-day trend
                $stmt = $pdo->prepare("
                    SELECT date, total_users, new_users, total_revenue, total_appointments
                    FROM analytics_daily_metrics 
                    ORDER BY date DESC LIMIT 7
                ");
                $stmt->execute();
                $trend = $stmt->fetchAll(PDO::FETCH_ASSOC);
                
                echo json_encode([
                    'success' => true,
                    'latest' => $latest,
                    'trend' => array_reverse($trend)
                ]);
                break;
                
            case 'revenue':
                $days = $_GET['days'] ?? 30;
                $stmt = $pdo->prepare("
                    SELECT 
                        date,
                        revenue_type,
                        SUM(amount) as total_amount
                    FROM revenue_analytics 
                    WHERE date >= DATE_SUB(CURDATE(), INTERVAL ? DAY)
                    GROUP BY date, revenue_type
                    ORDER BY date DESC
                ");
                $stmt->execute([$days]);
                $revenue = $stmt->fetchAll(PDO::FETCH_ASSOC);
                
                echo json_encode([
                    'success' => true,
                    'revenue' => $revenue
                ]);
                break;
                
            case 'coaches':
                $stmt = $pdo->prepare("
                    SELECT 
                        c.first_name,
                        c.last_name,
                        ca.total_sessions,
                        ca.total_revenue,
                        ca.avg_rating
                    FROM coach_analytics ca
                    JOIN coaches c ON ca.coach_id = c.id
                    WHERE ca.date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
                    GROUP BY ca.coach_id
                    ORDER BY ca.total_revenue DESC
                    LIMIT 10
                ");
                $stmt->execute();
                $coaches = $stmt->fetchAll(PDO::FETCH_ASSOC);
                
                echo json_encode([
                    'success' => true,
                    'coaches' => $coaches
                ]);
                break;
        }
        
    } elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
        // Track analytics event
        $input = json_decode(file_get_contents('php://input'), true);
        
        $stmt = $pdo->prepare("
            INSERT INTO analytics_events (event_type, user_id, session_id, event_data, ip_address, user_agent)
            VALUES (?, ?, ?, ?, ?, ?)
        ");
        
        $stmt->execute([
            $input['event_type'],
            $input['user_id'] ?? null,
            $input['session_id'] ?? session_id(),
            json_encode($input['event_data'] ?? []),
            $_SERVER['REMOTE_ADDR'],
            $_SERVER['HTTP_USER_AGENT'] ?? ''
        ]);
        
        echo json_encode(['success' => true]);
    }

} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>