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

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

    // Fetch current club name
    $club_result = $conn->query("SELECT club_name FROM clubs WHERE id = $club_id");
    $club = $club_result->fetch_assoc();
    if (!$club) {
        echo "Club not found.";
        exit;
    }

    // Handle form submission for adding a new footballer
    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 = '';
        if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
            $image_tmp = $_FILES['image']['tmp_name'];
            $image_size = $_FILES['image']['size'];
            $image_name = uniqid('player_') . '.' . pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
            $image_dir = '../footballers/' . $image_name;

            $max_size = 200 * 1024; // 200KB

            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $mime_type = finfo_file($finfo, $image_tmp);
            finfo_close($finfo);

            $allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
            if (!in_array($mime_type, $allowed_types)) {
                echo "<p>Invalid image format. Only JPEG, PNG, and GIF are allowed.</p>";
                exit;
            }

            if ($image_size > $max_size) {
                resizeImageWithWatermark($image_tmp, $image_dir, 650, 440, 'logo.png');
            } else {
                move_uploaded_file($image_tmp, $image_dir);
            }
        } else {
            echo "<p>No image uploaded or error during upload.</p>";
            exit;
        }

        // Insert the data into the footballers table
        $stmt = $conn->prepare("INSERT INTO footballers (player_name, position, squad_status, health_status, weekly_salary, image, jersey_number, achievements, history, date_of_birth, club_id) 
                                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("ssssdsdsssi", $player_name, $position, $squad_status, $health_status, $weekly_salary, $image_name, $jersey_number, $achievements, $history, $date_of_birth, $club_id);

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

        $stmt->close();
    }

    // Fetch footballers for the current club
    $footballers_result = $conn->query("SELECT * FROM footballers WHERE club_id = $club_id");
} else {
    echo "Invalid club ID.";
    exit;
}

// Function to resize image and apply watermark
function resizeImageWithWatermark($source, $destination, $newWidth, $newHeight, $watermarkPath) {
    $imageFormat = strtolower(pathinfo($destination, PATHINFO_EXTENSION));
    $sourceImage = null;

    switch ($imageFormat) {
        case 'jpeg':
        case 'jpg':
            $sourceImage = imagecreatefromjpeg($source);
            break;
        case 'png':
            $sourceImage = imagecreatefrompng($source);
            break;
        case 'gif':
            $sourceImage = imagecreatefromgif($source);
            break;
        default:
            echo "<p>Unsupported image format.</p>";
            return false;
    }

    $resizedImage = imagescale($sourceImage, $newWidth, $newHeight);
    $watermark = imagecreatefrompng($watermarkPath);

    $watermarkWidth = imagesx($watermark);
    $watermarkHeight = imagesy($watermark);

    $watermarkX = 10;  // Adjust as needed
    $watermarkY = 50;  // Adjust as needed

    imagecopy($resizedImage, $watermark, $watermarkX, $watermarkY, 0, 0, $watermarkWidth, $watermarkHeight);

    switch ($imageFormat) {
        case 'jpeg':
        case 'jpg':
            imagejpeg($resizedImage, $destination);
            break;
        case 'png':
            imagepng($resizedImage, $destination);
            break;
        case 'gif':
            imagegif($resizedImage, $destination);
            break;
    }

    imagedestroy($sourceImage);
    imagedestroy($resizedImage);
    imagedestroy($watermark);
    return true;
}
?>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Footballers - <?= htmlspecialchars($club['club_name']) ?></title>
    <style>
    body {
        font-family: Arial, sans-serif;
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }

    h2 {
        text-align: center;
        margin: 20px;
    }

    form {
        margin: 20px auto;
        padding: 20px;
        max-width: 600px;
        background-color: #f9f9f9;
        border: 1px solid #ddd;
        border-radius: 8px;
    }

    input, select, textarea {
        margin: 10px 0;
        padding: 10px;
        width: 100%;
        border: 1px solid #ccc;
        border-radius: 5px;
    }

    button {
        padding: 10px 15px;
        background-color: #007bff;
        color: white;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        width: 100%;
    }

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

    table {
        width: 100%;
        border-collapse: collapse;
        margin: 20px auto;
        max-width: 1200px;
        background-color: #fff;
    }

    table, th, td {
        border: 1px solid #ddd;
    }

    th, td {
        padding: 10px;
        text-align: center;
        font-size: 14px;
    }

    .button-group a {
        padding: 8px 15px;
        background-color: #28a745;
        color: white;
        text-decoration: none;
        border-radius: 5px;
        display: inline-block;
        margin: 2px;
    }

    .button-group a:hover {
        background-color: #218838;
    }

    /* Responsive Styles */
    @media screen and (max-width: 768px) {
        form, table {
            width: 95%;
        }

        table, th, td {
            font-size: 12px;
            padding: 5px;
        }

        button {
            width: 100%;
        }
    }

    @media screen and (max-width: 480px) {
        th, td {
            font-size: 10px;
            padding: 4px;
        }

        .button-group a {
            padding: 6px 10px;
            font-size: 12px;
        }
    }
</style>

</head>
<body>

<h2>Footballers of <?= htmlspecialchars($club['club_name']) ?></h2>

<!-- Form to add a new footballer -->
<form action="footballers.php?club_id=<?= $club_id ?>" method="POST" enctype="multipart/form-data">
    <label for="player_name">Player Name:</label>
    <input type="text" id="player_name" name="player_name" required>

    <label for="position">Position:</label>
    <select id="position" name="position" required>
        <option value="Goalkeeper">Goalkeeper</option>
        <option value="Defender">Defender</option>
        <option value="Midfielder">Midfielder</option>
        <option value="Winger">Winger</option>
        <option value="Striker">Striker</option>
    </select>

    <label for="squad_status">Squad Status:</label>
    <select id="squad_status" name="squad_status" required>
        <option value="First 11">First 11</option>
        <option value="Reserve">Reserve</option>
        <option value="Team">Team</option>
    </select>

    <label for="health_status">Health Status:</label>
    <select id="health_status" name="health_status" required>
        <option value="Healthy">Healthy</option>
        <option value="Injury">Injury</option>
    </select>

    <label for="weekly_salary">Weekly Salary:</label>
    <input type="number" id="weekly_salary" name="weekly_salary" step="0.01" required>

    <label for="jersey_number">Jersey Number:</label>
    <input type="number" id="jersey_number" name="jersey_number" required>

    <label for="image">Footballer Image:</label>
    <input type="file" id="image" name="image" accept="image/*" required>

    <label for="achievements">Achievements:</label>
    <textarea id="achievements" name="achievements"></textarea>

    <label for="history">History:</label>
    <textarea id="history" name="history"></textarea>

    <label for="date_of_birth">Date of Birth:</label>
    <input type="date" id="date_of_birth" name="date_of_birth" required>

    <button type="submit">Add Footballer</button>
</form>

<!-- List footballers belonging to the current club -->
<table>
    <thead>
        <tr>
            <th>Player Name</th>
            <th>Position</th>
            <th>Squad Status</th>
            <th>Health Status</th>
            <th>Weekly Salary</th>
            <th>Jersey Number</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
        <?php while ($footballer = $footballers_result->fetch_assoc()) : ?>
            <tr>
                <td><?= htmlspecialchars($footballer['player_name']) ?></td>
                <td><?= htmlspecialchars($footballer['position']) ?></td>
                <td><?= htmlspecialchars($footballer['squad_status']) ?></td>
                <td><?= htmlspecialchars($footballer['health_status']) ?></td>
                <td><?= htmlspecialchars($footballer['weekly_salary']) ?></td>
                <td><?= htmlspecialchars($footballer['jersey_number']) ?></td>
                <td class="button-group">
                    <a href="edit_footballer.php?id=<?= $footballer['id'] ?>">Edit</a> |
                    <a href="delete_footballer.php?id=<?= $footballer['id'] ?>">Delete</a>
                </td>
            </tr>
        <?php endwhile; ?>
    </tbody>
</table>

</body>
</html>
