<?php
require_once '../core/bootstrap.php';

// --- Authentication and Role Check ---
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'club_manager') {
    header('Location: login.php');
    exit();
}

$pageTitle = 'Membership Packages';
include 'includes/header.php';

$manager_id = $_SESSION['user_id'];

// --- Instantiate Models ---
$clubManagerModel = new ClubManager();
$clubModel = new Club();

// --- Fetch Data ---
$club = $clubManagerModel->getClubByManagerId($manager_id);
if (!$club) {
    echo "<div class='page-content'><p class='no-data-msg'>You are not currently assigned as a manager to any club.</p></div>";
    include 'includes/footer.php';
    exit();
}

$packages = $clubModel->getMembershipPackagesByClub($club->id);
$settings = (new Setting())->getAll();
$currency_symbol = ($settings['system_currency'] ?? 'USD') === 'ZMW' ? 'K' : '$';

$primary_color = $settings['primary_color'] ?? '#3498db';
$secondary_color = $settings['secondary_color'] ?? '#2c3e50';
?>

<div class="team-dashboard-hero">
    <div class="hero-content-wrapper">
        <div class="hero-header-row">
            <div class="team-identity">
                <img src="<?php echo htmlspecialchars($club->logo); ?>" alt="<?php echo htmlspecialchars($club->name); ?>" class="hero-team-logo">
                <div class="team-details">
                    <h1>Membership Packages</h1>
                    <span class="manager-badge"><?php echo htmlspecialchars($club->name); ?></span>
                </div>
            </div>
            <div class="hero-actions">
                <a href="my_club.php?tab=management" class="btn btn-hero-secondary"><i class="fa-solid fa-arrow-left"></i> Back</a>
                <button class="btn btn-hero-primary" onclick="openPackageModal()"><i class="fa-solid fa-plus"></i> Add Package</button>
            </div>
        </div>
    </div>
</div>

<div class="page-content">
    <div class="dashboard-section">
        <div class="table-wrapper">
            <?php if (!empty($packages)): ?>
                <table class="styled-table">
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Price</th>
                            <th>Duration</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($packages as $pkg): ?>
                            <tr>
                                <td><strong><?php echo htmlspecialchars($pkg->name); ?></strong><br><small><?php echo htmlspecialchars(substr($pkg->description, 0, 50)) . '...'; ?></small></td>
                                <td><?php echo $currency_symbol; ?><?php echo number_format($pkg->price, 2); ?></td>
                                <td><?php echo ucfirst($pkg->duration_type); ?></td>
                                <td>
                                    <span class="status-badge status-<?php echo $pkg->is_active ? 'active' : 'inactive'; ?>">
                                        <?php echo $pkg->is_active ? 'Active' : 'Inactive'; ?>
                                    </span>
                                </td>
                                <td>
                                    <button class="btn-sm btn-edit" onclick='openPackageModal(<?php echo json_encode($pkg); ?>)'>Edit</button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <p class="no-data-msg">No membership packages have been created yet.</p>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Add/Edit Package Modal -->
<div id="packageModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 id="modalTitle">Add Package</h3>
            <button class="modal-close-btn" onclick="closePackageModal()">&times;</button>
        </div>
        <form action="club_membership_packages_process.php" method="POST">
            <input type="hidden" name="action" id="formAction" value="create">
            <input type="hidden" name="package_id" id="packageId">
            <input type="hidden" name="club_id" value="<?php echo $club->id; ?>">

            <div class="form-group">
                <label for="name">Package Name</label>
                <input type="text" name="name" id="name" required placeholder="e.g., Gold Membership">
            </div>
            <div class="form-group">
                <label for="description">Description / Benefits</label>
                <textarea name="description" id="description" rows="4" placeholder="e.g., Free entry to home games, 10% shop discount..."></textarea>
            </div>
            <div class="form-group">
                <label for="price">Price (<?php echo $currency_symbol; ?>)</label>
                <input type="number" name="price" id="price" step="0.01" required placeholder="e.g., 25.00">
            </div>
            <div class="form-group">
                <label for="duration_type">Duration</label>
                <select name="duration_type" id="duration_type" required>
                    <option value="monthly">Monthly</option>
                    <option value="termly">Termly (3 Months)</option>
                    <option value="yearly">Yearly</option>
                </select>
            </div>
            <div class="form-group" id="statusGroup" style="display: none;">
                <label for="is_active">Status</label>
                <select name="is_active" id="is_active">
                    <option value="1">Active</option>
                    <option value="0">Inactive</option>
                </select>
            </div>

            <button type="submit" class="btn btn-block" id="modalSubmitBtn">Create Package</button>
        </form>
    </div>
</div>

<script>
    const modal = document.getElementById('packageModal');
    const modalTitle = document.getElementById('modalTitle');
    const formAction = document.getElementById('formAction');
    const packageIdInput = document.getElementById('packageId');
    const nameInput = document.getElementById('name');
    const descInput = document.getElementById('description');
    const priceInput = document.getElementById('price');
    const durationSelect = document.getElementById('duration_type');
    const statusGroup = document.getElementById('statusGroup');
    const statusSelect = document.getElementById('is_active');
    const modalSubmitBtn = document.getElementById('modalSubmitBtn');

    function openPackageModal(pkgData = null) {
        if (pkgData) {
            modalTitle.textContent = 'Edit Package';
            formAction.value = 'update';
            packageIdInput.value = pkgData.id;
            nameInput.value = pkgData.name;
            descInput.value = pkgData.description;
            priceInput.value = pkgData.price;
            durationSelect.value = pkgData.duration_type;
            statusSelect.value = pkgData.is_active;
            statusGroup.style.display = 'block';
            modalSubmitBtn.textContent = 'Update Package';
        } else {
            modalTitle.textContent = 'Add Package';
            formAction.value = 'create';
            packageIdInput.value = '';
            nameInput.value = '';
            descInput.value = '';
            priceInput.value = '';
            durationSelect.value = 'monthly';
            statusGroup.style.display = 'none';
            modalSubmitBtn.textContent = 'Create Package';
        }
        modal.classList.add('show');
    }

    function closePackageModal() {
        modal.classList.remove('show');
        // Wait for transition to finish before hiding display (optional, but cleaner)
        // For simplicity with CSS display:flex/none toggle in class, we rely on the class logic or override
    }

    window.onclick = function(event) {
        if (event.target == modal) {
            closePackageModal();
        }
    }
</script>

<style>
:root {
    --hero-gradient: linear-gradient(135deg, <?php echo $primary_color; ?> 0%, <?php echo $secondary_color; ?> 100%);
}

/* Transparent Header Override */
header {
    background: transparent !important;
    box-shadow: none !important;
    position: absolute !important;
    width: 100%;
    top: 0;
    z-index: 1000;
}

.team-dashboard-hero {
    background: var(--hero-gradient);
    color: white;
    padding: 6rem 20px 3rem 20px;
    border-radius: 0 0 30px 30px;
    margin-bottom: 2rem;
    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
    margin-top: 0;
}

.hero-content-wrapper {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0;
}

.hero-header-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.team-identity {
    display: flex;
    align-items: center;
    gap: 1.5rem;
}

.hero-team-logo {
    width: 80px;
    height: 80px;
    object-fit: contain;
    background: white;
    border-radius: 50%;
    padding: 5px;
    box-shadow: 0 4px 10px rgba(0,0,0,0.1);
}

.team-details h1 {
    margin: 0 0 5px 0;
    font-size: 2rem;
    font-weight: 700;
}

.manager-badge {
    background: rgba(255,255,255,0.2);
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 0.9rem;
    backdrop-filter: blur(5px);
}

.hero-actions {
    display: flex;
    gap: 10px;
}

.btn-hero-secondary {
    background: rgba(255,255,255,0.2);
    color: white;
    border: 1px solid rgba(255,255,255,0.3);
}
.btn-hero-secondary:hover { background: rgba(255,255,255,0.3); }

.btn-hero-primary {
    background: white;
    color: var(--primary-color);
    border: none;
}
.btn-hero-primary:hover { background: #f0f0f0; }

@media (max-width: 768px) {
    .hero-header-row {
        flex-direction: column;
        text-align: center;
        gap: 1.5rem;
    }
    .team-identity {
        flex-direction: column;
    }
}
</style>

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