<?php
$pageTitle = 'Add New Club';
include_once 'includes/header.php';

$clubModel = new Club();
$leagueModel = new League();
$message = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $stadium = trim($_POST['stadium'] ?? '');
    $league_id = filter_input(INPUT_POST, 'league_id', FILTER_VALIDATE_INT);

    if (empty($name) || empty($league_id)) {
        $error = 'Club name and league are required.';
    } elseif ($clubModel->findByName($name)) {
        $error = 'A club with this name already exists.';
    } else {
        $logo_path = null;
        if (isset($_FILES['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
            $upload_dir = '../uploads/logos/';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }
            $file_ext = strtolower(pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION));
            $allowed_ext = ['jpg', 'jpeg', 'png', 'gif', 'webp'];

            if (in_array($file_ext, $allowed_ext)) {
                $logo_filename = uniqid('club_logo_', true) . '.' . $file_ext;
                $logo_path = $upload_dir . $logo_filename;

                if (!move_uploaded_file($_FILES['logo']['tmp_name'], $logo_path)) {
                    $error = 'Failed to upload logo.';
                    $logo_path = null; // Reset path on failure
                }
            } else {
                $error = 'Invalid file type. Only JPG, PNG, GIF, and WEBP are allowed.';
            }
        }

        $clubData = ['name' => $name, 'stadium' => $stadium, 'league_id' => $league_id, 'logo' => $logo_path];
        if ($clubModel->create($clubData)) {
            $_SESSION['flash_message'] = "Club '{$name}' created successfully!";
            header('Location: manage_clubs.php');
            exit();
        } else {
            $error = 'Failed to create club.';
        }
    }
}

$leagues = $leagueModel->getAll();
include_once 'includes/sidebar.php';
?>

<h1>Add New Club</h1>

<?php if ($message): ?><div class="message success"><?php echo $message; ?></div><?php endif; ?>
<?php if ($error): ?><div class="message error"><?php echo $error; ?></div><?php endif; ?>

<div class="form-container">
    <form action="add_club.php" method="POST" enctype="multipart/form-data">
        <div class="form-group">
            <label for="name">Club Name</label>
            <input type="text" name="name" id="name" required>
        </div>
        <div class="form-group">
            <label for="stadium">Stadium</label>
            <input type="text" name="stadium" id="stadium">
        </div>
        <div class="form-group">
            <label for="logo">Club Logo</label>
            <input type="file" name="logo" id="logo" onchange="previewLogo(event)">
            <img id="logo-preview" src="#" alt="Logo Preview" style="display:none; max-width: 100px; margin-top: 10px;"/>
        </div>
        <div class="form-group">
            <label for="league_id">League</label>
            <select name="league_id" id="league_id" required>
                <option value="">-- Select a League --</option>
                <?php foreach ($leagues as $league): ?>
                    <option value="<?php echo $league->id; ?>"><?php echo htmlspecialchars($league->name); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <button type="submit" class="btn">Create Club</button>
    </form>
</div>

<script>
function previewLogo(event) {
    var reader = new FileReader();
    reader.onload = function(){
        var output = document.getElementById('logo-preview');
        output.src = reader.result;
        output.style.display = 'block';
    };
    reader.readAsDataURL(event.target.files[0]);
}
</script>

<?php include_once 'includes/footer.php'; ?>