<?php
/**
 * Dashboard Statistics API
 * Liefert aktuelle Statistiken für das Admin-Dashboard
 */

header('Content-Type: application/json');
header('Cache-Control: no-cache, must-revalidate');

session_start();

// Check if running from command line or web server
if (php_sapi_name() === 'cli') {
    // Running from command line - adjust path
    require_once __DIR__ . '/../../config/database.php';
} else {
    // Running from web server
    require_once '../../config/database.php';
}

// Check if user is logged in
if (!isset($_SESSION['admin_logged_in']) || !$_SESSION['admin_logged_in']) {
    http_response_code(401);
    echo json_encode([
        'success' => false,
        'error' => 'Nicht autorisiert'
    ]);
    exit;
}

try {
    $db = new Database();
    $conn = $db->getConnection();
    
    // Get statistics
    $stats = getDashboardStats($conn);
    
    // Return success response
    echo json_encode([
        'success' => true,
        'stats' => $stats,
        'timestamp' => date('Y-m-d H:i:s')
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Fehler beim Laden der Statistiken: ' . $e->getMessage()
    ]);
}

/**
 * Get dashboard statistics
 */
function getDashboardStats($conn) {
    $stats = [];
    
    try {
        // Total events
        $stmt = $conn->prepare("SELECT COUNT(*) as count FROM events WHERE is_active = 1");
        $stmt->execute();
        $stats['total_events'] = (int)$stmt->fetchColumn();
        
        // Total appointments
        $stmt = $conn->prepare("SELECT COUNT(*) as count FROM appointments");
        $stmt->execute();
        $stats['total_appointments'] = (int)$stmt->fetchColumn();
        
        // Today's appointments
        $stmt = $conn->prepare("SELECT COUNT(*) as count FROM appointments WHERE slot_date = CURDATE()");
        $stmt->execute();
        $stats['today_appointments'] = (int)$stmt->fetchColumn();
        
        // This month's appointments
        $stmt = $conn->prepare("SELECT COUNT(*) as count FROM appointments WHERE MONTH(slot_date) = MONTH(CURDATE()) AND YEAR(slot_date) = YEAR(CURDATE())");
        $stmt->execute();
        $stats['month_appointments'] = (int)$stmt->fetchColumn();
        
        // This week's appointments
        $stmt = $conn->prepare("SELECT COUNT(*) as count FROM appointments WHERE slot_date >= DATE_SUB(CURDATE(), INTERVAL WEEKDAY(CURDATE()) DAY) AND slot_date < DATE_ADD(DATE_SUB(CURDATE(), INTERVAL WEEKDAY(CURDATE()) DAY), INTERVAL 7 DAY)");
        $stmt->execute();
        $stats['week_appointments'] = (int)$stmt->fetchColumn();
        
        // Pending appointments (booked but not completed)
        $stmt = $conn->prepare("SELECT COUNT(*) as count FROM appointments WHERE status = 'booked'");
        $stmt->execute();
        $stats['pending_appointments'] = (int)$stmt->fetchColumn();
        
        // Completed appointments
        $stmt = $conn->prepare("SELECT COUNT(*) as count FROM appointments WHERE status = 'completed'");
        $stmt->execute();
        $stats['completed_appointments'] = (int)$stmt->fetchColumn();
        
        // Cancelled appointments
        $stmt = $conn->prepare("SELECT COUNT(*) as count FROM appointments WHERE status = 'cancelled'");
        $stmt->execute();
        $stats['cancelled_appointments'] = (int)$stmt->fetchColumn();
        
        // Upcoming events (next 7 days)
        $stmt = $conn->prepare("SELECT COUNT(*) as count FROM events WHERE event_date >= CURDATE() AND event_date <= DATE_ADD(CURDATE(), INTERVAL 7 DAY) AND is_active = 1");
        $stmt->execute();
        $stats['upcoming_events'] = (int)$stmt->fetchColumn();
        
        // Revenue statistics (price column doesn't exist in current schema)
        $stats['total_revenue'] = 0;
        $stats['month_revenue'] = 0;
        
        // Average appointments per day (last 30 days)
        $stmt = $conn->prepare("SELECT COUNT(*) / 30 as avg_daily FROM appointments WHERE slot_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)");
        $stmt->execute();
        $avgDaily = $stmt->fetchColumn();
        $stats['avg_daily_appointments'] = $avgDaily ? round((float)$avgDaily, 1) : 0;
        
        // Most popular time slots (last 30 days)
        $stmt = $conn->prepare("
            SELECT slot_time, COUNT(*) as count 
            FROM appointments 
            WHERE slot_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY) 
            GROUP BY slot_time 
            ORDER BY count DESC 
            LIMIT 3
        ");
        $stmt->execute();
        $stats['popular_time_slots'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Recent activity (last 24 hours)
        $stmt = $conn->prepare("SELECT COUNT(*) as count FROM appointments WHERE created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)");
        $stmt->execute();
        $stats['recent_activity'] = (int)$stmt->fetchColumn();
        
    } catch (Exception $e) {
        error_log("Dashboard stats error: " . $e->getMessage());
        throw $e;
    }
    
    return $stats;
}
?>
