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

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

$session_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if (!$session_id) {
    header('Location: training_sessions.php');
    exit();
}

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

// Fetch the training session
$stmt = $pdo->prepare("SELECT * FROM training_sessions WHERE id = ? AND coach_id = ?");
$stmt->execute([$session_id, $coach_id]);
$session = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$session) {
    header('Location: training_sessions.php');
    exit();
}

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

// Fetch the drills currently in the session
$stmt = $pdo->prepare("SELECT drill_id FROM training_session_drills WHERE session_id = ?");
$stmt->execute([$session_id]);
$session_drill_ids = $stmt->fetchAll(PDO::FETCH_COLUMN);

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();

            // Update the session details
            $stmt = $pdo->prepare("UPDATE training_sessions SET name = ?, description = ? WHERE id = ?");
            $stmt->execute([$name, $description, $session_id]);

            // Delete existing drill associations
            $stmt = $pdo->prepare("DELETE FROM training_session_drills WHERE session_id = ?");
            $stmt->execute([$session_id]);

            // Insert new drill associations
            $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_session.php?id=' . $session_id . '&status=updated');
            exit();

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

$pageTitle = 'Edit Training Session';
?>

<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">Edit 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="edit_training_session.php?id=<?php echo $session_id; ?>" 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($session['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($session['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 foreach ($all_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'], $session_drill_ids) ? 'checked' : ''; ?>>
                                        <?php echo htmlspecialchars($drill['title']); ?>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                        </div>

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

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