<?php
include("config.php");

// Function to resize and save an image
function resizeImage($source, $destination, $width, $height) {
    list($original_width, $original_height, $image_type) = getimagesize($source);
    $ratio = $original_width / $original_height;

    if ($width / $height > $ratio) {
        $width = (int)($height * $ratio);
    } else {
        $height = (int)($width / $ratio);
    }

    $image_p = imagecreatetruecolor($width, $height);

    switch ($image_type) {
        case IMAGETYPE_JPEG:
            $image = imagecreatefromjpeg($source);
            break;
        case IMAGETYPE_PNG:
            $image = imagecreatefrompng($source);
            break;
        case IMAGETYPE_GIF:
            $image = imagecreatefromgif($source);
            break;
        default:
            return false;
    }

    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $original_width, $original_height);

    switch ($image_type) {
        case IMAGETYPE_JPEG:
            imagejpeg($image_p, $destination, 90);
            break;
        case IMAGETYPE_PNG:
            imagepng($image_p, $destination);
            break;
        case IMAGETYPE_GIF:
            imagegif($image_p, $destination);
            break;
    }

    return true;
}

// Add Country
if (isset($_POST['add_country'])) {
    $country_name = $_POST['country_name'];

    // Check for duplicate country
    $check = $conn->prepare("SELECT id FROM countries WHERE name = ?");
    $check->bind_param("s", $country_name);
    $check->execute();
    $check->store_result();

    if ($check->num_rows > 0) {
        echo "Error: Country already exists!";
    } else {
        $flag_path = null;

        if (!empty($_FILES['flag']['tmp_name'])) {
            $upload_dir = '../flags/';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }

            $flag_filename = uniqid() . '_' . basename($_FILES['flag']['name']);
            $flag_full_path = $upload_dir . $flag_filename;

            if (resizeImage($_FILES['flag']['tmp_name'], $flag_full_path, 70, 50)) {
                $flag_path = 'flags/' . $flag_filename;
            }
        }

        $stmt = $conn->prepare("INSERT INTO countries (name, flag) VALUES (?, ?)");
        $stmt->bind_param("ss", $country_name, $flag_path);

        if ($stmt->execute()) {
            echo "Country added successfully!";
        } else {
            echo "Error: " . $stmt->error;
        }
    }
}

// Add League
if (isset($_POST['add_league'])) {
    $league_name = $_POST['league_name'];
    $country_id = $_POST['country_id'];

    // Check for duplicate league
    $check = $conn->prepare("SELECT id FROM leagues WHERE name = ? AND country_id = ?");
    $check->bind_param("si", $league_name, $country_id);
    $check->execute();
    $check->store_result();

    if ($check->num_rows > 0) {
        echo "Error: League already exists!";
    } else {
        $league_image_path = null;

        if (!empty($_FILES['league_image']['tmp_name'])) {
            $upload_dir = '../leagues/';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }

            $league_filename = uniqid() . '_' . basename($_FILES['league_image']['name']);
            $league_full_path = $upload_dir . $league_filename;

            if (resizeImage($_FILES['league_image']['tmp_name'], $league_full_path, 100, 100)) {
                $league_image_path = 'leagues/' . $league_filename;
            }
        }

        $stmt = $conn->prepare("INSERT INTO leagues (name, country_id, image) VALUES (?, ?, ?)");
        $stmt->bind_param("sis", $league_name, $country_id, $league_image_path);

        if ($stmt->execute()) {
            echo "League added successfully!";
        } else {
            echo "Error: " . $stmt->error;
        }
    }
}

// Add Club
if (isset($_POST['add_club'])) {
    $club_name = $_POST['club_name'];
    $league_id = $_POST['league_id'];

    // Check for duplicate club
    $check = $conn->prepare("SELECT id FROM clubs WHERE club_name = ? AND league_id = ?");
    $check->bind_param("si", $club_name, $league_id);
    $check->execute();
    $check->store_result();

    if ($check->num_rows > 0) {
        echo "Error: Club already exists!";
    } else {
        $club_image_path = null;

        if (!empty($_FILES['club_image']['tmp_name'])) {
            $upload_dir = '../clubs/';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }

            $club_filename = uniqid() . '_' . basename($_FILES['club_image']['name']);
            $club_full_path = $upload_dir . $club_filename;

            if (resizeImage($_FILES['club_image']['tmp_name'], $club_full_path, 100, 100)) {
                $club_image_path = 'clubs/' . $club_filename;
            }
        }

        $stmt = $conn->prepare("INSERT INTO clubs (club_name, league_id, image) VALUES (?, ?, ?)");
        $stmt->bind_param("sis", $club_name, $league_id, $club_image_path);

        if ($stmt->execute()) {
            echo "Club added successfully!";
        } else {
            echo "Error: " . $stmt->error;
        }
    }
}

// Fetch countries, leagues, and clubs
$countries = $conn->query("SELECT id, name, flag FROM countries ORDER BY name ASC");
$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 ORDER BY leagues.name ASC");
$clubs = $conn->query("SELECT clubs.club_name, leagues.name AS league_name FROM clubs JOIN leagues ON clubs.league_id = leagues.id ORDER BY clubs.club_name ASC");
?>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Countries, Leagues, and Clubs</title>
    <style>/* Global Reset */
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

/* Container for Form */
.form-container {
    max-width: 800px; /* Limit width for desktop */
    margin: 20px auto;
    padding: 20px;
    background: #f9f9f9;
    border: 1px solid #ddd;
    border-radius: 10px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

/* Form Header */
.form-container h1 {
    font-size: 24px;
    margin-bottom: 20px;
    text-align: center;
    color: #333;
}

/* Form Elements */
form {
    display: flex;
    flex-direction: column;
    gap: 15px;
}

label {
    font-size: 16px;
    color: #555;
    margin-bottom: 5px;
}

input[type="text"], select, input[type="file"] {
    width: 100%;
    padding: 10px;
    font-size: 14px;
    border: 1px solid #ccc;
    border-radius: 5px;
    outline: none;
    transition: border-color 0.3s ease-in-out;
}

input[type="text"]:focus, select:focus, input[type="file"]:focus {
    border-color: #007bff;
}

button {
    padding: 12px 20px;
    font-size: 16px;
    color: #fff;
    background-color: #007bff;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    transition: background-color 0.3s ease-in-out;
}

button:hover {
    background-color: #0056b3;
}

/* Desktop Styles */
@media (min-width: 768px) {
    .form-container {
        padding: 30px;
    }

    form {
        flex-direction: row; /* Align items side by side */
        flex-wrap: wrap;
        gap: 20px;
    }

    label {
        flex: 1 1 100%;
    }

    input[type="text"], select, input[type="file"], button {
        flex: 1 1 calc(50% - 20px); /* Half width on desktop */
        margin-bottom: 0;
    }

    button {
        flex: 1 1 100%; /* Full width for submit button */
    }
}

/* Mobile Styles */
@media (max-width: 767px) {
    .form-container {
        padding: 15px;
    }

    form {
        flex-direction: column;
    }

    input[type="text"], select, input[type="file"], button {
        width: 100%; /* Full width on mobile */
    }

    button {
        margin-top: 15px;
    }
}
</style>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    
    <div class="container">
    <div class="form-container">
    


    <h1>Add League</h1>
    <form method="POST" enctype="multipart/form-data">
        <input type="text" name="league_name" placeholder="League Name" required>
        <select name="country_id" required>
            <option value="">Select Country</option>
            <?php while ($row = $countries->fetch_assoc()) { ?>
                <option value="<?= $row['id'] ?>"><?= $row['name'] ?></option>
            <?php } ?>
        </select>
        <input type="file" name="league_image" accept="image/*" required>
        <button type="submit" name="add_league">Add League</button>
    </form>

    <br>
     <br>
      <br>
      
    <hr>
    
   <h1>Add Club</h1>
<form method="POST" enctype="multipart/form-data">
    <label for="country">Select Country:</label>
    <select name="country_id" id="country" required>
        <option value="">Select Country</option>
        <?php
        $countries = $conn->query("SELECT id, name FROM countries ORDER BY name ASC");
        while ($row = $countries->fetch_assoc()) { ?>
            <option value="<?= $row['id'] ?>"><?= $row['name'] ?></option>
        <?php } ?>
    </select>

    <label for="league">Select League:</label>
    <select name="league_id" id="league" required>
        <option value="">Select League</option>
    </select>

    <input type="text" name="club_name" placeholder="Club Name" required>
    <input type="file" name="club_image" accept="image/*">
    <button type="submit" name="add_club">Add Club</button>
</form>

</div>  </div>
    <script>
        $('#country').change(function() {
            var country_id = $(this).val();
            if (country_id) {
                $.ajax({
                    url: 'get_leagues.php',
                    method: 'POST',
                    data: { country_id: country_id },
                    success: function(response) {
                        $('#league').html(response);
                    }
                });
            } else {
                $('#league').html('<option value="">Select League</option>');
            }
        });
    </script>
    
<h2>Data Management</h2>

<table border="1" width="100%">
    <thead>
        <tr>
            <th>Type</th>
            <th>Image/Flag</th>
            <th>Name</th>
            <th>Additional Info</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        <?php
        

        // Fetch leagues
        $leagues = $conn->query("SELECT leagues.id, leagues.name, leagues.image, countries.name AS country_name 
                                FROM leagues 
                                JOIN countries ON leagues.country_id = countries.id 
                                ORDER BY leagues.name ASC");
        while ($row = $leagues->fetch_assoc()) { ?>
            <tr>
                <td>League</td>
                <td><img src="../<?= $row['image'] ?>" alt="League Image" width="50" height="50"></td>
                <td><?= htmlspecialchars($row['name']) ?></td>
                <td>Country: <?= htmlspecialchars($row['country_name']) ?></td>
                <td>
                    <a href="?delete=true&type=league&id=<?= $row['id'] ?>" onclick="return confirm('Are you sure you want to delete this league?');">Delete</a>
                </td>
            </tr>
        <?php }

        // Fetch clubs
        $clubs = $conn->query("SELECT clubs.id, clubs.club_name, clubs.image, leagues.name AS league_name 
                                FROM clubs 
                                JOIN leagues ON clubs.league_id = leagues.id 
                                ORDER BY clubs.club_name ASC");
        while ($row = $clubs->fetch_assoc()) { ?>
            <tr>
                <td>Club</td>
                <td><img src="../<?= $row['image'] ?>" alt="Club Image" width="50" height="50"></td>
                <td><?= htmlspecialchars($row['club_name']) ?></td>
                <td>League: <?= htmlspecialchars($row['league_name']) ?></td>
                <td>
                    <a href="?delete=true&type=club&id=<?= $row['id'] ?>" onclick="return confirm('Are you sure you want to delete this club?');">Delete</a>
                </td>
            </tr>
        <?php } ?>
    </tbody>
</table>

<?php
// Handle deletion
if (isset($_GET['delete'])) {
    $type = $_GET['type']; // "country", "league", or "club"
    $id = intval($_GET['id']); // ID of the record to delete

    if ($type === 'country') {
        $stmt = $conn->prepare("DELETE FROM countries WHERE id = ?");
    } elseif ($type === 'league') {
        $stmt = $conn->prepare("DELETE FROM leagues WHERE id = ?");
    } elseif ($type === 'club') {
        $stmt = $conn->prepare("DELETE FROM clubs WHERE id = ?");
    } else {
        die("Invalid type!");
    }

    $stmt->bind_param("i", $id);

    if ($stmt->execute()) {
        echo "<script>alert('" . ucfirst($type) . " deleted successfully!');</script>";
    } else {
        echo "<script>alert('Error deleting " . $type . ": " . $stmt->error . "');</script>";
    }
}
?>
<style>
    table {
        border-collapse: collapse;
        width: 100%;
        margin: 20px 0;
    }
    th, td {
        border: 1px solid #ddd;
        padding: 8px;
        text-align: left;
    }
    th {
        background-color: #f4f4f4;
        font-weight: bold;
    }
    tr:hover {
        background-color: #f1f1f1;
    }
    img {
        border-radius: 5px;
    }
    a {
        color: red;
        text-decoration: none;
    }
    a:hover {
        text-decoration: underline;
    }
</style>


</body>
</html>
