<?php
require_once __DIR__ . '/partials/header.php';

// Require login
if (!is_logged_in()) {
    header('Location: login.php');
    exit();
}

$pageTitle = 'Training Sessions';
$pageDescription = 'Manage your training sessions.';

$coach_id = get_user_id();
$pdo = db();

// Filtering logic
$show_favorites = isset($_GET['favorites']) && $_GET['favorites'] == '1';

$sql = "SELECT ts.*, (uf.id IS NOT NULL) as is_favorite 
        FROM training_sessions ts 
        LEFT JOIN user_favorites uf ON ts.id = uf.training_session_id AND uf.user_id = ? 
        WHERE ts.coach_id = ?";
$params = [$coach_id, $coach_id];

if ($show_favorites) {
    $sql .= " AND uf.id IS NOT NULL";
}

$sql .= " ORDER BY ts.created_at DESC";

// Fetch training sessions for the current coach
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$sessions = $stmt->fetchAll(PDO::FETCH_ASSOC);

?>

<main class="container my-5">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1 class="h2">My Training Sessions</h1>
        <a href="create_training_session.php" class="btn btn-primary">Create New Session</a>
    </div>

    <div class="mb-4 p-3 border rounded bg-light">
        <form method="GET" action="training_sessions.php">
            <h5 class="mb-3">Filter</h5>
            <div class="form-check">
                <input class="form-check-input" type="checkbox" name="favorites" value="1" id="favorites_filter" <?php echo $show_favorites ? 'checked' : ''; ?>>
                <label class="form-check-label" for="favorites_filter">
                    Show only favorites
                </label>
            </div>
            <div class="mt-3">
                <button type="submit" class="btn btn-primary">Filter</button>
                <a href="training_sessions.php" class="btn btn-secondary">Clear</a>
            </div>
        </form>
    </div>

    <?php if (isset($_GET['status']) && $_GET['status'] === 'created'): ?>
        <div class="alert alert-success">Training session created successfully!</div>
    <?php endif; ?>

    <div class="card shadow-sm border-0 rounded-4">
        <div class="card-body">
            <?php if (empty($sessions)): ?>
                <div class="text-center p-4">
                    <p class="mb-0 text-muted">You haven't created any training sessions yet.</p>
                </div>
            <?php else: ?>
                <div class="list-group list-group-flush">
                    <?php foreach ($sessions as $session): ?>
                        <div class="list-group-item list-group-item-action d-flex justify-content-between align-items-center">
                             <a href="training_session.php?id=<?php echo $session['id']; ?>" class="text-decoration-none text-dark flex-grow-1">
                                <h5 class="mb-1"><?php echo htmlspecialchars($session['name']); ?></h5>
                                <p class="mb-1 text-muted small"><?php echo htmlspecialchars(substr($session['description'], 0, 100)); ?>...</p>
                            </a>
                            <div class="d-flex align-items-center">
                                <i class="material-icons favorite-icon me-3 <?php echo $session['is_favorite'] ? 'is-favorite' : ''; ?>" data-session-id="<?php echo $session['id']; ?>">
                                    <?php echo $session['is_favorite'] ? 'favorite' : 'favorite_border'; ?>
                                </i>
                                <span class="badge bg-light text-dark rounded-pill"><?php echo date("M d, Y", strtotime($session['created_at'])); ?></span>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>
</main>

<script>
document.querySelectorAll('.favorite-icon').forEach(icon => {
    icon.addEventListener('click', function(e) {
        e.preventDefault();
        const sessionId = this.dataset.sessionId;
        const isFavorited = this.textContent.trim() === 'favorite';
        
        const formData = new FormData();
        formData.append('session_id', sessionId);

        fetch('toggle_favorite.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                if (data.status === 'added') {
                    this.textContent = 'favorite';
                    this.classList.add('is-favorite');
                } else {
                    this.textContent = 'favorite_border';
                    this.classList.remove('is-favorite');
                }
            } else {
                alert(data.message || 'An error occurred.');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('An error occurred while favoriting this session.');
        });
    });
});
</script>

<?php require_once __DIR__ . '/partials/footer.php'; ?>
