<?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);

// Add new membership plan
if ($_POST && isset($_POST['add_plan'])) {
    $plan_name = trim($_POST['plan_name']);
    $plan_type = $_POST['plan_type'];
    $duration_days = $_POST['duration_days'];
    $price = $_POST['price'];
    $description = trim($_POST['description']);
    $features = trim($_POST['features']);
    $status = $_POST['status'];

    // Check if plan name already exists - ONLY IN CURRENT GYM (plan type ki jagah plan name check karenge)
    $check_query = "SELECT id FROM membership_plans WHERE plan_name = ? AND gym_id = ?";
    $stmt = $db->prepare($check_query);
    $stmt->execute([$plan_name, $gym_id]);
    
    if ($stmt->rowCount() > 0) {
        $_SESSION['error'] = 'Plan name already exists! Please choose a different plan name.';
    } else {
        $query = "INSERT INTO membership_plans (plan_name, plan_type, duration_days, price, description, features, status, gym_id) 
                  VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt = $db->prepare($query);
        
        if ($stmt->execute([$plan_name, $plan_type, $duration_days, $price, $description, $features, $status, $gym_id])) {
            $_SESSION['success'] = 'Membership plan added successfully!';
        } else {
            $_SESSION['error'] = 'Failed to add membership plan! Please try again.';
        }
    }
    header("Location: membership-plans.php");
    exit();
}

// Update membership plan
if ($_POST && isset($_POST['update_plan'])) {
    $plan_id = $_POST['plan_id'];
    $plan_name = trim($_POST['plan_name']);
    $plan_type = $_POST['plan_type'];
    $duration_days = $_POST['duration_days'];
    $price = $_POST['price'];
    $description = trim($_POST['description']);
    $features = trim($_POST['features']);
    $status = $_POST['status'];

    // Check if plan name already exists (excluding current plan) - ONLY IN CURRENT GYM
    $check_query = "SELECT id FROM membership_plans WHERE plan_name = ? AND id != ? AND gym_id = ?";
    $stmt = $db->prepare($check_query);
    $stmt->execute([$plan_name, $plan_id, $gym_id]);
    
    if ($stmt->rowCount() > 0) {
        $_SESSION['error'] = 'Plan name already exists! Please choose a different plan name.';
    } else {
        $query = "UPDATE membership_plans SET plan_name=?, plan_type=?, duration_days=?, price=?, description=?, features=?, status=? WHERE id=? AND gym_id=?";
        $stmt = $db->prepare($query);
        
        if ($stmt->execute([$plan_name, $plan_type, $duration_days, $price, $description, $features, $status, $plan_id, $gym_id])) {
            $_SESSION['success'] = 'Membership plan updated successfully!';
        } else {
            $_SESSION['error'] = 'Failed to update membership plan!';
        }
    }
    header("Location: membership-plans.php");
    exit();
}

// Delete plan - ONLY FROM CURRENT GYM
if (isset($_GET['delete_id'])) {
    $delete_id = $_GET['delete_id'];
    
    // اصل میں یہ query ہے جو error دے رہی ہے
    // $check_query = "SELECT id FROM members WHERE membership_type = (SELECT plan_type FROM membership_plans WHERE id = ? AND gym_id = ?) LIMIT 1";
    
    // درست query (BINARY استعمال کریں collation کو force کرنے کے لیے)
    $check_query = "SELECT id FROM members WHERE BINARY membership_type = (SELECT plan_type FROM membership_plans WHERE id = ? AND gym_id = ?) LIMIT 1";
    
    $stmt = $db->prepare($check_query);
    $stmt->execute([$delete_id, $gym_id]);
    
    if ($stmt->rowCount() > 0) {
        $_SESSION['error'] = "Cannot delete plan! Some members are still using this plan.";
    } else {
        $query = "DELETE FROM membership_plans WHERE id = ? AND gym_id = ?";
        $stmt = $db->prepare($query);
        if ($stmt->execute([$delete_id, $gym_id])) {
            $_SESSION['success'] = "Membership plan deleted successfully!";
        } else {
            $_SESSION['error'] = "Failed to delete membership plan!";
        }
    }
    header("Location: membership-plans.php");
    exit();
}

// Toggle plan status - ONLY FOR CURRENT GYM
if (isset($_GET['toggle_status'])) {
    $plan_id = $_GET['toggle_status'];
    $query = "UPDATE membership_plans SET status = IF(status='active', 'inactive', 'active') WHERE id = ? AND gym_id = ?";
    $stmt = $db->prepare($query);
    if ($stmt->execute([$plan_id, $gym_id])) {
        $_SESSION['success'] = "Plan status updated successfully!";
    } else {
        $_SESSION['error'] = "Failed to update plan status!";
    }
    header("Location: membership-plans.php");
    exit();
}

// Get all membership plans - ONLY FROM CURRENT GYM
$query = "SELECT * FROM membership_plans WHERE gym_id = ? ORDER BY price ASC";
$stmt = $db->prepare($query);
$stmt->execute([$gym_id]);
$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">
            <h3 class="page-title">Membership Plans Management</h3>
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                    <li class="breadcrumb-item active" aria-current="page">Membership Plans</li>
                </ol>
            </nav>
        </div>

        <div class="row">
            <div class="col-lg-12 grid-margin stretch-card">
                <div class="card">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center mb-4">
                            <h4 class="card-title">Membership Plans</h4>
                            <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addPlanModal">
                                <i class="mdi mdi-plus-circle"></i> Add New Plan
                            </button>
                        </div>
                        
                        <div class="row">
                            <?php foreach ($plans as $plan): ?>
                            <div class="col-md-6 col-lg-4 grid-margin stretch-card">
                                <div class="card pricing-card">
                                    <div class="card-body">
                                        <div class="d-flex justify-content-between align-items-center mb-3">
                                            <h5 class="pricing-card-title"><?php echo $plan['plan_name']; ?></h5>
                                            <span class="badge badge-<?php echo $plan['status'] == 'active' ? 'success' : 'danger'; ?>">
                                                <?php echo ucfirst($plan['status']); ?>
                                            </span>
                                        </div>
                                        
                                        <div class="text-center mb-4">
                                            <h1 class="fw-bold text-primary">Rs. <?php echo number_format($plan['price']); ?></h1>
                                            <p class="text-muted">for <?php echo $plan['duration_days']; ?> days</p>
                                        </div>
                                        
                                        <div class="pricing-features mb-4">
                                            <p class="text-muted"><?php echo $plan['description']; ?></p>
                                            <?php if ($plan['features']): ?>
                                            <h6 class="fw-semibold">Features:</h6>
                                            <p class="text-muted small"><?php echo nl2br($plan['features']); ?></p>
                                            <?php endif; ?>
                                        </div>
                                        
                                        <div class="d-flex justify-content-between">
                                            <small class="text-muted">
                                            <span style="font-weight: bold; color: #000;">Type:</span>
                                            <?php echo ucfirst($plan['plan_type']); ?>
                                            </small>
                                            <div>
                                                <button class="btn btn-sm btn-primary edit-plan-btn" 
                                                        data-id="<?php echo $plan['id']; ?>"
                                                        data-name="<?php echo htmlspecialchars($plan['plan_name']); ?>"
                                                        data-type="<?php echo $plan['plan_type']; ?>"
                                                        data-duration="<?php echo $plan['duration_days']; ?>"
                                                        data-price="<?php echo $plan['price']; ?>"
                                                        data-description="<?php echo htmlspecialchars($plan['description']); ?>"
                                                        data-features="<?php echo htmlspecialchars($plan['features']); ?>"
                                                        data-status="<?php echo $plan['status']; ?>">
                                                    <i class="mdi mdi-pencil"></i>
                                                </button>
                                                <a href="membership-plans.php?toggle_status=<?php echo $plan['id']; ?>" 
                                                   class="btn btn-sm btn-<?php echo $plan['status'] == 'active' ? 'warning' : 'success'; ?>">
                                                    <i class="mdi mdi-<?php echo $plan['status'] == 'active' ? 'pause' : 'play'; ?>"></i>
                                                </a>
                                                <a href="membership-plans.php?delete_id=<?php echo $plan['id']; ?>" 
                                                   class="btn btn-sm btn-danger delete-plan-btn">
                                                    <i class="mdi mdi-delete"></i>
                                                </a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                            
                            <?php if (empty($plans)): ?>
                            <div class="col-12 text-center py-5">
                                <i class="mdi mdi-account-card-details-outline display-4 text-muted d-block mb-3"></i>
                                <h4 class="text-muted">No membership plans found</h4>
                                <p class="text-muted">Create your first membership plan to get started</p>
                                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addPlanModal">
                                    <i class="mdi mdi-plus-circle"></i> Add First Plan
                                </button>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Add Plan Modal -->
    <div class="modal fade" id="addPlanModal" tabindex="-1" aria-labelledby="addPlanModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addPlanModalLabel">Add New Membership Plan</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="addPlanForm" method="POST">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="plan_name" class="form-label">Plan Name *</label>
                                    <input type="text" class="form-control" id="plan_name" name="plan_name" required 
                                           placeholder="e.g., Basic Plan, Premium Plan, Gold Plan">
                                    <small class="text-muted">Each plan must have a unique name</small>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="plan_type" class="form-label">Plan Type *</label>
                                    <select class="form-control" id="plan_type" name="plan_type" required>
                                        <option value="">Select Plan Type</option>
                                        <option value="With cardio">With Cardio</option>
                                        <option value="Non-cardio">Non-Cardio</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="duration_days" class="form-label">Duration (Days) *</label>
                                    <input type="number" class="form-control" id="duration_days" name="duration_days" required 
                                           placeholder="e.g., 30, 90, 365" min="1">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="price" class="form-label">Price (PKR) *</label>
                                    <input type="number" class="form-control" id="price" name="price" required 
                                           placeholder="e.g., 3000" step="0.01" min="0">
                                </div>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="description" class="form-label">Description *</label>
                            <textarea class="form-control" id="description" name="description" required 
                                      placeholder="Brief description of the plan" rows="2"></textarea>
                        </div>

                        <div class="form-group">
                            <label for="features" class="form-label">Features</label>
                            <textarea class="form-control" id="features" name="features" 
                                      placeholder="List the features (one per line)" rows="4"></textarea>
                            <small class="text-muted">Enter each feature on a new line</small>
                        </div>

                        <div class="form-group">
                            <label for="status" class="form-label">Status</label>
                            <select class="form-control" id="status" name="status">
                                <option value="active">Active</option>
                                <option value="inactive">Inactive</option>
                            </select>
                        </div>
                        
                        <input type="hidden" name="add_plan" value="1">
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" form="addPlanForm" class="btn btn-primary">Add Plan</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Edit Plan Modal -->
    <div class="modal fade" id="editPlanModal" tabindex="-1" aria-labelledby="editPlanModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editPlanModalLabel">Edit Membership Plan</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="editPlanForm" method="POST">
                        <input type="hidden" id="edit_plan_id" name="plan_id">
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_plan_name" class="form-label">Plan Name *</label>
                                    <input type="text" class="form-control" id="edit_plan_name" name="plan_name" required 
                                           placeholder="e.g., Basic Plan, Premium Plan">
                                    <small class="text-muted">Each plan must have a unique name</small>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_plan_type" class="form-label">Plan Type *</label>
                                    <select class="form-control" id="edit_plan_type" name="plan_type" required>
                                        <option value="">Select Plan Type</option>
                                        <option value="With cardio">With Cardio</option>
                                        <option value="Non-cardio">Non-Cardio</option>
                                        <option value="Premium">Premium</option>
                                        <option value="Standard">Standard</option>
                                        <option value="Basic">Basic</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_duration_days" class="form-label">Duration (Days) *</label>
                                    <input type="number" class="form-control" id="edit_duration_days" name="duration_days" required 
                                           placeholder="e.g., 30, 90, 365" min="1">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_price" class="form-label">Price (PKR) *</label>
                                    <input type="number" class="form-control" id="edit_price" name="price" required 
                                           placeholder="e.g., 3000" step="0.01" min="0">
                                </div>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="edit_description" class="form-label">Description *</label>
                            <textarea class="form-control" id="edit_description" name="description" required 
                                      placeholder="Brief description of the plan" rows="2"></textarea>
                        </div>

                        <div class="form-group">
                            <label for="edit_features" class="form-label">Features</label>
                            <textarea class="form-control" id="edit_features" name="features" 
                                      placeholder="List the features (one per line)" rows="4"></textarea>
                            <small class="text-muted">Enter each feature on a new line</small>
                        </div>

                        <div class="form-group">
                            <label for="edit_status" class="form-label">Status</label>
                            <select class="form-control" id="edit_status" name="status">
                                <option value="active">Active</option>
                                <option value="inactive">Inactive</option>
                            </select>
                        </div>
                        
                        <input type="hidden" name="update_plan" value="1">
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" form="editPlanForm" class="btn btn-primary">Update Plan</button>
                </div>
            </div>
        </div>
    </div>

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

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
// SweetAlert functions
function showSuccess(message) {
    Swal.fire({
        icon: 'success',
        title: 'Success!',
        text: message,
        timer: 3000,
        showConfirmButton: false
    });
}

function showError(message) {
    Swal.fire({
        icon: 'error',
        title: 'Error!',
        text: message,
        timer: 3000,
        showConfirmButton: false
    });
}

function showConfirm(message, callback) {
    Swal.fire({
        title: 'Are you sure?',
        text: message,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, proceed!'
    }).then((result) => {
        if (result.isConfirmed) {
            callback();
        }
    });
}

// Delete plan confirmation
document.querySelectorAll('.delete-plan-btn').forEach(button => {
    button.addEventListener('click', function(e) {
        e.preventDefault();
        const deleteUrl = this.getAttribute('href');
        
        showConfirm('Are you sure you want to delete this plan?', function() {
            window.location.href = deleteUrl;
        });
    });
});

// Edit Plan Modal Open
document.querySelectorAll('.edit-plan-btn').forEach(button => {
    button.addEventListener('click', function() {
        const planId = this.getAttribute('data-id');
        const planName = this.getAttribute('data-name');
        const planType = this.getAttribute('data-type');
        const planDuration = this.getAttribute('data-duration');
        const planPrice = this.getAttribute('data-price');
        const planDescription = this.getAttribute('data-description');
        const planFeatures = this.getAttribute('data-features');
        const planStatus = this.getAttribute('data-status');
        
        // Populate edit form
        document.getElementById('edit_plan_id').value = planId;
        document.getElementById('edit_plan_name').value = planName;
        document.getElementById('edit_plan_type').value = planType;
        document.getElementById('edit_duration_days').value = planDuration;
        document.getElementById('edit_price').value = planPrice;
        document.getElementById('edit_description').value = planDescription;
        document.getElementById('edit_features').value = planFeatures;
        document.getElementById('edit_status').value = planStatus;
        
        // Show edit modal
        const editModal = new bootstrap.Modal(document.getElementById('editPlanModal'));
        editModal.show();
    });
});

// Show session messages
<?php if (isset($_SESSION['success'])): ?>
    showSuccess('<?php echo $_SESSION['success']; ?>');
    <?php unset($_SESSION['success']); ?>
<?php endif; ?>

<?php if (isset($_SESSION['error'])): ?>
    showError('<?php echo $_SESSION['error']; ?>');
    <?php unset($_SESSION['error']); ?>
<?php endif; ?>

// Modal close and reset
document.getElementById('addPlanModal').addEventListener('hidden.bs.modal', function () {
    document.getElementById('addPlanForm').reset();
});

document.getElementById('editPlanModal').addEventListener('hidden.bs.modal', function () {
    document.getElementById('editPlanForm').reset();
});
</script>