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

if (isset($_GET['id'])) {
    $id = intval($_GET['id']);
    $result = $conn->query("SELECT * FROM footballers WHERE id = $id");
    $footballer = $result->fetch_assoc();

    if (!$footballer) {
        echo "Footballer not found.";
        exit;
    }

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $player_name = htmlspecialchars($_POST['player_name']);
        $position = htmlspecialchars($_POST['position']);
        $squad_status = htmlspecialchars($_POST['squad_status']);
        $health_status = htmlspecialchars($_POST['health_status']);
        $weekly_salary = floatval($_POST['weekly_salary']);
        $jersey_number = intval($_POST['jersey_number']);
        $achievements = htmlspecialchars($_POST['achievements']);
        $history = htmlspecialchars($_POST['history']);
        $date_of_birth = $_POST['date_of_birth'];

        $image_name = $footballer['image']; // Default to current image
        if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
            // Handle file upload and resizing
            $image_tmp = $_FILES['image']['tmp_name'];
            $image_name = uniqid('player_') . '.' . pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
            $target_path = "../footballers/" . $image_name;

            // Resize image to max width/height of 800px and reduce file size
            resizeImage($image_tmp, $target_path, 800);

            // Remove old image if a new one is uploaded
            if (!empty($footballer['image']) && file_exists("../footballers/" . $footballer['image'])) {
                unlink("../footballers/" . $footballer['image']);
            }
        }

        $stmt = $conn->prepare("UPDATE footballers 
                                SET player_name = ?, position = ?, squad_status = ?, health_status = ?, weekly_salary = ?, 
                                    image = ?, jersey_number = ?, achievements = ?, history = ?, date_of_birth = ? 
                                WHERE id = ?");
        $stmt->bind_param("ssssdsdsssi", $player_name, $position, $squad_status, $health_status, $weekly_salary, 
                                            $image_name, $jersey_number, $achievements, $history, $date_of_birth, $id);

        if ($stmt->execute()) {
            header("Location: footballers.php?club_id=" . $footballer['club_id']);
            exit;
        } else {
            echo "Error: " . $stmt->error;
        }
    }
} else {
    echo "Invalid ID.";
    exit;
}

// Function to resize the uploaded image
function resizeImage($source, $destination, $max_size) {
    list($width, $height, $type) = getimagesize($source);
    $ratio = $width / $height;

    if ($width > $max_size || $height > $max_size) {
        if ($ratio > 1) {
            $new_width = $max_size;
            $new_height = $max_size / $ratio;
        } else {
            $new_height = $max_size;
            $new_width = $max_size * $ratio;
        }

        $image_p = imagecreatetruecolor($new_width, $new_height);
        switch ($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, $new_width, $new_height, $width, $height);

        switch ($type) {
            case IMAGETYPE_JPEG:
                imagejpeg($image_p, $destination, 80); // Reduce quality for smaller file size
                break;
            case IMAGETYPE_PNG:
                imagepng($image_p, $destination, 8); // Reduce compression for smaller file size
                break;
            case IMAGETYPE_GIF:
                imagegif($image_p, $destination);
                break;
        }

        imagedestroy($image_p);
        imagedestroy($image);
    } else {
        move_uploaded_file($source, $destination); // No resizing needed
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Edit Footballer</title>
    <style>body {
    font-family: Arial, sans-serif;
    background-color: #f4f4f9;
    margin: 0;
    padding: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
}

h2 {
    text-align: center;
    color: #333;
    margin-bottom: 20px;
}

form {
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    max-width: 400px;
    width: 100%;
}

form label {
    display: block;
    font-weight: bold;
    margin-bottom: 5px;
    color: #555;
}

form input[type="text"],
form input[type="number"],
form input[type="date"],
form input[type="file"],
form select,
form textarea {
    width: 100%;
    padding: 10px;
    margin-bottom: 15px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 14px;
}

form textarea {
    resize: vertical;
    height: 100px;
}

form button {
    background-color: #007bff;
    color: #fff;
    border: none;
    padding: 10px 15px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 16px;
    width: 100%;
}

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

img {
    display: block;
    max-width: 100px;
    margin-bottom: 15px;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

form input[type="file"] {
    border: none;
    padding: 5px;
}

form select {
    cursor: pointer;
}

form button:focus {
    outline: none;
    box-shadow: 0 0 5px #007bff;
}
</style>
</head>
<body>
<h2>Edit Footballer</h2>

<form action="edit_footballer.php?id=<?= $id ?>" method="POST" enctype="multipart/form-data">
    <label for="player_name">Player Name:</label>
    <input type="text" id="player_name" name="player_name" value="<?= htmlspecialchars($footballer['player_name']) ?>" required><br>

    <label for="position">Position:</label>
    <select id="position" name="position">
        <option value="Goalkeeper" <?= $footballer['position'] === 'Goalkeeper' ? 'selected' : '' ?>>Goalkeeper</option>
        <option value="Defender" <?= $footballer['position'] === 'Defender' ? 'selected' : '' ?>>Defender</option>
        <option value="Midfielder" <?= $footballer['position'] === 'Midfielder' ? 'selected' : '' ?>>Midfielder</option>
        <option value="Forward" <?= $footballer['position'] === 'Forward' ? 'selected' : '' ?>>Forward</option>
    </select><br>

    <label for="squad_status">Squad Status:</label>
    <select id="squad_status" name="squad_status">
        <option value="First 11" <?= $footballer['squad_status'] === 'First 11' ? 'selected' : '' ?>>First 11</option>
        <option value="Reserve" <?= $footballer['squad_status'] === 'Reserve' ? 'selected' : '' ?>>Reserve</option>
    </select><br>

    <label for="health_status">Health Status:</label>
    <input type="text" id="health_status" name="health_status" value="<?= htmlspecialchars($footballer['health_status']) ?>"><br>

    <label for="weekly_salary">Weekly Salary:</label>
    <input type="number" id="weekly_salary" name="weekly_salary" value="<?= $footballer['weekly_salary'] ?>" step="0.01"><br>

    <label for="jersey_number">Jersey Number:</label>
    <input type="number" id="jersey_number" name="jersey_number" value="<?= $footballer['jersey_number'] ?>"><br>

    <label for="achievements">Achievements:</label>
    <textarea id="achievements" name="achievements"><?= htmlspecialchars($footballer['achievements']) ?></textarea><br>

    <label for="history">History:</label>
    <textarea id="history" name="history"><?= htmlspecialchars($footballer['history']) ?></textarea><br>

    <label for="date_of_birth">Date of Birth:</label>
    <input type="date" id="date_of_birth" name="date_of_birth" value="<?= $footballer['date_of_birth'] ?>"><br>

    <label for="image">Upload New Photo:</label>
    <input type="file" id="image" name="image"><br>

    <?php if (!empty($footballer['image'])): ?>
        <img src="../footballers/<?= htmlspecialchars($footballer['image']) ?>" alt="Current Photo" width="100">
    <?php endif; ?><br>

    <button type="submit">Update Footballer</button>
</form>
</body>
</html>
