<?php
$page_title = 'Edit Club';
include_once 'includes/header.php';

$clubModel = new Club();
$userModel = new User();
$leagueModel = new League();

$club_id = $_GET['id'] ?? null;
$club = null;
$leagues = $leagueModel->getAll();
$errors = [];
$success_message = '';

$clubManagers = $userModel->getUsersByRole('club_manager');
if (!$club_id) {
    header('Location: manage_clubs.php');
    exit;
}

$club = $clubModel->findById($club_id);

if (!$club) {
    header('Location: manage_clubs.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name']);
    $stadium = trim($_POST['stadium']);
    $club_manager_id = $_POST['club_manager_id'];
    $league_id = $_POST['league_id'];

    if (empty($name)) {
        $errors[] = 'Club name is required.';
    }

   if (empty($league_id)) {
        $errors[] = 'Please assign the club to a league.';
    }

    $new_logo_path = $club->logo; // Keep old logo by default
    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)) {
            // Delete old logo if it exists
            if ($club->logo && file_exists($club->logo)) {
                unlink($club->logo);
            }

            $logo_filename = uniqid('club_logo_', true) . '.' . $file_ext;
            $new_logo_path = $upload_dir . $logo_filename;

            if (!move_uploaded_file($_FILES['logo']['tmp_name'], $new_logo_path)) {
                $error = 'Failed to upload new logo.';
                $new_logo_path = $club->logo; // Revert to old logo on failure
            }
        } else {
            $error = 'Invalid file type. Only JPG, PNG, GIF, and WEBP are allowed.';
        }
    }

    if (empty($errors)) {
        $data = [
            'id' => $club_id,
            'name' => $name,
            'stadium' => $stadium,
            'league_id' => $league_id,
            'manager_id' => $club_manager_id,
            'logo' => $new_logo_path
        ];

        if ($clubModel->update($data)) {
            $success_message = 'Club updated successfully!';
            // Refresh club data to show in form
            $club = $clubModel->findById($club_id);
        } else {
            $errors[] = 'Failed to update club. Please try again.';
        }
    }
}

include_once 'includes/sidebar.php';
?>
<h1>Edit Club: <?php echo htmlspecialchars($club->name); ?></h1>

<div class="form-container">
    <?php if (!empty($errors)): ?>
        <div class="message error"><?php echo implode('<br>', $errors); ?></div>
    <?php endif; ?>
    <?php if ($success_message): ?>
        <div class="message success"><?php echo $success_message; ?></div>
    <?php endif; ?>

    <form action="edit_club.php?id=<?php echo htmlspecialchars($club->id); ?>" method="post" enctype="multipart/form-data">
        <div class="form-group">
            <label for="name">Club Name</label>
            <input type="text" name="name" id="name" class="form-control" value="<?php echo htmlspecialchars($club->name); ?>" required>
        </div>
        <div class="form-group">
            <label for="stadium">Stadium</label>
            <input type="text" name="stadium" id="stadium" class="form-control" value="<?php echo htmlspecialchars($club->stadium); ?>">
        </div>
        <div class="form-group">
            <label for="logo">Club Logo</label>
            <input type="file" name="logo" id="logo" onchange="previewLogo(event)">
            <div style="margin-top: 10px;">
                <p>Current Logo:</p>
                <img id="logo-preview" src="<?php echo !empty($club->logo) ? htmlspecialchars($club->logo) : '#'; ?>" alt="Logo Preview" style="max-width: 100px; <?php echo empty($club->logo) ? 'display:none;' : ''; ?>">
                <?php if(empty($club->logo)): ?><p>No logo uploaded.</p><?php endif; ?>
            </div>
        </div>
        <div class="form-group">
            <label for="league_id">League</label>
            <select name="league_id" id="league_id" class="form-control" required>
                <option value="">-- Select League --</option>
                <?php foreach ($leagues as $league): ?>
                    <option value="<?php echo $league->id; ?>" <?php echo ($club->league_id == $league->id) ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($league->name); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="form-group">
            <label for="club_manager_id">Club Manager</label>
            <select name="club_manager_id" id="club_manager_id" class="form-control">
                <option value="">-- Select Club Manager --</option>
                <?php foreach ($clubManagers as $manager): ?>
                <option value="<?php echo $manager->id; ?>" <?php echo ($club->manager_id == $manager->id) ? 'selected' : ''; ?>><?php echo htmlspecialchars($manager->first_name . ' ' . $manager->last_name); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <button type="submit" class="btn">Save Changes</button>
        <a href="manage_clubs.php" class="btn btn-secondary">Back to Clubs</a>
    </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'; ?>