<?php
session_start();
include 'includes/auth.php';
include 'includes/db.php';

// Validate ID
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header("Location: members_all.php");
    exit;
}

$id = (int)$_GET['id'];

// Fetch member data
$result = mysqli_query($conn, "SELECT * FROM members WHERE id = $id");
if (mysqli_num_rows($result) == 0) {
    echo "<p>Member not found.</p>";
    exit;
}

$member = mysqli_fetch_assoc($result);

// Handle update
if (isset($_POST['update'])) {
    $membership_type = mysqli_real_escape_string($conn, $_POST['membership_type']);
    $family_members = $_POST['family_members'] ?? [];

    $email = mysqli_real_escape_string($conn, $_POST['email']);
    $password = !empty($_POST['password']) ? password_hash($_POST['password'], PASSWORD_DEFAULT) : $member['password'];
    $photo = $member['photo']; // default to existing

    if (isset($_FILES['photo']) && $_FILES['photo']['error'] === UPLOAD_ERR_OK) {
        $upload_dir = 'uploads/';
        $tmp_name = $_FILES['photo']['tmp_name'];
        $filename = uniqid() . '_' . basename($_FILES['photo']['name']);
        $target_file = $upload_dir . $filename;

        $file_type = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
        if (in_array($file_type, ['jpg', 'jpeg', 'png'])) {
            if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);
            move_uploaded_file($tmp_name, $target_file);
            $photo = $filename;
        }
    }

    // Remove previous links
    mysqli_query($conn, "DELETE FROM family_links WHERE member_id = $id");

    // If family membership, insert links
     if ($membership_type === 'family_28') {
        $group_id = time(); // unique group
        mysqli_query($conn, "INSERT INTO family_links (group_id, member_id) VALUES ($group_id, $id)");

        foreach ($family_members as $fam_id) {
            $fid = (int)$fam_id;
            mysqli_query($conn, "INSERT INTO family_links (group_id, member_id) VALUES ($group_id, $fid)");
            mysqli_query($conn, "UPDATE members SET membership_type = 'family_28' WHERE id = $fid");
        }
    }
    // The rest of your fields (no change below)
    $first_name = mysqli_real_escape_string($conn, $_POST['first_name']);
    $middle_name = mysqli_real_escape_string($conn, $_POST['middle_name']);
    $surname = mysqli_real_escape_string($conn, $_POST['surname']);
    $joined = mysqli_real_escape_string($conn, $_POST['joined']);
    $paid_amount = mysqli_real_escape_string($conn, $_POST['paid_amount']);
    $paid_date = mysqli_real_escape_string($conn, $_POST['paid_date']);
    $expiry_date = mysqli_real_escape_string($conn, $_POST['expiry_date']);
    $notes = mysqli_real_escape_string($conn, $_POST['notes']);
    $phone = mysqli_real_escape_string($conn, $_POST['phone']);
    $next_of_kin = mysqli_real_escape_string($conn, $_POST['next_of_kin']);
    $relationship = mysqli_real_escape_string($conn, $_POST['relationship']);
    $next_of_kin_phone = mysqli_real_escape_string($conn, $_POST['next_of_kin_phone']);
    $payment_status = mysqli_real_escape_string($conn, $_POST['payment_status']);
    $gender = mysqli_real_escape_string($conn, $_POST['gender']);
    $dob = mysqli_real_escape_string($conn, $_POST['dob']);
    $medical_condition = mysqli_real_escape_string($conn, $_POST['medical_condition']);
    $current_medication = mysqli_real_escape_string($conn, $_POST['current_medication']);
    $permission = mysqli_real_escape_string($conn, $_POST['permission']);
    $waiver_print_name = mysqli_real_escape_string($conn, $_POST['waiver_print_name']);
    $signature_data1 = mysqli_real_escape_string($conn, $_POST['signature_data1']);
    $signature_data2 = mysqli_real_escape_string($conn, $_POST['signature_data2']);
    $signature_date = mysqli_real_escape_string($conn, $_POST['signature_date']);
    $q1 = mysqli_real_escape_string($conn, $_POST['q1']);
    $q2 = mysqli_real_escape_string($conn, $_POST['q2']);
    $q3 = mysqli_real_escape_string($conn, $_POST['q3']);
    $q4 = mysqli_real_escape_string($conn, $_POST['q4']);
    $q5 = mysqli_real_escape_string($conn, $_POST['q5']);
    $q6 = mysqli_real_escape_string($conn, $_POST['q6']);
    $q7 = mysqli_real_escape_string($conn, $_POST['q7']);
    $q8 = mysqli_real_escape_string($conn, $_POST['q8']);
    $q9 = mysqli_real_escape_string($conn, $_POST['q9']);
    $q10 = mysqli_real_escape_string($conn, $_POST['q10']);
    $q11 = mysqli_real_escape_string($conn, $_POST['q11']);
    $other_info = mysqli_real_escape_string($conn, $_POST['other_info']);

    // If email is blank, keep the old one
if (empty($email)) {
    $email = $member['email'];
}

$sql = "UPDATE members SET
    photo='$photo',
    membership_type = '$membership_type',
    email='$email',
    password='$password',
    first_name='$first_name',
    middle_name='$middle_name',
    surname='$surname',
    joined='$joined',
    paid_amount='$paid_amount',
    paid_date='$paid_date',
    expiry_date='$expiry_date',
    notes='$notes',
    phone='$phone',
    next_of_kin='$next_of_kin',
    relationship='$relationship',
    next_of_kin_phone='$next_of_kin_phone',
    payment_status='$payment_status',
    gender='$gender',
    dob='$dob',
    medical_condition='$medical_condition',
    current_medication='$current_medication',
    permission='$permission',
    waiver_print_name='$waiver_print_name',
    signature_data1='$signature_data1',
    signature_data2='$signature_data2',
    signature_date='$signature_date',
    q1='$q1', q2='$q2', q3='$q3', q4='$q4', q5='$q5', q6='$q6', q7='$q7', q8='$q8', q9='$q9', q10='$q10', q11='$q11',
    other_info='$other_info'
    WHERE id = $id";

if (mysqli_query($conn, $sql)) {
    echo "<script>alert('Member updated successfully!'); window.location.href='members_all.php';</script>";
} else {
    echo "<div class='alert alert-danger'>Update failed: " . mysqli_error($conn) . "</div>";
}


       
     
}

?>

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

<h2>Edit Member #<?php echo $id; ?></h2>

<form method="post" class="row g-3" enctype="multipart/form-data">
<div class="col-md-4">
  <label>Photo:</label>
  <?php if (!empty($member['photo'])): ?>
      <div class="mb-2"><img src="uploads/<?php echo htmlspecialchars($member['photo']); ?>" style="width:100px;height:auto;"></div>
  <?php endif; ?>
  <input type="file" name="photo" class="form-control">
</div>

    <div class="col-md-4"><label>Email:</label><input type="email" name="email" value="<?php echo htmlspecialchars($member['email']); ?>" class="form-control" ></div>
    <div class="col-md-4"><label>New Password (leave blank to keep):</label><input type="password" name="password" class="form-control"></div>

    <div class="col-md-4"><label>First Name:</label><input type="text" name="first_name" value="<?php echo htmlspecialchars($member['first_name']); ?>" class="form-control"></div>
    <div class="col-md-4"><label>Middle Name:</label><input type="text" name="middle_name" value="<?php echo htmlspecialchars($member['middle_name']); ?>" class="form-control"></div>
    <div class="col-md-4"><label>Surname:</label><input type="text" name="surname" value="<?php echo htmlspecialchars($member['surname']); ?>" class="form-control"></div>

    <div class="col-md-4"><label>Phone:</label><input type="text" name="phone" value="<?php echo htmlspecialchars($member['phone']); ?>" class="form-control"></div>
    <div class="col-md-4"><label>Next of Kin:</label><input type="text" name="next_of_kin" value="<?php echo htmlspecialchars($member['next_of_kin']); ?>" class="form-control"></div>
    <div class="col-md-4"><label>Relationship:</label><input type="text" name="relationship" value="<?php echo htmlspecialchars($member['relationship']); ?>" class="form-control"></div>
    <div class="col-md-4"><label>Next of Kin Phone:</label><input type="text" name="next_of_kin_phone" value="<?php echo htmlspecialchars($member['next_of_kin_phone']); ?>" class="form-control"></div>

    <div class="col-md-4"><label>Paid Amount:</label><input type="number" step="0.01" name="paid_amount" value="<?php echo htmlspecialchars($member['paid_amount']); ?>" class="form-control"></div>
    <div class="col-md-4"><label>Paid Date:</label><input type="date" name="paid_date" value="<?php echo htmlspecialchars($member['paid_date']); ?>" class="form-control"></div>
    <div class="col-md-4"><label>Expiry Date:</label><input type="date" name="expiry_date" value="<?php echo htmlspecialchars($member['expiry_date']); ?>" class="form-control"></div>
    
    <div class="col-md-4">
 <div class="col-md-4">
  <label>Membership Type:</label>
  <select name="membership_type" id="membership_type" class="form-select">
    <option value="">-- Select --</option>
    <option value="1_day" <?= $member['membership_type'] == '1_day' ? 'selected' : '' ?>>Drop In - 1 Day</option>
    <option value="28_days" <?= $member['membership_type'] == '28_days' ? 'selected' : '' ?>>28 Days</option>
    <option value="3_months" <?= $member['membership_type'] == '3_months' ? 'selected' : '' ?>>3 Months</option>
    <option value="family_28" <?= $member['membership_type'] == 'family_28' ? 'selected' : '' ?>>Family of Four - 28 Days</option>
  </select>
</div>

<div class="col-md-12" id="familyMembersBox" style="display: none;">
 <select name="family_members[]" class="form-select select2" multiple>
    <?php
    // Get group_id of this member (if any)
    $groupRes = mysqli_query($conn, "SELECT group_id FROM family_links WHERE member_id = $id LIMIT 1");
    $group_id = mysqli_num_rows($groupRes) ? (int)mysqli_fetch_assoc($groupRes)['group_id'] : 0;

    // Get other member IDs in same group
    $linked_ids = [];
    if ($group_id) {
        $linkedRes = mysqli_query($conn, "SELECT member_id FROM family_links WHERE group_id = $group_id AND member_id != $id");
        while ($row = mysqli_fetch_assoc($linkedRes)) {
            $linked_ids[] = (int)$row['member_id'];
        }
    }

    // Fetch all other members
    $membersQuery = mysqli_query($conn, "SELECT id, first_name, surname FROM members WHERE id != $id");
    while ($m = mysqli_fetch_assoc($membersQuery)) {
        $fid = (int)$m['id'];
        $fullname = htmlspecialchars($m['first_name'] . ' ' . $m['surname']);
        $selected = in_array($fid, $linked_ids) ? 'selected' : '';
        echo "<option value='$fid' $selected>$fullname</option>";
    }
    ?>
</select>

</div></div>


 



    <div class="col-md-4"><label>Payment Status:</label>
        <select name="payment_status" class="form-select">
            <option value="OK" <?php if ($member['payment_status']=='OK') echo 'selected'; ?>>OK</option>
            <option value="Due" <?php if ($member['payment_status']=='Due') echo 'selected'; ?>>Due</option>
            <option value="Expired" <?php if ($member['payment_status']=='Expired') echo 'selected'; ?>>Expired</option>
        </select>
    </div>

    <div class="col-md-4"><label>Gender:</label><input type="text" name="gender" value="<?php echo htmlspecialchars($member['gender']); ?>" class="form-control"></div>
    <div class="col-md-4"><label>Date of Birth:</label><input type="date" name="dob" value="<?php echo htmlspecialchars($member['dob']); ?>" class="form-control"></div>

    <div class="col-12"><label>Medical Condition:</label><input type="text" name="medical_condition" value="<?php echo htmlspecialchars($member['medical_condition']); ?>" class="form-control"></div>
    <div class="col-12"><label>Current Medication:</label><textarea name="current_medication" class="form-control"><?php echo htmlspecialchars($member['current_medication']); ?></textarea></div>

    <div class="col-12"><label>Permission to Contact:</label>
        <select name="permission" class="form-select">
            <option value="Yes" <?php if ($member['permission']=='Yes') echo 'selected'; ?>>Yes</option>
            <option value="No" <?php if ($member['permission']=='No') echo 'selected'; ?>>No</option>
        </select>
    </div>

    <div class="col-12">
    <label>Do you lose your balance because of dizziness, or do you ever lose consciousness?</label>
    <select name="q1" class="form-select">
        <option value="Yes" <?php if ($member["q1"]=='Yes') echo 'selected'; ?>>Yes</option>
        <option value="No" <?php if ($member["q1"]=='No') echo 'selected'; ?>>No</option>
    </select>
</div>

<div class="col-12">
    <label>Has your doctor ever said you have a heart condition and should only do physical activity recommended by a doctor?</label>
    <select name="q2" class="form-select">
        <option value="Yes" <?php if ($member["q2"]=='Yes') echo 'selected'; ?>>Yes</option>
        <option value="No" <?php if ($member["q2"]=='No') echo 'selected'; ?>>No</option>
    </select>
</div>

<div class="col-12">
    <label>Do you feel pain in your chest when you do physical activity?</label>
    <select name="q3" class="form-select">
        <option value="Yes" <?php if ($member["q3"]=='Yes') echo 'selected'; ?>>Yes</option>
        <option value="No" <?php if ($member["q3"]=='No') echo 'selected'; ?>>No</option>
    </select>
</div>

<div class="col-12">
    <label>Are you being treated for high blood pressure?</label>
    <select name="q4" class="form-select">
        <option value="Yes" <?php if ($member["q4"]=='Yes') echo 'selected'; ?>>Yes</option>
        <option value="No" <?php if ($member["q4"]=='No') echo 'selected'; ?>>No</option>
    </select>
</div>

<div class="col-12">
    <label>Do you have diabetes?</label>
    <select name="q5" class="form-select">
        <option value="Yes" <?php if ($member["q5"]=='Yes') echo 'selected'; ?>>Yes</option>
        <option value="No" <?php if ($member["q5"]=='No') echo 'selected'; ?>>No</option>
    </select>
</div>

<div class="col-12">
    <label>Do you have asthma or any other respiratory problems?</label>
    <select name="q6" class="form-select">
        <option value="Yes" <?php if ($member["q6"]=='Yes') echo 'selected'; ?>>Yes</option>
        <option value="No" <?php if ($member["q6"]=='No') echo 'selected'; ?>>No</option>
    </select>
</div>

<div class="col-12">
    <label>Do you have any bone or joint problems that could be made worse by a change in your physical activity?</label>
    <select name="q7" class="form-select">
        <option value="Yes" <?php if ($member["q7"]=='Yes') echo 'selected'; ?>>Yes</option>
        <option value="No" <?php if ($member["q7"]=='No') echo 'selected'; ?>>No</option>
    </select>
</div>

<div class="col-12">
    <label>Do you have epilepsy?</label>
    <select name="q8" class="form-select">
        <option value="Yes" <?php if ($member["q8"]=='Yes') echo 'selected'; ?>>Yes</option>
        <option value="No" <?php if ($member["q8"]=='No') echo 'selected'; ?>>No</option>
    </select>
</div>

<div class="col-12">
    <label>Do you have a pacemaker?</label>
    <select name="q9" class="form-select">
        <option value="Yes" <?php if ($member["q9"]=='Yes') echo 'selected'; ?>>Yes</option>
        <option value="No" <?php if ($member["q9"]=='No') echo 'selected'; ?>>No</option>
    </select>
</div>

<div class="col-12">
    <label>Are you pregnant?</label>
    <select name="q10" class="form-select">
        <option value="Yes" <?php if ($member["q10"]=='Yes') echo 'selected'; ?>>Yes</option>
        <option value="No" <?php if ($member["q10"]=='No') echo 'selected'; ?>>No</option>
    </select>
</div>

<div class="col-12">
    <label>Do you know any other reasons you should not engage in physical activity?</label>
    <select name="q11" class="form-select">
        <option value="Yes" <?php if ($member["q11"]=='Yes') echo 'selected'; ?>>Yes</option>
        <option value="No" <?php if ($member["q11"]=='No') echo 'selected'; ?>>No</option>
    </select>
</div>


    <div class="col-12"><label>Other Info:</label><textarea name="other_info" class="form-control"><?php echo htmlspecialchars($member['other_info']); ?></textarea></div>
    <div class="col-12"><label>Waiver Print Name:</label><input type="text" name="waiver_print_name" value="<?php echo htmlspecialchars($member['waiver_print_name']); ?>" class="form-control"></div>
   <div class="col-12">
    <label>Signature 1:</label><br>
    <?php if (!empty($member['signature_data1'])): ?>
        <p>Current Signature:</p>
        <img src="<?php echo $member['signature_data1']; ?>" style="border:1px solid #ccc; max-width:100%; height:auto;">
    <?php endif; ?>
    <canvas id="signature-pad1" class="signature-pad" style="border:1px solid #ccc; width:100%; height:200px;"></canvas>
    <input type="hidden" name="signature_data1" id="signature_data1">
    <button type="button" class="btn btn-secondary btn-sm mt-2" id="clear-signature1">Clear Signature</button>
</div>

<div class="col-12">
    <label>Signature 2:</label><br>
    <?php if (!empty($member['signature_data2'])): ?>
        <p>Current Signature:</p>
        <img src="<?php echo $member['signature_data2']; ?>" style="border:1px solid #ccc; max-width:100%; height:auto;">
    <?php endif; ?>
    <canvas id="signature-pad2" class="signature-pad" style="border:1px solid #ccc; width:100%; height:200px;"></canvas>
    <input type="hidden" name="signature_data2" id="signature_data2">
    <button type="button" class="btn btn-secondary btn-sm mt-2" id="clear-signature2">Clear Signature</button>
</div>


    <div class="col-12">
        <label>Notes:</label><textarea name="notes" class="form-control"><?php echo htmlspecialchars($member['notes']); ?></textarea>
    </div>

    <div class="col-12">
        <button type="submit" name="update" class="btn btn-success"><i class="fas fa-save"></i> Update Member</button>
        <a href="members_all.php" class="btn btn-secondary">Cancel</a>
    </div>

</form>
<!-- jQuery FIRST -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<!-- Select2 AFTER jQuery -->
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<!-- Your script that calls $('.select2').select2() -->
<script>
$(document).ready(function() {
  $('.select2').select2({
    placeholder: "Start typing a member's name",
    allowClear: true,
    width: '100%'
  });

  function toggleFamilyBox() {
    const value = $('#membership_type').val();
    if (value === 'family_28') {
      $('#familyMembersBox').slideDown();
    } else {
      $('#familyMembersBox').slideUp();
    }
  }

  $('#membership_type').on('change', toggleFamilyBox);
  toggleFamilyBox(); // run on load
});
</script>

<script src="https://cdn.jsdelivr.net/npm/signature_pad@4.1.6/dist/signature_pad.umd.min.js"></script>
<script>
function resizeCanvas(canvas) {
    const ratio = Math.max(window.devicePixelRatio || 1, 1);
    canvas.width = canvas.offsetWidth * ratio;
    canvas.height = canvas.offsetHeight * ratio;
    canvas.getContext("2d").scale(ratio, ratio);
}

const canvas1 = document.getElementById('signature-pad1');
const canvas2 = document.getElementById('signature-pad2');
resizeCanvas(canvas1);
resizeCanvas(canvas2);

const sigPad1 = new SignaturePad(canvas1);
const sigPad2 = new SignaturePad(canvas2);

document.getElementById('clear-signature1').addEventListener('click', () => sigPad1.clear());
document.getElementById('clear-signature2').addEventListener('click', () => sigPad2.clear());

document.querySelector('form').addEventListener('submit', function() {
    if (!sigPad1.isEmpty()) {
        document.getElementById('signature_data1').value = sigPad1.toDataURL();
    } else {
        document.getElementById('signature_data1').value = '<?php echo $member['signature_data1']; ?>'; // keep old if blank
    }
    if (!sigPad2.isEmpty()) {
        document.getElementById('signature_data2').value = sigPad2.toDataURL();
    } else {
        document.getElementById('signature_data2').value = '<?php echo $member['signature_data2']; ?>'; // keep old if blank
    }
});
</script>
<script>
function updateExpiryDate() {
    const type = document.getElementById('membership_type').value;
    const paidDateField = document.querySelector('[name="paid_date"]');
    const expiryDateField = document.querySelector('[name="expiry_date"]');
    const paidDate = new Date(paidDateField.value);

    if (!paidDate || isNaN(paidDate)) return;

    let daysToAdd = 0;
    if (type === '1_day') daysToAdd = 1;
    if (type === '28_days' || type === 'family_28') daysToAdd = 28;
    if (type === '3_months') daysToAdd = 90;

    paidDate.setDate(paidDate.getDate() + daysToAdd);
    expiryDateField.value = paidDate.toISOString().split('T')[0];
}

document.getElementById('membership_type').addEventListener('change', updateExpiryDate);
document.querySelector('[name="paid_date"]').addEventListener('change', updateExpiryDate);
</script>

 


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