<?php
$leagues = $conn->query("SELECT leagues.id, leagues.name AS league_name, countries.name AS country_name 
                         FROM leagues 
                         JOIN countries ON leagues.country_id = countries.id");

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_club'])) {
    $club_name = $_POST['club_name'];
    $league_id = $_POST['league_id'];
    $image_name = $_FILES['club_image']['name'];
    $image_tmp_name = $_FILES['club_image']['tmp_name'];
    $target_dir = "uploads/";
    $target_file = $target_dir . basename($image_name);

    if (move_uploaded_file($image_tmp_name, $target_file)) {
        $stmt = $conn->prepare("INSERT INTO clubs (name, image, league_id) VALUES (?, ?, ?)");
        $stmt->bind_param("ssi", $club_name, $target_file, $league_id);
        $stmt->execute();
        echo "Club '$club_name' added successfully!";
    } else {
        echo "Error uploading club image.";
    }
}
?>

<form method="POST" enctype="multipart/form-data">
    <input type="text" name="club_name" placeholder="Club Name" required>
    <input type="file" name="club_image" required>
    <select name="league_id" required>
        <option value="">Select League</option>
        <?php while ($row = $leagues->fetch_assoc()): ?>
            <option value="<?= $row['id'] ?>"><?= $row['league_name'] ?> (<?= $row['country_name'] ?>)</option>
        <?php endwhile; ?>
    </select>
    <button type="submit" name="add_club">Add Club</button>
</form>
