<?php
session_start();
if (!isset($_SESSION['gym_id'])) {
    header("Location: login.php");
    exit();
}

require_once '../config/database.php';
$db = (new Database())->getConnection();
$gym_id = $_SESSION['gym_id'];

// Current gym کا data fetch کریں sidebar کے لیے
$gym_stmt = $db->prepare("SELECT name, owner_name FROM gyms WHERE id = ?");
$gym_stmt->execute([$gym_id]);
$current_gym = $gym_stmt->fetch(PDO::FETCH_ASSOC);

// Get all active subscription plans from super admin
$query = "SELECT * FROM subscription_plans WHERE status = 'active' ORDER BY price_monthly ASC";
$stmt = $db->prepare($query);
$stmt->execute();
$plans = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<?php include 'includes/header.php'; ?>
<?php include 'includes/sidebar.php'; ?>
<?php include 'includes/navbar.php'; ?>

<div class="main-panel">
    <div class="content-wrapper">
        <div class="page-header flex-wrap">
            <div class="header-left">
                <h2 class="page-title">Subscription Plans</h2>
                <p class="text-muted">Choose the perfect plan for your gym</p>
            </div>
            
            
        </div>

        <!-- Plans Grid -->
        <div class="row">
            <?php foreach ($plans as $plan): 
                $features = json_decode($plan['features'], true);
                $is_popular = $plan['is_popular'];
            ?>
            <div class="col-xl-4 col-lg-6 col-md-12 grid-margin stretch-card">
                <div class="card pricing-card <?php echo $is_popular ? 'popular' : ''; ?>">
                    <?php if ($is_popular): ?>
                        <div class="popular-badge">Most Popular</div>
                    <?php endif; ?>
                    
                    <div class="card-header bg-primary text-white text-center py-4">
                        <h4 class="mb-0"><?php echo $plan['name']; ?></h4>
                        <p class="mb-0 opacity-75"><?php echo $plan['description']; ?></p>
                    </div>
                    
                    <div class="card-body">
                        <div class="price-section text-center mb-4">
                            <h2 class="price text-primary">$<?php echo $plan['price_monthly']; ?><small>/month</small></h2>
                            <p class="text-muted">or $<?php echo $plan['price_yearly']; ?>/year <span class="text-success">(Save 20%)</span></p>
                        </div>

                        <div class="members-count text-center mb-4">
                            <span class="badge bg-primary text-white p-2">
                                <i class="mdi mdi-account-multiple me-1"></i>
                                <?php echo $plan['max_members'] == 0 ? 'Unlimited' : $plan['max_members']; ?> Gym Members
                            </span>
                        </div>

                        <div class="features-list mb-4">
                            <?php foreach ($features as $feature): ?>
                                <div class="d-flex align-items-center mb-3">
                                    <i class="mdi mdi-check-circle-outline text-success me-3 fs-5"></i>
                                    <span class="feature-text"><?php echo $feature; ?></span>
                                </div>
                            <?php endforeach; ?>
                        </div>

                        <div class="action-buttons mt-4">
                                <button class="btn btn-primary w-100 subscribe-btn" 
                                        data-plan-id="<?php echo $plan['id']; ?>"
                                        data-plan-name="<?php echo $plan['name']; ?>"
                                        data-price-monthly="<?php echo $plan['price_monthly']; ?>"
                                        data-price-yearly="<?php echo $plan['price_yearly']; ?>">
                                    <i class="mdi mdi-credit-card"></i> Subscribe Now
                                </button>
                        </div>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>

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

<!-- Subscription Modal -->
<div class="modal fade" id="subscribeModal" tabindex="-1" aria-labelledby="subscribeModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="subscribeModalLabel">Subscribe to Plan</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="subscribeForm">
                    <input type="hidden" id="plan_id" name="plan_id">
                    
                    <div class="text-center mb-4">
                        <h4 id="plan_name" class="text-primary"></h4>
                        <div class="price-details">
                            <h3 id="monthly_price" class="text-success"></h3>
                            <h5 id="yearly_price" class="text-muted"></h5>
                        </div>
                    </div>

                    <div class="form-group mb-3">
                        <label class="form-label">Billing Cycle *</label>
                        <div class="btn-group w-100" role="group">
                            <input type="radio" class="btn-check" name="billing_cycle" id="monthly" value="monthly" checked>
                            <label class="btn btn-outline-primary" for="monthly">Monthly</label>
                            
                            <input type="radio" class="btn-check" name="billing_cycle" id="yearly" value="yearly">
                            <label class="btn btn-outline-primary" for="yearly">Yearly (Save 20%)</label>
                        </div>
                    </div>

                    <div class="form-group mb-3">
                        <label class="form-label">Payment Method *</label>
                        <select class="form-control" name="payment_method" required>
                            <option value="">Select Payment Method</option>
                            <option value="credit_card">Credit Card</option>
                            <option value="debit_card">Debit Card</option>
                            <option value="bank_transfer">Bank Transfer</option>
                            <option value="easypaisa">Easypaisa</option>
                            <option value="jazzcash">JazzCash</option>
                            <option value="cash">Cash</option>
                        </select>
                    </div>

                    <div class="form-group mb-3">
                        <label class="form-label">Transaction ID</label>
                        <input type="text" class="form-control" name="transaction_id" placeholder="Enter transaction reference">
                    </div>

                    <div class="alert alert-info">
                        <small>
                            <i class="mdi mdi-information-outline"></i>
                            Your subscription will be activated after payment verification.
                        </small>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" form="subscribeForm" class="btn btn-primary">
                    <i class="mdi mdi-credit-card"></i> Confirm Subscription
                </button>
            </div>
        </div>
    </div>
</div>

<!-- SweetAlert CDN -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
// Subscribe Button Click
document.querySelectorAll('.subscribe-btn').forEach(button => {
    button.addEventListener('click', function() {
        const planId = this.getAttribute('data-plan-id');
        const planName = this.getAttribute('data-plan-name');
        const priceMonthly = this.getAttribute('data-price-monthly');
        const priceYearly = this.getAttribute('data-price-yearly');
        
        // Populate modal
        document.getElementById('plan_id').value = planId;
        document.getElementById('plan_name').textContent = planName;
        document.getElementById('monthly_price').textContent = '$' + priceMonthly + '/month';
        document.getElementById('yearly_price').textContent = '$' + priceYearly + '/year';
        
        // Show modal
        const subscribeModal = new bootstrap.Modal(document.getElementById('subscribeModal'));
        subscribeModal.show();
    });
});

// Billing Cycle Change
document.querySelectorAll('input[name="billing_cycle"]').forEach(radio => {
    radio.addEventListener('change', function() {
        const monthlyPrice = document.getElementById('monthly_price');
        const yearlyPrice = document.getElementById('yearly_price');
        
        if (this.value === 'monthly') {
            monthlyPrice.classList.remove('text-muted');
            monthlyPrice.classList.add('text-success');
            yearlyPrice.classList.remove('text-success');
            yearlyPrice.classList.add('text-muted');
        } else {
            yearlyPrice.classList.remove('text-muted');
            yearlyPrice.classList.add('text-success');
            monthlyPrice.classList.remove('text-success');
            monthlyPrice.classList.add('text-muted');
        }
    });
});

// Subscription Form Submission
document.getElementById('subscribeForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    formData.append('subscribe', 'true');
    
    // Show loading state
    const submitBtn = this.querySelector('button[type="submit"]');
    const originalText = submitBtn.innerHTML;
    submitBtn.innerHTML = '<i class="mdi mdi-loading mdi-spin me-1"></i> Processing...';
    submitBtn.disabled = true;
    
    fetch('subscriptions.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            Swal.fire({
                icon: 'success',
                title: 'Subscription Successful!',
                html: data.message,
                confirmButtonColor: '#3085d6',
            }).then(() => {
                location.reload();
            });
        } else {
            Swal.fire({
                icon: 'error',
                title: 'Subscription Failed!',
                text: data.message,
                confirmButtonColor: '#d33',
            });
        }
    })
    .catch(error => {
        console.error('Error:', error);
        Swal.fire({
            icon: 'error',
            title: 'Error!',
            text: 'An error occurred while processing subscription!',
            confirmButtonColor: '#d33',
        });
    })
    .finally(() => {
        submitBtn.innerHTML = originalText;
        submitBtn.disabled = false;
    });
});
</script>

<style>
.pricing-card {
    position: relative;
    transition: all 0.3s ease;
    border: none;
    border-radius: 15px;
    box-shadow: 0 5px 20px rgba(0,0,0,0.1);
    margin-bottom: 30px;
    overflow: hidden;
}

.pricing-card:hover {
    transform: translateY(-10px);
    box-shadow: 0 15px 35px rgba(0,0,0,0.15);
}

.pricing-card.popular {
    border: 3px solid #3085d6;
    transform: scale(1.02);
}

.pricing-card.popular:hover {
    transform: scale(1.02) translateY(-10px);
}

.popular-badge {
    position: absolute;
    top: 20px;
    right: -35px;
    background: #3085d6;
    color: white;
    padding: 8px 40px;
    font-size: 12px;
    font-weight: bold;
    transform: rotate(45deg);
    box-shadow: 0 2px 10px rgba(76, 175, 80, 0.3);
    z-index: 1;
}

.card-header {
    border-radius: 15px 15px 0 0 !important;
    border: none;
    padding: 30px 20px;
}

.price {
    font-size: 2.5rem;
    font-weight: 800;
    margin-bottom: 0.5rem;
}

.price small {
    font-size: 1rem;
    font-weight: 400;
}

.features-list {
    max-height: 300px;
    overflow-y: auto;
    padding: 10px 0;
}

.feature-text {
    font-size: 0.95rem;
    color: #555;
}

.btn-primary {
    background-color: #1956e3 !important;
    border-color: #1956e3 !important;
}

/* Responsive Design */
@media (max-width: 768px) {
    .pricing-card {
        margin-bottom: 20px;
    }
    
    .price {
        font-size: 2rem;
    }
}
</style>