<?php
$pageTitle = 'Manage Leagues';
include_once 'includes/header.php';

$league = new League();
$season_model = new Season(); // To fetch seasons for the dropdown
$message = '';
$error = '';

// Handle deletion
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['delete_id'])) {
    $delete_id = filter_input(INPUT_GET, 'delete_id', FILTER_VALIDATE_INT);
    if ($delete_id && $league->delete($delete_id)) {
        $_SESSION['flash_message'] = 'League deleted successfully!';
    } else {
        $_SESSION['flash_message'] = 'Failed to delete league. It might have associated clubs.';
    }
    header('Location: manage_leagues.php');
    exit();
}

// Handle form submission for creating a new league
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_league'])) {
    $name = trim($_POST['name'] ?? '');
    $country = trim($_POST['country'] ?? '');
    $season = trim($_POST['season'] ?? '');

    if (empty($name) || empty($country) || empty($season)) {
        $error = 'All fields are required.';
    } 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', 'svg'];

            if (in_array($file_ext, $allowed_ext)) {
                $logo_filename = uniqid('league_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, WEBP, and SVG are allowed.';
            }
        }

        $leagueData = [
            'name' => $name,
            'country' => $country,
            'season' => $season,
            'manager_id' => $_SESSION['admin_user_id'],
            'logo' => $logo_path
        ];

        if ($league->create($leagueData)) {
            // Use a session flash message for success after redirect
            $_SESSION['flash_message'] = 'League created successfully!';
            header('Location: manage_leagues.php');
            exit();
        } else {
            $error = 'Failed to create league. Please try again.';
        }
    }
}

// Check for flash messages from redirects
if (isset($_SESSION['flash_message'])) {
    $message = $_SESSION['flash_message'];
    unset($_SESSION['flash_message']);
}

// Fetch all leagues for display
$all_seasons = $season_model->getAll();
$all_leagues = $league->getAllForAdmin();

include_once 'includes/sidebar.php';
?>

<h1>Manage Leagues</h1>

<!-- Display Messages -->
<?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; ?>

<!-- Create League Form -->
<div class="form-container">
    <h2>Create New League</h2>
    <form action="manage_leagues.php" method="POST" enctype="multipart/form-data">
        <div class="form-group"><label for="name">League Name</label><input type="text" name="name" id="name" required></div>
        <div class="form-group"><label for="country">Country</label><input type="text" name="country" id="country" required></div>
        <div class="form-group">
            <label for="logo">League 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="season">Season</label>
            <select name="season" id="season" required>
                <?php foreach ($all_seasons as $s): ?>
                    <option value="<?php echo htmlspecialchars($s->name); ?>"><?php echo htmlspecialchars($s->name); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <button type="submit" name="create_league" class="btn">Create League</button>
    </form>
</div>

<!-- List of Existing Leagues -->
<h2>Existing Leagues</h2>
<table class="styled-table">
    <thead><tr><th>ID</th><th>Logo</th><th>Name</th><th>Country</th><th>Season</th><th>Manager</th><th>Actions</th></tr></thead>
    <tbody>
        <?php foreach ($all_leagues as $l): ?>
            <tr>
                <td><?php echo $l->id; ?></td>
                <td><?php if (!empty($l->logo)): ?><img src="<?php echo htmlspecialchars($l->logo); ?>" alt="<?php echo htmlspecialchars($l->name); ?> Logo" style="width: 40px; height: 40px; object-fit: contain;"><?php endif; ?></td>
                <td><?php echo htmlspecialchars($l->name); ?></td>
                <td><?php echo htmlspecialchars($l->country); ?></td>
                <td><?php echo htmlspecialchars($l->season); ?></td>
                <td><?php echo htmlspecialchars($l->manager_username ?? 'N/A'); ?></td>
                <td class="actions-cell">
                    <a href="edit_league.php?id=<?php echo $l->id; ?>" class="btn-sm btn-edit">Edit</a>
                    <a href="?delete_id=<?php echo $l->id; ?>" class="btn-sm btn-delete" onclick="return confirm('Are you sure you want to delete this league?');">Delete</a>
                </td>
            </tr>
        <?php endforeach; ?>
    </tbody>
</table>

<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'; ?>