<?php
$pageTitle = 'Edit League';
include_once 'includes/header.php';

$leagueModel = new League();
$seasonModel = new Season();
$userModel = new User();
$error = '';

$league_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if (!$league_id) {
    header('Location: manage_leagues.php');
    exit();
}

$league = $leagueModel->getById($league_id);
if (!$league) {
    header('Location: manage_leagues.php');
    exit();
}

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

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

            if (in_array($file_ext, $allowed_ext)) {
                // Delete old logo if it exists
                if ($league->logo && file_exists($league->logo)) {
                    unlink($league->logo);
                }

                $logo_filename = uniqid('league_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 = $league->logo; // Revert to old logo on failure
                }
            } else {
                $error = 'Invalid file type. Only JPG, PNG, GIF, WEBP, and SVG are allowed.';
            }
        }

        $leagueData = [
            'id' => $league_id,
            'name' => $name,
            'country' => $country,
            'season' => $season,
            'manager_id' => $manager_id ?: null, // Set to null if empty
            'logo' => $new_logo_path,
            'reg_fee_total' => (float)$_POST['reg_fee_total'],
            'reg_deposit_pct' => (float)$_POST['reg_deposit_pct'],
            'reg_inst2_pct' => (float)$_POST['reg_inst2_pct'],
            'reg_inst2_games' => (int)$_POST['reg_inst2_games'],
            'reg_inst3_pct' => (float)$_POST['reg_inst3_pct'],
            'reg_inst3_games' => (int)$_POST['reg_inst3_games'],
        ];
        if ($leagueModel->update($leagueData)) {
            $_SESSION['flash_message'] = "League '{$name}' updated successfully!";
            header('Location: manage_leagues.php');
            exit();
        } else {
            $error = 'Failed to update league.';
        }
    }
}

$all_seasons = $seasonModel->getAll();
$potential_managers = $userModel->getPotentialManagers();
include_once 'includes/sidebar.php';
?>

<h1>Edit League: <?php echo htmlspecialchars($league->name); ?></h1>

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

<div class="form-container">
    <form action="edit_league.php?id=<?php echo $league_id; ?>" method="POST" enctype="multipart/form-data">
        <div class="form-group"><label for="name">League Name</label><input type="text" name="name" id="name" value="<?php echo htmlspecialchars($league->name); ?>" required></div>
        <div class="form-group"><label for="country">Country</label><input type="text" name="country" id="country" value="<?php echo htmlspecialchars($league->country); ?>" required></div>
        <div class="form-group">
            <label for="logo">League 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($league->logo) ? htmlspecialchars($league->logo) : '#'; ?>" alt="Logo Preview" style="max-width: 100px; <?php echo empty($league->logo) ? 'display:none;' : ''; ?>">
                <?php if(empty($league->logo)): ?><p>No logo uploaded.</p><?php endif; ?>
            </div>
        </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 ($s->name == $league->season) ? 'selected' : ''; ?>><?php echo htmlspecialchars($s->name); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="form-group">
            <label for="manager_id">League Manager</label>
            <select name="manager_id" id="manager_id">
                <option value="">-- Unassigned --</option>
                <?php foreach ($potential_managers as $manager): ?>
                    <option value="<?php echo $manager->id; ?>" <?php echo ($manager->id == $league->manager_id) ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($manager->first_name . ' ' . $manager->last_name . ' (' . $manager->username . ')'); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <h3>Registration Fees & Payment Plan</h3>
        <div class="form-group">
            <label for="reg_fee_total">Total Registration Fee</label>
            <input type="number" name="reg_fee_total" id="reg_fee_total" value="<?php echo $league->reg_fee_total ?? 0; ?>" min="0" step="0.01">
            <small>Total fee required for a club to participate in this league.</small>
        </div>
        <div class="form-row" style="display: flex; gap: 20px; align-items: flex-end;">
            <div class="form-group" style="flex: 1;">
                <label>Initial Deposit (%)</label>
                <input type="number" name="reg_deposit_pct" value="<?php echo $league->reg_deposit_pct ?? 50; ?>" min="0" max="100" step="1">
                <small>Due immediately.</small>
            </div>
        </div>
        <div class="form-row" style="display: flex; gap: 20px; align-items: flex-end;">
            <div class="form-group" style="flex: 1;">
                <label>2nd Installment (%)</label>
                <input type="number" name="reg_inst2_pct" value="<?php echo $league->reg_inst2_pct ?? 30; ?>" min="0" max="100" step="1">
            </div>
            <div class="form-group" style="flex: 1;">
                <label>Due After (Games Played)</label>
                <input type="number" name="reg_inst2_games" value="<?php echo $league->reg_inst2_games ?? 5; ?>" min="0">
            </div>
        </div>
        <div class="form-row" style="display: flex; gap: 20px; align-items: flex-end;">
            <div class="form-group" style="flex: 1;">
                <label>3rd Installment (%)</label>
                <input type="number" name="reg_inst3_pct" value="<?php echo $league->reg_inst3_pct ?? 20; ?>" min="0" max="100" step="1">
            </div>
            <div class="form-group" style="flex: 1;">
                <label>Due After (Games Played)</label>
                <input type="number" name="reg_inst3_games" value="<?php echo $league->reg_inst3_games ?? 10; ?>" min="0">
            </div>
        </div>

        <button type="submit" class="btn">Update League</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'; ?>