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

// Function to resize and compress the image
function resizeImage($source, $destination, $width, $height, $max_size_kb = 10) {
    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);

    $quality = 90; // Initial compression quality
    do {
        ob_start();
        switch ($image_type) {
            case IMAGETYPE_JPEG:
                imagejpeg($image_p, null, $quality);
                break;
            case IMAGETYPE_PNG:
                imagepng($image_p, null);
                break;
            case IMAGETYPE_GIF:
                imagegif($image_p, null);
                break;
        }
        $compressed_image = ob_get_clean();
        $size_kb = strlen($compressed_image) / 1024;

        if ($size_kb <= $max_size_kb) {
            file_put_contents($destination, $compressed_image);
            return true;
        }

        $quality -= 5; // Reduce quality for further compression
    } while ($quality > 10);

    return false; // Return false if unable to compress to the required size
} 

if (isset($_GET['league_id'])) {
    $league_id = intval($_GET['league_id']);

    // Handle image upload
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['cup_image'])) {
        $upload_dir = "../cups/";
        $file_name = basename($_FILES['cup_image']['name']);
        $target_file = $upload_dir . $file_name; 

        if (move_uploaded_file($_FILES['cup_image']['tmp_name'], $target_file)) {
            // Resize and compress the uploaded image
            $resized_file = $upload_dir . "resized_" . $file_name;
            if (resizeImage($target_file, $resized_file, 300, 300, 10)) {
                // Update league cup image in the database
                $conn->query("UPDATE leagues SET cup_image = '$resized_file' WHERE id = $league_id");
                echo "Cup image uploaded and resized successfully.";
            } else {
                echo "Failed to resize the cup image to the required size.";
            }
        } else {
            echo "Failed to upload cup image.";
        }
    }

    // Fetch league details
    $result = $conn->query("SELECT name, cup_image FROM leagues WHERE id = $league_id");
    if ($result->num_rows > 0) {
        $league = $result->fetch_assoc();
        ?>
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Add/View League Cup Image</title>
        </head>
        <body>
            <h2>League: <?= htmlspecialchars($league['name']) ?></h2>

            <?php if (!empty($league['cup_image'])) { ?>
                <p>Current League Cup Image:</p>
                <img src="../<?= htmlspecialchars($league['cup_image']) ?>" alt="League Cup Image" width="200">
            <?php } else { ?>
                <p>No League Cup Image Uploaded Yet.</p>
            <?php } ?>

            <form action="" method="POST" enctype="multipart/form-data">
                <label for="cup_image">Upload New Cup Image:</label>
                <input type="file" name="cup_image" id="cup_image" required>
                <button type="submit">Upload</button>
            </form>

            <br>
            <a href="index.php">Back to Data Management</a>
        </body>
        </html>
        <?php
    } else {
        echo "League not found.";
    }
} else {
    echo "Invalid league ID.";
}
?>
