<?php
// views/trainer.php - Coach dashboard with player list and PM system
require_once __DIR__ . '/../auth.php';
require_role(['admin', 'trainer']);

$user = current_user();
$errors = [];
$success_msg = '';

// 1. Handle Send PM (Private Message)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'send_pm') {
    $receiver_id = intval($_POST['receiver_id'] ?? 0);
    $subject = trim($_POST['subject'] ?? '');
    $message = trim($_POST['message'] ?? '');

    if ($receiver_id <= 0 || empty($subject) || empty($message)) {
        $errors[] = "Bitte Empfänger, Betreff und Nachricht vollständig ausfüllen.";
    }

    if (empty($errors)) {
        try {
            $pdo->beginTransaction();
            
            // Insert private message
            $stmt = $pdo->prepare("INSERT INTO messages (sender_id, receiver_id, subject, message) VALUES (:sender_id, :receiver_id, :subject, :message)");
            $stmt->execute([
                ':sender_id' => $user['id'],
                ':receiver_id' => $receiver_id,
                ':subject' => $subject,
                ':message' => $message
            ]);

            // Add notification for the receiver
            $sender_name = $user['first_name'] . ' ' . $user['last_name'];
            $notif_title = "Neue Nachricht von " . $sender_name;
            $notif_msg = "Betreff: " . $subject;
            
            $stmt = $pdo->prepare("INSERT INTO notifications (user_id, title, message) VALUES (:uid, :title, :msg)");
            $stmt->execute([
                ':uid' => $receiver_id,
                ':title' => $notif_title,
                ':msg' => $notif_msg
            ]);

            $pdo->commit();
            $success_msg = "Private Nachricht erfolgreich an das Mitglied gesendet!";
        } catch (PDOException $e) {
            $pdo->rollBack();
            $errors[] = "Fehler beim Senden der Nachricht: " . $e->getMessage();
        }
    }
}

// 2. Fetch Squad Members (all regular members and trainers)
$squad_stmt = $pdo->query("SELECT id, username, first_name, last_name, email, photo_path, role FROM users WHERE role IN ('member', 'trainer') ORDER BY role DESC, last_name ASC");
$squad = $squad_stmt->fetchAll(PDO::FETCH_ASSOC);

// 2. Fetch Squad Members (all regular members and trainers)
$squad_stmt = $pdo->query("SELECT id, username, first_name, last_name, email, photo_path, role FROM users WHERE role IN ('member', 'trainer') ORDER BY role DESC, last_name ASC");
$squad = $squad_stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; flex-wrap: wrap; gap: 10px;">
    <div>
        <h1 style="font-size: 28px; font-weight: 800; color: var(--secondary);">Trainer-Zentrale</h1>
        <p style="color: var(--text-muted); font-size: 14px;">Kaderübersicht und Spieler-Kommunikation</p>
    </div>
</div>

<?php if (!empty($errors)): ?>
    <div class="alert alert-danger">
        <ul>
            <?php foreach ($errors as $err): ?>
                <li><?= htmlspecialchars($err) ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<?php if (!empty($success_msg)): ?>
    <div class="alert alert-success"><?= htmlspecialchars($success_msg) ?></div>
<?php endif; ?>


<div class="grid" style="grid-template-columns: 3fr 2fr; gap: 24px;">
    <!-- Roster Table -->
    <div class="card">
        <h3 class="card-title">📋 Kaderliste</h3>
        <div class="table-responsive" style="margin-top: 15px;">
            <table>
                <thead>
                    <tr>
                        <th style="width: 50px;">Foto</th>
                        <th>Name</th>
                        <th>Rolle</th>
                        <th>E-Mail</th>
                        <th style="width: 140px;">Aktionen</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($squad as $sq): ?>
                        <tr>
                            <td>
                                <?php if (!empty($sq['photo_path']) && file_exists(__DIR__ . '/../' . $sq['photo_path'])): ?>
                                    <img src="<?= htmlspecialchars($sq['photo_path']) ?>" style="width: 32px; height: 32px; border-radius: 50%; object-fit: cover;" alt="Foto">
                                <?php else: ?>
                                    <div style="width: 32px; height: 32px; border-radius: 50%; background-color: var(--primary); color: white; display: flex; align-items: center; justify-content: center; font-size: 11px; font-weight: bold;">
                                        <?= strtoupper(substr($sq['first_name'], 0, 1) . substr($sq['last_name'], 0, 1)) ?>
                                    </div>
                                <?php endif; ?>
                            </td>
                            <td style="font-weight: 600;"><?= htmlspecialchars($sq['first_name'] . ' ' . $sq['last_name']) ?></td>
                            <td>
                                <span style="font-size: 12px; padding: 2px 6px; border-radius: 4px; background: #e2e8f0;">
                                    <?= $sq['role'] === 'trainer' ? 'Trainer' : 'Spieler/Mitglied' ?>
                                </span>
                            </td>
                            <td><?= htmlspecialchars($sq['email']) ?></td>
                            <td>
                                <button type="button" class="btn btn-secondary btn-sm" onclick="openPMForm(<?= $sq['id'] ?>, '<?= htmlspecialchars($sq['first_name'] . ' ' . $sq['last_name']) ?>')">PN senden</button>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- PM Writer Form -->
    <div class="card" id="pm-writer-card">
        <h3 class="card-title">✉️ Private Nachricht (PN) verfassen</h3>
        
        <form method="POST" action="" style="margin-top: 15px;">
            <input type="hidden" name="action" value="send_pm">
            
            <div class="form-group">
                <label for="pm_receiver">Empfänger</label>
                <select id="pm_receiver" name="receiver_id" required>
                    <option value="">-- Spieler auswählen --</option>
                    <?php foreach ($squad as $sq): ?>
                        <?php if (intval($sq['id']) !== intval($user['id'])): ?>
                            <option value="<?= $sq['id'] ?>"><?= htmlspecialchars($sq['first_name'] . ' ' . $sq['last_name']) ?></option>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="form-group">
                <label for="pm_subject">Betreff</label>
                <input type="text" id="pm_subject" name="subject" placeholder="z. B. Trainingsabsage / Treffpunkt Spiel" required>
            </div>

            <div class="form-group">
                <label for="pm_message">Nachrichtentext</label>
                <textarea id="pm_message" name="message" rows="6" placeholder="Deine Mitteilung an den Spieler..." required></textarea>
            </div>

            <button type="submit" class="btn btn-primary" style="width: 100%;">Nachricht senden</button>
        </form>
    </div>
</div>

<script>
function openPMForm(userId, userName) {
    const select = document.getElementById("pm_receiver");
    const subjectInput = document.getElementById("pm_subject");
    const writerCard = document.getElementById("pm-writer-card");
    
    select.value = userId;
    subjectInput.value = "Mitteilung an " + userName;
    
    // Smooth scroll to writer
    writerCard.scrollIntoView({ behavior: 'smooth' });
}
</script>
