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

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

$pageTitle = 'Create Training Session';
$pageDescription = 'Build a new training session from your drills.';

$coach_id = get_user_id();
$pdo = db();
$errors = [];

// Fetch the coach's drills
$stmt = $pdo->prepare("SELECT id, title FROM drills WHERE coach_id = ? ORDER BY title");
$stmt->execute([$coach_id]);
$drills = $stmt->fetchAll(PDO::FETCH_ASSOC);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $selected_drills = $_POST['drills'] ?? [];

    if (empty($name)) $errors[] = 'Session name is required.';
    if (empty($selected_drills)) $errors[] = 'You must select at least one drill.';

    if (empty($errors)) {
        try {
            $pdo->beginTransaction();

            // Insert the new session
            $stmt = $pdo->prepare("INSERT INTO training_sessions (coach_id, name, description) VALUES (?, ?, ?)");
            $stmt->execute([$coach_id, $name, $description]);
            $session_id = $pdo->lastInsertId();

            // Link drills to the session
            $stmt = $pdo->prepare("INSERT INTO training_session_drills (session_id, drill_id, sequence) VALUES (?, ?, ?)");
            $sequence = 0;
            foreach ($selected_drills as $drill_id) {
                $stmt->execute([$session_id, $drill_id, ++$sequence]);
            }

            $pdo->commit();
            header('Location: training_sessions.php?status=created');
            exit();

        } catch (PDOException $e) {
            $pdo->rollBack();
            $errors[] = "Database error: " . $e->getMessage();
        }
    }
}
?>

<main class="container my-5">
    <div class="row justify-content-center">
        <div class="col-lg-8">
            <div class="card shadow-sm border-0 rounded-4">
                <div class="card-body p-4">
                    <h1 class="h3 mb-4 text-center">Create a New Training Session</h1>

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

                    <form action="create_training_session.php" method="POST">
                        <div class="form-floating mb-3">
                            <input type="text" class="form-control" id="name" name="name" placeholder="Session Name" required value="<?php echo htmlspecialchars($_POST['name'] ?? ''); ?>">
                            <label for="name">Session Name</label>
                        </div>

                        <div class="form-floating mb-3">
                            <textarea class="form-control" id="description" name="description" placeholder="Session Description" style="height: 120px;"><?php echo htmlspecialchars($_POST['description'] ?? ''); ?></textarea>
                            <label for="description">Description (Optional)</label>
                        </div>

                        <div class="mb-4">
                            <label class="form-label">Select Drills</label>
                            <div class="list-group" style="max-height: 300px; overflow-y: auto;">
                                <?php if (empty($drills)): ?>
                                    <div class="list-group-item">You have no drills to add. <a href="create_drill.php">Create one now</a>.</div>
                                <?php else: ?>
                                    <?php foreach ($drills as $drill): ?>
                                        <label class="list-group-item">
                                            <input class="form-check-input me-2" type="checkbox" name="drills[]" value="<?php echo $drill['id']; ?>" <?php echo in_array($drill['id'], $_POST['drills'] ?? []) ? 'checked' : ''; ?>>
                                            <?php echo htmlspecialchars($drill['title']); ?>
                                        </label>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </div>
                            <div class="form-text">Select one or more drills to include in this session.</div>
                        </div>

                        <div class="d-grid">
                            <button type="submit" class="btn btn-primary btn-lg">Create Session</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</main>

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