<?php
ob_start();
// index.php - Main entry point and URL router for Team Mania Pro

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/auth.php';

// Handle API requests
if (isset($_GET['api'])) {
    header('Content-Type: application/json');
    
    if (!is_logged_in()) {
        echo json_encode(['success' => false, 'error' => 'Nicht eingeloggt']);
        exit;
    }
    
    $api = $_GET['api'];
    
    try {
        if ($api === 'chat_messages') {
            $room_id = intval($_GET['room_id'] ?? 0);
            $last_id = intval($_GET['last_id'] ?? 0);
            
            // Verify room membership (optional check for private rooms)
            $stmt = $pdo->prepare("SELECT m.*, u.first_name, u.last_name, u.role 
                                   FROM chat_messages m 
                                   JOIN users u ON m.sender_id = u.id 
                                   WHERE m.room_id = :room_id AND m.id > :last_id 
                                   ORDER BY m.id ASC");
            $stmt->execute([':room_id' => $room_id, ':last_id' => $last_id]);
            $raw_messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            $messages = [];
            $roles_labels = [
                'admin' => 'Admin',
                'vorstand' => 'Vorstand',
                'kassenwart' => 'Kassenwart',
                'trainer' => 'Trainer',
                'materialwart' => 'Materialwart',
                'member' => 'Mitglied'
            ];
            
            foreach ($raw_messages as $m) {
                $messages[] = [
                    'id' => intval($m['id']),
                    'message' => $m['message'],
                    'first_name' => $m['first_name'],
                    'last_name' => $m['last_name'],
                    'role_label' => $roles_labels[$m['role']] ?? 'Mitglied',
                    'is_self' => intval($m['sender_id']) === intval($_SESSION['user_id']),
                    'time' => date('H:i', strtotime($m['created_at']))
                ];
            }
            
            echo json_encode(['success' => true, 'messages' => $messages]);
            exit;
            
        } elseif ($api === 'send_chat_message') {
            if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
                throw new Exception("Nur POST erlaubt");
            }
            
            $room_id = intval($_POST['room_id'] ?? 0);
            $message = trim($_POST['message'] ?? '');
            
            if ($room_id <= 0 || empty($message)) {
                throw new Exception("Ungültige Daten");
            }
            
            $stmt = $pdo->prepare("INSERT INTO chat_messages (room_id, sender_id, message) VALUES (:room_id, :sender_id, :message)");
            $stmt->execute([
                ':room_id' => $room_id,
                ':sender_id' => $_SESSION['user_id'],
                ':message' => $message
            ]);
            
            echo json_encode(['success' => true]);
            exit;
            
        } elseif ($api === 'notifications_unread') {
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM notifications WHERE user_id = :user_id AND is_read = 0");
            $stmt->execute([':user_id' => $_SESSION['user_id']]);
            $count = intval($stmt->fetchColumn());
            
            echo json_encode(['success' => true, 'count' => $count]);
            exit;
        }
        
        throw new Exception("API-Endpunkt nicht gefunden");
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        exit;
    }
}

// Router for Page Views
$view = $_GET['view'] ?? 'dashboard';

// Access Control
if ($view !== 'login' && !is_logged_in()) {
    header("Location: index.php?view=login");
    exit;
}

// Handle Form Submissions like Login or Actions
$auth_error = '';
if ($view === 'login' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    
    if (!empty($username) && !empty($password)) {
        $stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username OR email = :email");
        $stmt->execute([':username' => $username, ':email' => $username]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($user && password_verify($password, $user['password_hash'])) {
            $_SESSION['user_id'] = $user['id'];
            header("Location: index.php?view=dashboard");
            exit;
        } else {
            $auth_error = 'Ungültige Anmeldedaten';
        }
    } else {
        $auth_error = 'Bitte füllen Sie alle Felder aus';
    }
}

// Handle Logout
if ($view === 'logout') {
    if (isset($_SESSION['is_demo']) && $_SESSION['is_demo'] === true) {
        // Keep the demo session flag but log the user out
        unset($_SESSION['user_id']);
        unset($_SESSION['role']);
        unset($_SESSION['username']);
        header("Location: index.php?view=login");
    } else {
        session_destroy();
        header("Location: index.php?view=login");
    }
    exit;
}

// Secure View Selection
$allowed_views = ['login', 'dashboard', 'profile', 'admin', 'pages', 'kassenwart', 'vorstand', 'trainer', 'inventory', 'chat', 'forum'];
if (!in_array($view, $allowed_views)) {
    $view = 'dashboard';
}

// Enforce specific role requirements for views based on menu visibility settings
if ($view !== 'login' && $view !== 'profile' && $view !== 'dashboard' && $view !== 'pages') {
    if ($view === 'admin') {
        require_role('admin');
    } elseif (!is_menu_visible($view)) {
        header("Location: index.php?view=dashboard&error=access_denied");
        exit;
    }
}

// Load custom branding colors and name
$club_name = htmlspecialchars(get_setting('club_name', 'Team Mania Pro'));
$primary_color = htmlspecialchars(get_setting('primary_color', '#10b981'));
$secondary_color = htmlspecialchars(get_setting('secondary_color', '#1e293b'));
$logo_path = get_setting('logo_path', '');

// Load View Files
if ($view === 'login') {
    include __DIR__ . '/views/login.php';
} else {
    include __DIR__ . '/views/header.php';
    include __DIR__ . '/views/' . $view . '.php';
    include __DIR__ . '/views/footer.php';
}
