<?php
require_once '../includes/config.php';
require_once 'header.php';

$error = '';
$success = '';

// Handle Add/Edit/Delete
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['action']) && $_POST['action'] == 'add') {
        $type = trim($_POST['type'] ?? '');
        $amount = floatval($_POST['amount'] ?? 0);
        $duration_months = intval($_POST['duration_months'] ?? 12);
        $description = trim($_POST['description'] ?? '');
        $features = trim($_POST['features'] ?? '');
        
        if (empty($type) || $amount <= 0) {
            $error = 'Please fill all required fields';
        } else {
            $stmt = $pdo->prepare("INSERT INTO membership_types (type, amount, duration_months, description, features) VALUES (?, ?, ?, ?, ?)");
            if ($stmt->execute([$type, $amount, $duration_months, $description, $features])) {
                $success = 'Membership type added successfully';
            } else {
                $error = 'Failed to add membership type';
            }
        }
    }
    
    if (isset($_POST['action']) && $_POST['action'] == 'edit') {
        $id = $_POST['id'] ?? 0;
        $type = trim($_POST['type'] ?? '');
        $amount = floatval($_POST['amount'] ?? 0);
        $duration_months = intval($_POST['duration_months'] ?? 12);
        $description = trim($_POST['description'] ?? '');
        $features = trim($_POST['features'] ?? '');
        
        if ($id && !empty($type) && $amount > 0) {
            $stmt = $pdo->prepare("UPDATE membership_types SET type = ?, amount = ?, duration_months = ?, description = ?, features = ? WHERE id = ?");
            if ($stmt->execute([$type, $amount, $duration_months, $description, $features, $id])) {
                $success = 'Membership type updated successfully';
            } else {
                $error = 'Failed to update membership type';
            }
        }
    }
    
    if (isset($_POST['action']) && $_POST['action'] == 'delete') {
        $id = $_POST['id'] ?? 0;
        
        // Check if any members use this type
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM members WHERE membership_type_id = ?");
        $stmt->execute([$id]);
        $count = $stmt->fetchColumn();
        
        if ($count > 0) {
            $error = 'Cannot delete: This membership type has ' . $count . ' members assigned';
        } else {
            $stmt = $pdo->prepare("DELETE FROM membership_types WHERE id = ?");
            if ($stmt->execute([$id])) {
                $success = 'Membership type deleted successfully';
            } else {
                $error = 'Failed to delete membership type';
            }
        }
    }
}

// Get all membership types
$stmt = $pdo->query("SELECT * FROM membership_types ORDER BY amount");
$membershipTypes = $stmt->fetchAll();

// Get statistics
$stmt = $pdo->query("SELECT COUNT(*) as total_members FROM members");
$totalMembers = $stmt->fetch()['total_members'];
?>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2"><i class="fas fa-tags me-2"></i>Manage Membership Types</h1>
    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addTypeModal">
        <i class="fas fa-plus me-2"></i>Add New Type
    </button>
</div>

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

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

<div class="row">
    <?php foreach ($membershipTypes as $type): ?>
        <?php
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM members WHERE membership_type_id = ?");
        $stmt->execute([$type['id']]);
        $memberCount = $stmt->fetchColumn();
        ?>
        <div class="col-md-4 mb-4">
            <div class="card h-100">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0"><?php echo htmlspecialchars($type['type']); ?></h5>
                </div>
                <div class="card-body">
                    <h2 class="text-center text-primary"><?php echo formatCurrency($type['amount']); ?></h2>
                    <p class="text-center text-muted">
                        <?php if ($type['duration_months'] > 0): ?>
                            <?php echo $type['duration_months']; ?> months validity
                        <?php else: ?>
                            Lifetime membership
                        <?php endif; ?>
                    </p>
                    <p><strong>Members:</strong> <?php echo $memberCount; ?></p>
                    <p><strong>Description:</strong><br><?php echo nl2br(htmlspecialchars($type['description'] ?: 'No description')); ?></p>
                    <?php if ($type['features']): ?>
                        <p><strong>Features:</strong><br><?php echo nl2br(htmlspecialchars($type['features'])); ?></p>
                    <?php endif; ?>
                </div>
                <div class="card-footer">
                    <button class="btn btn-warning btn-sm" onclick="editType(<?php echo $type['id']; ?>, '<?php echo htmlspecialchars($type['type']); ?>', <?php echo $type['amount']; ?>, <?php echo $type['duration_months']; ?>, '<?php echo htmlspecialchars($type['description']); ?>', '<?php echo htmlspecialchars($type['features']); ?>')">
                        <i class="fas fa-edit"></i> Edit
                    </button>
                    <button class="btn btn-danger btn-sm" onclick="deleteType(<?php echo $type['id']; ?>, '<?php echo htmlspecialchars($type['type']); ?>')">
                        <i class="fas fa-trash"></i> Delete
                    </button>
                </div>
            </div>
        </div>
    <?php endforeach; ?>
</div>

<!-- Add Type Modal -->
<div class="modal fade" id="addTypeModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title"><i class="fas fa-plus me-2"></i>Add Membership Type</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="add">
                    <div class="mb-3">
                        <label class="form-label">Type Name *</label>
                        <input type="text" class="form-control" name="type" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Amount (₹) *</label>
                        <input type="number" class="form-control" name="amount" step="0.01" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Duration (Months)</label>
                        <input type="number" class="form-control" name="duration_months" value="12">
                        <small class="text-muted">Enter 0 for lifetime membership</small>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Description</label>
                        <textarea class="form-control" name="description" rows="2"></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Features (one per line)</label>
                        <textarea class="form-control" name="features" rows="3" placeholder="Feature 1&#10;Feature 2&#10;Feature 3"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Add Type</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Type Modal -->
<div class="modal fade" id="editTypeModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-warning text-dark">
                <h5 class="modal-title"><i class="fas fa-edit me-2"></i>Edit Membership Type</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="edit">
                    <input type="hidden" name="id" id="edit_id">
                    <div class="mb-3">
                        <label class="form-label">Type Name *</label>
                        <input type="text" class="form-control" name="type" id="edit_type" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Amount (₹) *</label>
                        <input type="number" class="form-control" name="amount" id="edit_amount" step="0.01" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Duration (Months)</label>
                        <input type="number" class="form-control" name="duration_months" id="edit_duration">
                        <small class="text-muted">Enter 0 for lifetime membership</small>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Description</label>
                        <textarea class="form-control" name="description" id="edit_description" rows="2"></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Features (one per line)</label>
                        <textarea class="form-control" name="features" id="edit_features" rows="3"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-warning">Update Type</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteTypeModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title"><i class="fas fa-exclamation-triangle me-2"></i>Confirm Delete</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="id" id="delete_id">
                    <p>Are you sure you want to delete <strong id="delete_name"></strong>?</p>
                    <p class="text-danger">This action cannot be undone.</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">Delete</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function editType(id, type, amount, duration, description, features) {
    document.getElementById('edit_id').value = id;
    document.getElementById('edit_type').value = type;
    document.getElementById('edit_amount').value = amount;
    document.getElementById('edit_duration').value = duration;
    document.getElementById('edit_description').value = description;
    document.getElementById('edit_features').value = features;
    new bootstrap.Modal(document.getElementById('editTypeModal')).show();
}

function deleteType(id, name) {
    document.getElementById('delete_id').value = id;
    document.getElementById('delete_name').textContent = name;
    new bootstrap.Modal(document.getElementById('deleteTypeModal')).show();
}
</script>

<?php require_once 'footer.php'; ?>