<?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'];

/* --------------------------------------------------
   FETCH CURRENT GYM INFO (SIDEBAR PURPOSE)
-------------------------------------------------- */
$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 MEMBER
-------------------------------------------------- */
if ($_POST && isset($_POST['add_member'])) {
    $name = trim($_POST['name']);
    $email = trim($_POST['email']);
    $phone = trim($_POST['phone']);
    $gender = $_POST['gender'];
    $date_of_birth = $_POST['date_of_birth'];
    $address = trim($_POST['address']);
    $emergency_contact = trim($_POST['emergency_contact']);
    $membership_type = $_POST['membership_type'];
    $join_date = $_POST['join_date'];
    $height = $_POST['height'];
    $weight = $_POST['weight'];
    $medical_conditions = trim($_POST['medical_conditions']);
    $assigned_trainer_id = !empty($_POST['assigned_trainer_id']) ? $_POST['assigned_trainer_id'] : null;

    // Logged in user (staff/admin id)
    $created_by = $_SESSION['user_id'] ?? null;

    // unique code
    $member_code = 'GM' . date('ym') . str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT);

    // Get plan duration from membership_plans table
    $plan_stmt = $db->prepare("SELECT duration_days FROM membership_plans WHERE plan_type = ? AND gym_id = ?");
    $plan_stmt->execute([$membership_type, $gym_id]);
    $plan = $plan_stmt->fetch(PDO::FETCH_ASSOC);
    
    $duration_days = $plan ? $plan['duration_days'] : 30; // Default 30 days if plan not found

    // expiry date based on plan duration
    $expiry_date = date('Y-m-d', strtotime($join_date . " + $duration_days days"));

    $query = "INSERT INTO members
            (member_id, name, email, phone, gender, date_of_birth, address, emergency_contact,
            membership_type, join_date, expiry_date, height, weight, medical_conditions,
            assigned_trainer_id, created_by, gym_id)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

    $stmt = $db->prepare($query);

    $result = $stmt->execute([
        $member_code, $name, $email, $phone, $gender, $date_of_birth, $address,
        $emergency_contact, $membership_type, $join_date, $expiry_date, $height,
        $weight, $medical_conditions, $assigned_trainer_id, $created_by, $gym_id
    ]);

    if ($result) {
        $_SESSION['success'] = 'Member added successfully! Member ID: ' . $member_code;
    } else {
        $_SESSION['error'] = 'Failed to add member!';
    }
    header("Location: members.php");
    exit();
}

/* --------------------------------------------------
   UPDATE MEMBER
-------------------------------------------------- */
if ($_POST && isset($_POST['update_member'])) {
    $member_id = $_POST['member_id'];
    $name = trim($_POST['name']);
    $email = trim($_POST['email']);
    $phone = trim($_POST['phone']);
    $gender = $_POST['gender'];
    $date_of_birth = $_POST['date_of_birth'];
    $address = trim($_POST['address']);
    $emergency_contact = trim($_POST['emergency_contact']);
    $membership_type = $_POST['membership_type'];
    $join_date = $_POST['join_date'];
    $height = $_POST['height'];
    $weight = $_POST['weight'];
    $medical_conditions = trim($_POST['medical_conditions']);
    $assigned_trainer_id = !empty($_POST['assigned_trainer_id']) ? $_POST['assigned_trainer_id'] : null;
    $status = $_POST['status'];

    $query = "UPDATE members SET 
                name = ?, 
                email = ?, 
                phone = ?, 
                gender = ?, 
                date_of_birth = ?, 
                address = ?, 
                emergency_contact = ?, 
                membership_type = ?, 
                join_date = ?, 
                height = ?, 
                weight = ?, 
                medical_conditions = ?, 
                assigned_trainer_id = ?, 
                status = ? 
              WHERE id = ? AND gym_id = ?";

    $stmt = $db->prepare($query);

    $result = $stmt->execute([
        $name, $email, $phone, $gender, $date_of_birth, $address, $emergency_contact,
        $membership_type, $join_date, $height, $weight, $medical_conditions,
        $assigned_trainer_id, $status, $member_id, $gym_id
    ]);

    if ($result) {
        $_SESSION['success'] = 'Member updated successfully!';
    } else {
        $_SESSION['error'] = 'Failed to update member!';
    }
    header("Location: members.php");
    exit();
}

/* --------------------------------------------------
   RECORD PAYMENT - COMPLETELY FIXED VERSION
-------------------------------------------------- */
if ($_POST && isset($_POST['record_payment'])) {
    $member_id = $_POST['member_id'];
    $amount = $_POST['amount'];
    $payment_date = $_POST['payment_date'];
    $payment_method = $_POST['payment_method'];
    $transaction_id = trim($_POST['transaction_id']);
    $notes = trim($_POST['notes']);
    
    // Get member details
    $member_stmt = $db->prepare("SELECT member_id, name FROM members WHERE id = ? AND gym_id = ?");
    $member_stmt->execute([$member_id, $gym_id]);
    $member = $member_stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$member) {
        $_SESSION['error'] = 'Member not found!';
        header("Location: members.php");
        exit();
    }
    
    // Generate payment ID
    $payment_id = 'PAY' . date('ym') . str_pad(rand(1, 999), 3, '0', STR_PAD_LEFT);
    
    // Check payments table structure and insert accordingly
    try {
        // First try the basic columns that should exist
        $query = "INSERT INTO payments 
                  (payment_id, member_id, amount, payment_date, payment_method, transaction_id, notes, gym_id) 
                  VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
        
        $stmt = $db->prepare($query);
        
        $result = $stmt->execute([
            $payment_id, $member_id, $amount, $payment_date, 
            $payment_method, $transaction_id, $notes, $gym_id
        ]);
        
    } catch (PDOException $e) {
        // If basic insert fails, try without payment_id
        try {
            $query = "INSERT INTO payments 
                      (member_id, amount, payment_date, payment_method, transaction_id, notes, gym_id) 
                      VALUES (?, ?, ?, ?, ?, ?, ?)";
            
            $stmt = $db->prepare($query);
            
            $result = $stmt->execute([
                $member_id, $amount, $payment_date, 
                $payment_method, $transaction_id, $notes, $gym_id
            ]);
            
            $payment_id = 'AUTO'; // Since we're not generating custom ID
            
        } catch (PDOException $e2) {
            // If still fails, try minimal columns
            try {
                $query = "INSERT INTO payments 
                          (member_id, amount, payment_date, payment_method, gym_id) 
                          VALUES (?, ?, ?, ?, ?)";
                
                $stmt = $db->prepare($query);
                
                $result = $stmt->execute([
                    $member_id, $amount, $payment_date, $payment_method, $gym_id
                ]);
                
                $payment_id = 'AUTO'; // Since we're not generating custom ID
                
            } catch (PDOException $e3) {
                $_SESSION['error'] = 'Payment table structure issue! Please check your database.';
                header("Location: members.php");
                exit();
            }
        }
    }
    
    if ($result) {
        $_SESSION['success'] = 'Payment recorded successfully!' . ($payment_id != 'AUTO' ? ' Payment ID: ' . $payment_id : '');
    } else {
        $_SESSION['error'] = 'Failed to record payment!';
    }
    header("Location: members.php");
    exit();
}

/* --------------------------------------------------
   DELETE MEMBER - ONLY FROM CURRENT GYM
-------------------------------------------------- */
if (isset($_GET['delete_id'])) {
    $delete_id = $_GET['delete_id'];

    $stmt = $db->prepare("DELETE FROM members WHERE id = ? AND gym_id = ?");
    $stmt->execute([$delete_id, $gym_id]);

    $_SESSION['success'] = "Member deleted successfully!";
    header("Location: members.php");
    exit();
}

/* --------------------------------------------------
   FETCH TRAINERS ONLY FOR CURRENT GYM
-------------------------------------------------- */
$trainers_stmt = $db->prepare("SELECT id, name, trainer_fee FROM staff WHERE role='trainer' AND status='active' AND gym_id=?");
$trainers_stmt->execute([$gym_id]);
$trainers = $trainers_stmt->fetchAll(PDO::FETCH_ASSOC);

/* --------------------------------------------------
   FETCH ACTIVE MEMBERSHIP PLANS
-------------------------------------------------- */
$plans_stmt = $db->prepare("SELECT * FROM membership_plans WHERE status='active' AND gym_id=?");
$plans_stmt->execute([$gym_id]);
$membership_plans = $plans_stmt->fetchAll(PDO::FETCH_ASSOC);

/* --------------------------------------------------
   FETCH ALL MEMBERS FOR CURRENT GYM
-------------------------------------------------- */
$query = "SELECT m.*, s.name AS trainer_name, s.trainer_fee 
          FROM members m 
          LEFT JOIN staff s ON m.assigned_trainer_id = s.id 
          WHERE m.gym_id = ? 
          ORDER BY m.created_at DESC";

$stmt = $db->prepare($query);
$stmt->execute([$gym_id]);
$members = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!-- REST OF THE HTML CODE SAME AS BEFORE -->
<?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">Members 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">Members Management</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">Gym Members</h4>
                            <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addMemberModal">
                                <i class="mdi mdi-plus-circle"></i> Add New Member
                            </button>
                        </div>
                        
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Member ID</th>
                                        <th>Name</th>
                                        <th>Phone</th>
                                        <th>Membership</th>
                                        <th>Join Date</th>
                                        <th>Expiry Date</th>
                                        <th>Trainer & Fee</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($members as $member): ?>
                                    <tr>
                                        <td>
                                            <span class="fw-bold text-primary"><?php echo $member['member_id']; ?></span>
                                        </td>
                                        <td>
                                            <div class="d-flex align-items-center">
                                                <i class="mdi mdi-account" style="font-size:30px; color:#7a7a7a;"></i>
                                                <div class="ms-3">
                                                    <div class="fw-semibold"><?php echo htmlspecialchars($member['name']); ?></div>
                                                    <small class="text-muted"><?php echo $member['email']; ?></small>
                                                </div>
                                            </div>
                                        </td>
                                        <td><?php echo $member['phone']; ?></td>
                                        <td>
                                            <label class="badge badge-<?php 
                                                echo $member['membership_type'] == 'vip' ? 'danger' : 
                                                    ($member['membership_type'] == 'premium' ? 'warning' : 
                                                    ($member['membership_type'] == 'basic' ? 'info' : 'success')); 
                                            ?>">
                                                <?php echo ucfirst($member['membership_type']); ?>
                                            </label>
                                        </td>
                                        <td><?php echo date('M d, Y', strtotime($member['join_date'])); ?></td>
                                        <td>
                                            <?php 
                                            $expiry_date = strtotime($member['expiry_date']);
                                            $today = strtotime(date('Y-m-d'));
                                            $days_left = ceil(($expiry_date - $today) / (60 * 60 * 24));
                                            
                                            if ($days_left < 0) {
                                                echo '<span class="text-danger">' . date('M d, Y', $expiry_date) . '</span>';
                                            } elseif ($days_left <= 7) {
                                                echo '<span class="text-warning">' . date('M d, Y', $expiry_date) . '</span>';
                                            } else {
                                                echo date('M d, Y', $expiry_date);
                                            }
                                            ?>
                                        </td>
                                        <td>
                                            <?php if ($member['trainer_name'] && isset($member['trainer_fee'])): ?>
                                                <div class="trainer-info">
                                                    <div class="fw-semibold"><?php echo $member['trainer_name']; ?></div>
                                                    <small class="text-success">Fee: Rs. <?php echo number_format($member['trainer_fee']); ?></small>
                                                </div>
                                            <?php else: ?>
                                                <span class="text-muted">Not Assigned</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <label class="badge badge-<?php 
                                                echo $member['status'] == 'active' ? 'success' : 
                                                    ($member['status'] == 'expired' ? 'danger' : 'warning'); 
                                            ?>">
                                                <?php echo ucfirst($member['status']); ?>
                                            </label>
                                        </td>
                                        <td>
                                            <button class="btn btn-sm btn-primary edit-member-btn" 
                                                    data-id="<?php echo $member['id']; ?>"
                                                    data-name="<?php echo htmlspecialchars($member['name']); ?>"
                                                    data-email="<?php echo htmlspecialchars($member['email']); ?>"
                                                    data-phone="<?php echo $member['phone']; ?>"
                                                    data-gender="<?php echo $member['gender']; ?>"
                                                    data-date-of-birth="<?php echo $member['date_of_birth']; ?>"
                                                    data-address="<?php echo htmlspecialchars($member['address']); ?>"
                                                    data-emergency-contact="<?php echo $member['emergency_contact']; ?>"
                                                    data-membership-type="<?php echo $member['membership_type']; ?>"
                                                    data-join-date="<?php echo $member['join_date']; ?>"
                                                    data-height="<?php echo $member['height']; ?>"
                                                    data-weight="<?php echo $member['weight']; ?>"
                                                    data-medical-conditions="<?php echo htmlspecialchars($member['medical_conditions']); ?>"
                                                    data-assigned-trainer-id="<?php echo $member['assigned_trainer_id']; ?>"
                                                    data-status="<?php echo $member['status']; ?>">
                                                <i class="mdi mdi-pencil"></i>
                                            </button>
                                            <a href="members.php?delete_id=<?php echo $member['id']; ?>" 
                                               class="btn btn-sm btn-danger delete-member-btn">
                                                <i class="mdi mdi-delete"></i>
                                            </a>
                                            <button class="btn btn-sm btn-info payment-btn" 
                                                    data-member-id="<?php echo $member['id']; ?>"
                                                    data-member-name="<?php echo htmlspecialchars($member['name']); ?>">
                                                <i class="mdi mdi-credit-card"></i>
                                            </button>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                    
                                    <?php if (empty($members)): ?>
                                    <tr>
                                        <td colspan="9" class="text-center text-muted py-4">
                                            <i class="mdi mdi-account-off-outline display-4 d-block mb-2"></i>
                                            No members found. <a href="#" data-bs-toggle="modal" data-bs-target="#addMemberModal">Add the first member</a>.
                                        </td>
                                    </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Add Member Modal -->
    <div class="modal fade" id="addMemberModal" tabindex="-1" aria-labelledby="addMemberModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="addMemberModalLabel">Add New Member</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="addMemberForm" method="POST">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="name" class="form-label">Full Name *</label>
                                    <input type="text" class="form-control" id="name" name="name" required 
                                           placeholder="Enter full name">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="email" class="form-label">Email Address</label>
                                    <input type="email" class="form-control" id="email" name="email" 
                                           placeholder="Enter email address">
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="phone" class="form-label">Phone Number *</label>
                                    <input type="text" class="form-control" id="phone" name="phone" required 
                                           placeholder="0300-1234567">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="gender" class="form-label">Gender</label>
                                    <select class="form-control" id="gender" name="gender">
                                        <option value="">Select Gender</option>
                                        <option value="male">Male</option>
                                        <option value="female">Female</option>
                                        <option value="other">Other</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="date_of_birth" class="form-label">Date of Birth</label>
                                    <input type="date" class="form-control" id="date_of_birth" name="date_of_birth">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="emergency_contact" class="form-label">Emergency Contact</label>
                                    <input type="text" class="form-control" id="emergency_contact" name="emergency_contact" 
                                           placeholder="Emergency phone number">
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="membership_type" class="form-label">Membership Type *</label>
                                    <select class="form-control" id="membership_type" name="membership_type" required>
                                        <option value="">Select Membership</option>
                                        <?php foreach ($membership_plans as $plan): ?>
                                        <option value="<?php echo $plan['plan_type']; ?>">
                                            <?php echo $plan['plan_name'] . ' - Rs. ' . number_format($plan['price']) . ' (' . $plan['duration_days'] . ' days)'; ?>
                                        </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="join_date" class="form-label">Join Date *</label>
                                    <input type="date" class="form-control" id="join_date" name="join_date" required 
                                           value="<?php echo date('Y-m-d'); ?>">
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="height" class="form-label">Height (cm)</label>
                                    <input type="number" class="form-control" id="height" name="height" 
                                           placeholder="Height in cm" step="0.1">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="weight" class="form-label">Weight (kg)</label>
                                    <input type="number" class="form-control" id="weight" name="weight" 
                                           placeholder="Weight in kg" step="0.1">
                                </div>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="assigned_trainer_id" class="form-label">Assigned Trainer</label>
                            <select class="form-control" id="assigned_trainer_id" name="assigned_trainer_id">
                                <option value="">Select Trainer</option>
                                <?php foreach ($trainers as $trainer): ?>
                                <option value="<?php echo $trainer['id']; ?>">
                                    <?php echo $trainer['name']; ?> - Rs. <?php echo number_format($trainer['trainer_fee']); ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="address" class="form-label">Address</label>
                            <textarea class="form-control" id="address" name="address" rows="3" 
                                      placeholder="Enter full address"></textarea>
                        </div>

                        <div class="form-group">
                            <label for="medical_conditions" class="form-label">Medical Conditions</label>
                            <textarea class="form-control" id="medical_conditions" name="medical_conditions" rows="2" 
                                      placeholder="Any medical conditions or allergies"></textarea>
                        </div>
                        
                        <input type="hidden" name="add_member" 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="addMemberForm" class="btn btn-primary">Add Member</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Edit Member Modal -->
    <div class="modal fade" id="editMemberModal" tabindex="-1" aria-labelledby="editMemberModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editMemberModalLabel">Edit Member</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="editMemberForm" method="POST">
                        <input type="hidden" id="edit_member_id" name="member_id">
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_name" class="form-label">Full Name *</label>
                                    <input type="text" class="form-control" id="edit_name" name="name" required 
                                           placeholder="Enter full name">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_email" class="form-label">Email Address</label>
                                    <input type="email" class="form-control" id="edit_email" name="email" 
                                           placeholder="Enter email address">
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_phone" class="form-label">Phone Number *</label>
                                    <input type="text" class="form-control" id="edit_phone" name="phone" required 
                                           placeholder="0300-1234567">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_gender" class="form-label">Gender</label>
                                    <select class="form-control" id="edit_gender" name="gender">
                                        <option value="">Select Gender</option>
                                        <option value="male">Male</option>
                                        <option value="female">Female</option>
                                        <option value="other">Other</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_date_of_birth" class="form-label">Date of Birth</label>
                                    <input type="date" class="form-control" id="edit_date_of_birth" name="date_of_birth">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_emergency_contact" class="form-label">Emergency Contact</label>
                                    <input type="text" class="form-control" id="edit_emergency_contact" name="emergency_contact" 
                                           placeholder="Emergency phone number">
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_membership_type" class="form-label">Membership Type *</label>
                                    <select class="form-control" id="edit_membership_type" name="membership_type" required>
                                        <option value="">Select Membership</option>
                                        <?php foreach ($membership_plans as $plan): ?>
                                        <option value="<?php echo $plan['plan_type']; ?>">
                                            <?php echo $plan['plan_name']; ?>
                                        </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_join_date" class="form-label">Join Date *</label>
                                    <input type="date" class="form-control" id="edit_join_date" name="join_date" required>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_height" class="form-label">Height (cm)</label>
                                    <input type="number" class="form-control" id="edit_height" name="height" 
                                           placeholder="Height in cm" step="0.1">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="edit_weight" class="form-label">Weight (kg)</label>
                                    <input type="number" class="form-control" id="edit_weight" name="weight" 
                                           placeholder="Weight in kg" step="0.1">
                                </div>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="edit_assigned_trainer_id" class="form-label">Assigned Trainer</label>
                            <select class="form-control" id="edit_assigned_trainer_id" name="assigned_trainer_id">
                                <option value="">Select Trainer</option>
                                <?php foreach ($trainers as $trainer): ?>
                                <option value="<?php echo $trainer['id']; ?>">
                                    <?php echo $trainer['name']; ?> - Rs. <?php echo number_format($trainer['trainer_fee']); ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </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="expired">Expired</option>
                                <option value="cancelled">Cancelled</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="edit_address" class="form-label">Address</label>
                            <textarea class="form-control" id="edit_address" name="address" rows="3" 
                                      placeholder="Enter full address"></textarea>
                        </div>

                        <div class="form-group">
                            <label for="edit_medical_conditions" class="form-label">Medical Conditions</label>
                            <textarea class="form-control" id="edit_medical_conditions" name="medical_conditions" rows="2" 
                                      placeholder="Any medical conditions or allergies"></textarea>
                        </div>
                        
                        <input type="hidden" name="update_member" 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="editMemberForm" class="btn btn-primary">Update Member</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Payment Modal -->
    <div class="modal fade" id="paymentModal" tabindex="-1" aria-labelledby="paymentModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="paymentModalLabel">Record Payment</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="paymentForm" method="POST">
                        <input type="hidden" id="payment_member_id" name="member_id">
                        
                        <div class="form-group">
                            <label for="member_name" class="form-label">Member Name</label>
                            <input type="text" class="form-control" id="member_name" readonly>
                        </div>
                        
                        <div class="form-group">
                            <label for="amount" class="form-label">Amount (PKR) *</label>
                            <input type="number" class="form-control" id="amount" name="amount" required 
                                   placeholder="Enter amount" step="0.01">
                        </div>
                        
                        <div class="form-group">
                            <label for="payment_date" class="form-label">Payment Date *</label>
                            <input type="date" class="form-control" id="payment_date" name="payment_date" required 
                                   value="<?php echo date('Y-m-d'); ?>">
                        </div>
                        
                        <div class="form-group">
                            <label for="payment_method" class="form-label">Payment Method *</label>
                            <select class="form-control" id="payment_method" name="payment_method" required>
                                <option value="">Select Method</option>
                                <option value="cash">Cash</option>
                                <option value="card">Credit/Debit Card</option>
                                <option value="bank_transfer">Bank Transfer</option>
                                <option value="easypaisa">Easypaisa</option>
                                <option value="jazzcash">JazzCash</option>
                                <option value="paypal">PayPal</option>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label for="transaction_id" class="form-label">Transaction ID</label>
                            <input type="text" class="form-control" id="transaction_id" name="transaction_id" 
                                   placeholder="Transaction reference number">
                        </div>
                        
                        <div class="form-group">
                            <label for="notes" class="form-label">Notes</label>
                            <textarea class="form-control" id="notes" name="notes" rows="2" 
                                      placeholder="Additional notes"></textarea>
                        </div>
                        
                        <input type="hidden" name="record_payment" 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="paymentForm" class="btn btn-primary">Record Payment</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 member confirmation
document.querySelectorAll('.delete-member-btn').forEach(button => {
    button.addEventListener('click', function(e) {
        e.preventDefault();
        const deleteUrl = this.getAttribute('href');
        
        showConfirm('Are you sure you want to delete this member?', function() {
            window.location.href = deleteUrl;
        });
    });
});

// Edit Member Modal Open
document.querySelectorAll('.edit-member-btn').forEach(button => {
    button.addEventListener('click', function() {
        const memberId = this.getAttribute('data-id');
        const memberName = this.getAttribute('data-name');
        const memberEmail = this.getAttribute('data-email');
        const memberPhone = this.getAttribute('data-phone');
        const memberGender = this.getAttribute('data-gender');
        const memberDOB = this.getAttribute('data-date-of-birth');
        const memberAddress = this.getAttribute('data-address');
        const memberEmergencyContact = this.getAttribute('data-emergency-contact');
        const memberMembershipType = this.getAttribute('data-membership-type');
        const memberJoinDate = this.getAttribute('data-join-date');
        const memberHeight = this.getAttribute('data-height');
        const memberWeight = this.getAttribute('data-weight');
        const memberMedicalConditions = this.getAttribute('data-medical-conditions');
        const memberTrainerId = this.getAttribute('data-assigned-trainer-id');
        const memberStatus = this.getAttribute('data-status');
        
        // Populate edit form
        document.getElementById('edit_member_id').value = memberId;
        document.getElementById('edit_name').value = memberName;
        document.getElementById('edit_email').value = memberEmail;
        document.getElementById('edit_phone').value = memberPhone;
        document.getElementById('edit_gender').value = memberGender;
        document.getElementById('edit_date_of_birth').value = memberDOB;
        document.getElementById('edit_address').value = memberAddress;
        document.getElementById('edit_emergency_contact').value = memberEmergencyContact;
        document.getElementById('edit_membership_type').value = memberMembershipType;
        document.getElementById('edit_join_date').value = memberJoinDate;
        document.getElementById('edit_height').value = memberHeight;
        document.getElementById('edit_weight').value = memberWeight;
        document.getElementById('edit_medical_conditions').value = memberMedicalConditions;
        document.getElementById('edit_assigned_trainer_id').value = memberTrainerId;
        document.getElementById('edit_status').value = memberStatus;
        
        // Show edit modal
        const editModal = new bootstrap.Modal(document.getElementById('editMemberModal'));
        editModal.show();
    });
});

// Payment Modal Open
document.querySelectorAll('.payment-btn').forEach(button => {
    button.addEventListener('click', function() {
        const memberId = this.getAttribute('data-member-id');
        const memberName = this.getAttribute('data-member-name');
        
        document.getElementById('payment_member_id').value = memberId;
        document.getElementById('member_name').value = memberName;
        
        const paymentModal = new bootstrap.Modal(document.getElementById('paymentModal'));
        paymentModal.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('addMemberModal').addEventListener('hidden.bs.modal', function () {
    document.getElementById('addMemberForm').reset();
});

document.getElementById('editMemberModal').addEventListener('hidden.bs.modal', function () {
    document.getElementById('editMemberForm').reset();
});

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