<?php
require_once 'db.php';

$nextNo = (int)mysqli_fetch_row(
    mysqli_query($conn, "SELECT MAX(CAST(member_number AS UNSIGNED)) FROM members")
)[0] + 1;

$success = false;
$errors = [];

// Only run if POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // Helper
    function safe($key) {
        return isset($_POST[$key]) ? htmlspecialchars(trim($_POST[$key])) : '';
    }

    // Values
    $member_number       = (int) safe('member_number');
    $first_name          = safe('first_name');
    $middle_name         = safe('middle_name');
    $surname             = safe('surname');
    $joined              = date('Y-m-d');
    $paid_amount         = '';
    $paid_date           = '';
    $expiry_date         = '';
    $notes               = '';
    $phone               = safe('phone');
    $next_of_kin         = safe('next_of_kin');
    $relationship        = safe('relationship');
    $next_of_kin_phone   = safe('kin_contact');
    $payment_status      = 'Due';
    $email               = safe('email');
    $password            = null;
    $gender              = safe('gender');
    $dob                 = safe('dob');
    $medical_condition   = safe('medical_condition');
    $current_medication  = safe('current_medication');
    $permission          = safe('permission');
    $nfc_uid             = '';
    $membership_type     = 'Pending';
    $banned              = 'No';
    $address             = safe('address');

    // Handle photo
    $photo = '';
    if (!empty($_POST['photo_capture'])) {
        $data = $_POST['photo_capture'];
        if (preg_match('/^data:image\/jpeg;base64,/', $data)) {
            $data = substr($data, strlen('data:image/jpeg;base64,'));
            $data = str_replace(' ', '+', $data);
            $imageData = base64_decode($data);

            $photoName = 'photo_' . time() . '_' . rand(1000,9999) . '.jpg';
            $photoPath = __DIR__ . '/admin/uploads/' . $photoName;

            if (file_put_contents($photoPath, $imageData)) {
                $photo = $photoName;
            } else {
                $errors[] = "Failed to save photo.";
            }
        }
    }

    // Questions
    $questions = [];
    for ($i = 1; $i <= 11; $i++) {
        $questions["q$i"] = safe("q$i");
    }

    // Signature & Waivers
    $other_info          = safe('other_info');
    $waiver_print_name   = safe('waiver_print_name');
    $signature_data1     = $_POST['signature_data1'] ?? '';
    $signature_data2     = $_POST['signature_data2'] ?? '';
    $signature_date      = safe('signature_date');

    // Insert
    $stmt = $conn->prepare("
        INSERT INTO members (
            first_name, middle_name, surname, joined, paid_amount, paid_date, expiry_date,
            notes, phone, next_of_kin, relationship, next_of_kin_phone, payment_status,
            email, password, gender, dob, medical_condition, current_medication,
            permission, q1, q2, q3, q4, q5, q6, q7, q8, q9, q10, q11,
            other_info, waiver_print_name, signature_data1, signature_data2, signature_date,
            nfc_uid, photo, membership_type, banned, member_number, address
        ) VALUES (
            ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
        )
    ");

    $stmt->bind_param(
        "sssssssssssssssssssssssssssssssssssssssssi",
        $first_name, $middle_name, $surname, $joined, $paid_amount, $paid_date, $expiry_date,
        $notes, $phone, $next_of_kin, $relationship, $next_of_kin_phone, $payment_status,
        $email, $password, $gender, $dob, $medical_condition, $current_medication,
        $permission,
        $questions['q1'], $questions['q2'], $questions['q3'], $questions['q4'], $questions['q5'],
        $questions['q6'], $questions['q7'], $questions['q8'], $questions['q9'], $questions['q10'],
        $questions['q11'],
        $other_info, $waiver_print_name, $signature_data1, $signature_data2, $signature_date,
        $nfc_uid, $photo, $membership_type, $banned, $member_number, $address
    );

    if ($stmt->execute()) {
        $success = true;
    } else {
        $errors[] = "Database error: " . $stmt->error;
    }

    $stmt->close();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sunny-Side Gym – New Member</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="icon" href="admin/includes/logo.png" type="image/png">
<style>
/*  ───── visual style (unchanged) ───── */
body{background:#fac13a;font-family:system-ui,-apple-system,'Segoe UI',sans-serif;padding:1rem;margin:0}
form.wizard-card{max-width:780px;margin:auto;background:#fff;padding:2.4rem 2.2rem;border-radius:16px;
  box-shadow:0 6px 18px rgba(0,0,0,.15)}
.wizard-step h5{font-size:1.6rem;text-align:center;margin-bottom:1.4rem;font-weight:600;color:#333}
input.form-control,textarea.form-control{    font-size: 25px !important;
padding:.85rem 1rem;font-size:1.1rem;border-radius:10px;margin-bottom:1.1rem}
.signature-pad{border:2px solid #888;width:100%;height:240px;touch-action:none;border-radius:10px;background:#f4f4f4}
.waiver-box {
    max-height: 310px;
    overflow-y: auto;
    border: 1px solid #ddd;
    padding: 15px;
    background: #f9f9f9;
    border-radius: 8px;
    font-size: 20px;
}.nextBtn,.prevBtn,button[type=submit]{font-size:1.15rem;padding:.8rem 2rem;border-radius:12px;min-width:160px;border:none;
  color:#fff;background:#391436;margin:.4rem}
.nextBtn:hover,.prevBtn:hover,button[type=submit]:hover{background:#391436}
@media (pointer:coarse){.signature-pad{height:260px}}

/* ─── Camera section tweaks ────────────────────────────── */

/* Wrap the video/canvas so we can centre it */
.camera-wrapper{
  display:flex;
  justify-content:center;
  align-items:center;
  flex-direction:column;
}

#camera,
#snapshot {
  width: 100%;
  max-width: 720px;
  aspect-ratio: 1 / 1;             /* Force 1:1 ratio */
  object-fit: cover;               /* Fill the square */
  border-radius: 12px;
  border: 3px solid #666;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.25);
  display: block;
  margin: auto;
}


/* Big thumb-friendly capture button */
#snapBtn{
  font-size:1.5rem;
  padding:1rem 2.5rem;
  border-radius:14px;
  background:#1a252f;
  color:#fff;
  border:none;
  letter-spacing:.5px;
  margin-top:1rem;
  transition:background .15s ease-in-out;
}
#snapBtn:hover{ background:#111b24 }
#snapBtn:disabled{opacity:.5}

/* Slightly narrow layouts */
@media (max-width:768px){
  #camera,#snapshot{max-width:100%}
  #snapBtn{font-size:1.3rem;padding:.9rem 2rem}
}

    .success-card {
      max-width: 96%;
      margin: auto;
       padding: 2rem;
      border-radius: 16px;
      text-align: center;
          height: 100vh;
    align-content: center;
     }
    .success-card .logo {
    max-width: 338px;
    margin-bottom: 1rem;
}


   .success-card h2 {
    font-size: 3rem;
    color: #2c3e50;
    margin-bottom: 2.5rem;
}
   .success-card p {
    font-size: 2.2rem;
    color: #333;
    margin-bottom: 2.5rem;
}
   .btn-register {
    background: #2c3e50;
    color: #fff;
    padding: 0.75rem 1.5rem;
    border-radius: 8px;
    text-decoration: none;
    font-size: 2rem;
}
    .btn-register:hover {
      background: #1a252f;
    }
    .form-label {
    margin-bottom: .5rem;
    font-size: 25px;
}
label
  {
     font-size: 25px;
}
.success-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}
.form-wrapper {
    width: 95%;
}
button#startBtn

 {
    font-size: 34px;
    margin-top: 16px;
}
h2.mb-4.rtext
  {
    font-size: 45px;
}
  </style>
</head>
<body><div class="success-wrapper">

<?php if (!$success): ?>
<div id="startScreen" class="text-center">
  <img src="logo.png" alt="Sunny-Side Gym Logo" style="max-width: 500px; margin-bottom: 2rem;">
  <h2 class="mb-4 rtext">Ready to Sign Up?</h2>
  <button id="startBtn" class="btn btn-dark btn-lg">Start Registration</button>
</div>

<div id="registrationFormWrapper" class="form-wrapper" style="display: none;">
 
<h3 class="text-center mb-4 fw-bold">New Member Registration</h3>

  <form id="regForm" method="post" enctype="multipart/form-data">
  <input type="hidden" name="member_number" value="<?= $nextNo ?>">

  <!-- STEP 1 -->
  <div class="wizard-step active" data-step="1">
    <h5>Step 1 / 7 – Member Details</h5>
<div class="row">
  <div class="col-md-6 mb-3">
    <label class="form-label">First Name *</label>
    <input name="first_name" class="form-control required">
  </div>
  <div class="col-md-6 mb-3">
    <label class="form-label">Surname *</label>
    <input name="surname" class="form-control required">
  </div>
</div>


    <div class="mb-3"><label class="form-label">Phone</label><input name="phone" class="form-control"></div>
    <div class="mb-3"><label class="form-label">Email *</label><input type="email" name="email" class="form-control required"></div>
    <div class="mb-3"><label class="form-label">Address</label><textarea name="address" rows="2" class="form-control"></textarea></div>

    <div class="mb-3"><label class="form-label d-block">Do you identify as</label>
      <label class="form-check form-check-inline"><input class="form-check-input" type="radio" name="gender" value="Male"> Male</label>
      <label class="form-check form-check-inline"><input class="form-check-input" type="radio" name="gender" value="Female"> Female</label>
    </div>
    <div class="mb-4"><label class="form-label">Date of Birth</label><input type="date" name="dob" class="form-control"></div>
    <div class="text-end"><button type="button" class="nextBtn btn btn-primary">Next →</button></div>
  </div>

  <!-- STEP 2 -->
  <div class="wizard-step" data-step="2">
    <h5>Step 2 / 7 – Next of Kin</h5>
    <div class="mb-3"><label class="form-label">Name *</label><input name="next_of_kin" class="form-control required"></div>
    <div class="mb-3"><label class="form-label">Relationship *</label><input name="relationship" class="form-control required"></div>
    <div class="mb-3"><label class="form-label">Contact No. *</label><input name="kin_contact" class="form-control required"></div>

    <div class="mb-3"><label class="form-label d-block">I give permission for Sunny-Side Gym to contact me with the details you provided?
</label>
      <label class="form-check form-check-inline"><input class="form-check-input required-radio" type="radio" name="permission" value="Yes"> Yes</label>
      <label class="form-check form-check-inline"><input class="form-check-input required-radio" type="radio" name="permission" value="No"> No</label>
    </div>

    <div class="d-flex justify-content-between">
      <button type="button" class="prevBtn btn btn-secondary">← Back</button>
      <button type="button" class="nextBtn btn btn-primary">Next →</button>
    </div>
  </div>

  <!-- STEP 3 -->
  <div class="wizard-step" data-step="3">
    <h5>Step 3 / 7 – Medical &amp; Questions 1-6</h5>
    <div class="mb-3"><label class="form-label">Any medical condition</label><input name="medical_condition" class="form-control"></div>
    <div class="mb-4"><label class="form-label">Current medication</label><textarea name="current_medication" rows="2" class="form-control"></textarea></div>

<?php
$qTxt=[
1=>"Do you lose your balance because of dizziness, or do you ever lose consciousness?",
2=>"Has your doctor ever said you have a heart condition and should only do physical activity recommended by a doctor?",
3=>"Do you feel pain in your chest when you do physical activity?",
4=>"Are you being treated for high blood pressure?",
5=>"Do you have diabetes?",
6=>"Do you have asthma or any other respiratory problems?"
];
foreach($qTxt as $n=>$txt){ echo
"<div class='mb-3'><label class='form-label'>$txt</label><br>
 <label class='form-check form-check-inline'><input class='form-check-input required-radio' type='radio' name='q$n' value='Yes'> Yes</label>
 <label class='form-check form-check-inline'><input class='form-check-input required-radio' type='radio' name='q$n' value='No'> No</label></div>";
}
?>
    <div class="d-flex justify-content-between">
      <button type="button" class="prevBtn btn btn-secondary">← Back</button>
      <button type="button" class="nextBtn btn btn-primary">Next →</button>
    </div>
  </div>

  <!-- STEP 4 -->
  <div class="wizard-step" data-step="4">
    <h5>Step 4 / 7 – Questions 7-11</h5>
<?php
$qTxt2=[
7=>"Do you have any bone or joint problems that could be made worse by a change in your physical activity?",
8=>"Do you have epilepsy?",
9=>"Do you have a pacemaker?",
10=>"Are you pregnant?",
11=>"Do you know any other reasons you should not engage in physical activity?"
];
foreach($qTxt2 as $n=>$txt){ echo
"<div class='mb-3'><label class='form-label'>$txt</label><br>
 <label class='form-check form-check-inline'><input class='form-check-input required-radio' type='radio' name='q$n' value='Yes'> Yes</label>
 <label class='form-check form-check-inline'><input class='form-check-input required-radio' type='radio' name='q$n' value='No'> No</label></div>";
}
?>
    <div class="mb-4"><label class="form-label">If yes to any, give details</label><textarea name="other_info" rows="3" class="form-control"></textarea></div>

    <div class="d-flex justify-content-between">
      <button type="button" class="prevBtn btn btn-secondary">← Back</button>
      <button type="button" class="nextBtn btn btn-primary">Next →</button>
    </div>
  </div>

  <!-- STEP 5 -->
  <div class="wizard-step" data-step="5">
    <h5>Step 5 / 7 – Waiver &amp; Assumption of Risk</h5>
    <div class="waiver-box mb-3">
     <p><strong>Waiver Issued by: Sunny-Side Gym Ltd, 7/9 Springfield Street Morecambe LA44HA</strong></p>
      <p>By submitting an order, (online or by other means), making an authorisation payment or by using any services supplied by Sunny-Side Gym Ltd trading as Sunny-Side Gym, the Customer agrees to Sunny-Side Gym Ltd Terms of Service (TOS) and Privacy Policy.</p>
      <p><strong>Express assumption of risk:</strong></p>
      <p>I, the undersigned, am aware that there are significant risks involved in any physical training regimen. These risks include but are not limited to: falls which can result in serious injury or death; injury or death due to negligence on the part of myself, my training partner, or other people around me, injury or death due to improper use or failure of equipment. Injury may also result simply from the fact of physical training itself.</p>
      <p>By its very nature, physical training seeks to have me push beyond my physical and mental limits in order to produce a physical adaptation by my body. Excessive work can result (in rare cases) in exertional rhabdomyolysis. I should look for signs of excessive soreness, darkened urine, and pain in the kidney areas in the days following a particularly intense workout. While this type of injury is rare, it can occur due to a number of factors, including (but not limited to) genetic predisposition, medication, or other factors that are beyond the control of my trainer. I am aware that any of these above mentioned risks may result in serious injury or death to myself and or my partner(s).</p>
      <p>I willingly assume full responsibility for the risks that I am exposing myself to and accept full responsibility for any injury or death that may result from participation in any activity or class while training at or with Sunny-Side Gym Ltd.</p>
    </div>
    <div class="mb-3">
      <label class="form-label">Print Name *</label><input name="waiver_print_name" class="form-control required">
    </div>
    <div class="mb-4">
      <label class="form-label d-block">Signature *</label>
      <canvas id="signature-pad1" class="signature-pad"></canvas>
      <input type="hidden" name="signature_data1" id="signature_data1">
      <button type="button" class="btn btn-link p-0" id="clear1">Clear</button>
    </div>
    <div class="d-flex justify-content-between">
      <button type="button" class="prevBtn btn btn-secondary">← Back</button>
      <button type="button" class="nextBtn btn btn-primary">Next →</button>
    </div>
  </div>

  <!-- STEP 6 -->
  <div class="wizard-step" data-step="6">
    <h5>Step 6 / 7 – Release of Liability &amp; Indemnification</h5>
    <div class="waiver-box mb-3">
     <p>I, the undersigned, acknowledge that I have no physical condition, illness, or impairment that I know of that will endanger myself or others.</p>
      <p><strong>Release of liability:</strong></p>
      <p>In consideration of the above mentioned risks and hazards and in consideration of the fact that I am willingly and voluntarily participating in the activities available at Sunny-Side Gym ltd, I, the undersigned hereby release Sunny-Side Gym Ltd, Inc., its officers and directors, and Sunny-Side Gym Ltd their principals, agents, employees, and volunteers from any and all liability, claims, demands, actions or rights of action, which are related to, arise out of, or are in any way connected with my participation in this activity, including those allegedly attributed to the negligent acts or omissions of the above mentioned parties.</p>
      <p>I affirm that I have stated all my known medical conditions and answered all questions honestly. I agree to keep Sunny-Side Gym ltd updated as to any changes in my medical profile and understand that there is no liability on Sunny-Side Gym Ltd part should I fail to do so.</p>
      <p>This agreement shall be binding upon me, my successors, representatives, heirs, executors, assigns, or transferees. If any portion of this agreement is held invalid, I agree that the remainder of the agreement shall remain in full legal force and effect.</p>
      <p><strong>Indemnification:</strong></p>
      <p>The participant recognizes that there is risk involved in the types of activities offered by Sunny-Side Gym Ltd. Therefore, the participant accepts financial responsibility for any injury that the participant may cause either to him/herself or to any other participant due to his/her negligence. Should the above-mentioned parties, or anyone acting on their behalf, be required to incur attorney’s fees and costs to enforce this agreement, I agree to reimburse them for such fees and costs. I further agree to indemnify and hold harmless Sunny-Side Gym Ltd, their principals, agents, employees, and volunteers from liability for the injury or death of any person(s) and damage to property that may result from my negligent or intentional act or omission while participating in activities offered by Sunny-Side Gym Ltd.</p>
    </div>
    <div class="mb-3"><label class="form-label">Date *</label><input type="date" name="signature_date" class="form-control required"></div>
    <div class="mb-4">
      <label class="form-label d-block">Signature *</label>
      <canvas id="signature-pad2" class="signature-pad"></canvas>
      <input type="hidden" name="signature_data2" id="signature_data2">
      <button type="button" class="btn btn-link p-0" id="clear2">Clear</button>
    </div>
    <div class="d-flex justify-content-between">
      <button type="button" class="prevBtn btn btn-secondary">← Back</button>
      <button type="button" class="nextBtn btn btn-primary">Next →</button>
    </div>
  </div>

<!-- ───────── STEP 7 ───────── -->
<div class="wizard-step" data-step="7">
  <h5>Step 7 / 7 – Photo &amp; Finish</h5>

  <div class="camera-wrapper">      <!--  ← add this -->
<video id="camera" autoplay playsinline muted class="w-100 d-block" ></video>
    <canvas  id="snapshot" class="d-none mb-2"></canvas>
    <button  type="button" id="snapBtn">📸 Capture / Retake</button>
  </div>                            <!--  ← and close here -->

<input type="hidden" name="photo_capture" id="photoCap" required>
  <div class="d-flex justify-content-between mt-4">
      <button type="button" class="btn btn-secondary prevBtn">← Back</button>
      <button type="submit" class="btn btn-success px-4">Submit</button>
  </div>
</div>

</form>
</div>
</div>

<?php endif; ?>

<?php if ($success): ?>
 

  <div class="success-card">
    <img src="logo.png" alt="Sunny-Side Gym Logo" class="logo">
    <h2>Thank you!</h2>
    <p>Registration complete. Please speak to a staff member about membership packages.</p>
<a href="#" class="btn-register">← Back to Registration</a>
  </div>


  <?php exit; // Stop form from rendering again ?>
<?php elseif (!empty($errors)): ?>
  <div class="alert alert-danger text-center">
    <strong>Error:</strong><br>
    <?php foreach ($errors as $e) echo htmlspecialchars($e) . "<br>"; ?>
  </div>
<?php endif; ?>
</div>
<!-- JS libs -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/signature_pad@4.1.6/dist/signature_pad.umd.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', () => {

  /* ──────────────────────────── WIZARD ──────────────────────────── */
  initWizard();
  initStartButton();

  function initWizard() {
    const form   = document.getElementById('regForm');
    const steps  = [...document.querySelectorAll('.wizard-step')];
    let   cur    = 0;

    /* signatures */
    const pad1 = new SignaturePad(document.getElementById('signature-pad1'));
    const pad2 = new SignaturePad(document.getElementById('signature-pad2'));

    /* camera */
    const cam        = document.getElementById('camera');
    const snapCv     = document.getElementById('snapshot');
    const snapBtn    = document.getElementById('snapBtn');
    const photoField = document.getElementById('photoCap');

    let stream        = null;
    let cameraStarted = false;

    /* ─── webcam helpers ─── */
    function startCamera() {
      if (cameraStarted || !navigator.mediaDevices?.getUserMedia) return;
      navigator.mediaDevices
        .getUserMedia({
          video: { facingMode: 'user', width: { ideal: 640 }, height: { ideal: 640 } }
        })
        .then(s => {
          stream = s;
          cam.srcObject = s;
          cam.play();
          cameraStarted = true;
        })
        .catch(err => {
          console.error('Camera error:', err);
          snapBtn.disabled = true;
          alert('Camera access blocked or unavailable.');
        });
    }
    function stopCamera() {
      if (stream) {
        stream.getTracks().forEach(t => t.stop());
        stream = null;
      }
      cam.srcObject  = null;
      cameraStarted  = false;
    }

    /* DPR‑aware canvas resize */
    function resizeSigCanvas(cnv) {
      const ratio = Math.max(window.devicePixelRatio || 1, 1);
      const box   = cnv.getBoundingClientRect();
      cnv.width   = box.width  * ratio;
      cnv.height  = box.height * ratio;
      cnv.getContext('2d').scale(ratio, ratio);
    }

    /* show/hide steps */
    function showStep(i) {
      steps.forEach((s, idx) => (s.style.display = idx === i ? 'block' : 'none'));
      window.scrollTo(0, 0);
      cur = i;

      if (steps[i].contains(pad1.canvas)) resizeSigCanvas(pad1.canvas);
      if (steps[i].contains(pad2.canvas)) resizeSigCanvas(pad2.canvas);

      if (steps[i].contains(cam)) startCamera();
      else                        stopCamera();
    }
    showStep(cur);

    /* next / prev */
    document.querySelectorAll('.nextBtn').forEach(btn =>
      btn.addEventListener('click', e => {
        e.preventDefault();
        if (validateStep() && cur < steps.length - 1) showStep(cur + 1);
      })
    );
    document.querySelectorAll('.prevBtn').forEach(btn =>
      btn.addEventListener('click', e => {
        e.preventDefault();
        if (cur > 0) showStep(cur - 1);
      })
    );

    /* snapshot / retake */
    snapBtn.addEventListener('click', () => {
      if (cam.classList.contains('d-none')) {
        /* retake */
        cam.classList.remove('d-none');
        snapCv.classList.add('d-none');
        photoField.value   = '';
        snapBtn.textContent = '📸 Capture / Retake';
        startCamera();
        return;
      }

      /* capture → crop centre → scale to 480 px */
      const crop   = Math.min(cam.videoWidth, cam.videoHeight);
      const target = 480;
      snapCv.width  = target;
      snapCv.height = target;
      snapCv.getContext('2d').drawImage(
        cam,
        (cam.videoWidth  - crop) / 2,
        (cam.videoHeight - crop) / 2,
        crop, crop,
        0, 0,
        target, target
      );

      cam.classList.add('d-none');
      snapCv.classList.remove('d-none');
      photoField.value   = snapCv.toDataURL('image/jpeg', 0.7);   /* ≈150 kB */
      snapBtn.textContent = 'Retake';
      stopCamera();
    });

    /* validation */
    function validateStep() {
      const step = steps[cur];

      for (const el of step.querySelectorAll('.required')) {
        if (!el.value.trim()) { el.focus(); return false; }
      }
      const radios = {};
      step.querySelectorAll('.required-radio').forEach(r =>
        (radios[r.name] = radios[r.name] || []).push(r)
      );
      for (const name in radios) {
        if (!radios[name].some(r => r.checked)) {
          radios[name][0].scrollIntoView({ behavior: 'smooth' });
          return false;
        }
      }
      if (step.contains(pad1.canvas) && pad1.isEmpty()) { alert('Please sign the first waiver');  return false; }
      if (step.contains(pad2.canvas) && pad2.isEmpty()) { alert('Please sign the second waiver'); return false; }

      return true;
    }

    /* submit */
    form.addEventListener('submit', e => {
      e.preventDefault();

      if (!photoField.value) { alert('Please capture a photo before submitting'); return; }
      if (!pad1.isEmpty()) document.getElementById('signature_data1').value = pad1.toDataURL();
      if (!pad2.isEmpty()) document.getElementById('signature_data2').value = pad2.toDataURL();
      stopCamera();

      fetch('', { method: 'POST', body: new FormData(form) })
        .then(res => res.text())
        .then(html => {
          const doc     = new DOMParser().parseFromString(html, 'text/html');
          const success = doc.querySelector('.success-card');

          if (success) {
            document.body.innerHTML = '';
            document.body.appendChild(success);
            document.documentElement.requestFullscreen?.();
            document.body.addEventListener('click', ev => {
              if (ev.target.closest('.btn-register')) {
                ev.preventDefault();
                window.location.reload(true);   /* fresh page, new member number */
              }
            });
          } else {
            document.body.innerHTML = html;     /* show server‑side errors */
          }
        })
        .catch(err => alert('Something went wrong: ' + err));
    });

    resizeSigCanvas(pad1.canvas);
  }

  /* ─────────────────────────── Start screen ─────────────────────────── */
  function initStartButton() {
    const startBtn   = document.getElementById('startBtn');
    const startScr   = document.getElementById('startScreen');
    const regWrapper = document.getElementById('registrationFormWrapper');

    if (startBtn && startScr && regWrapper) {
      startBtn.addEventListener('click', () => {
        startScr.style.display = 'none';
        regWrapper.style.display = 'block';
        document.documentElement.requestFullscreen?.();
      });
    }
  }
});
</script>



<!-- drop this *after* the previous <script> so it adds the webcam logic -->
<script src="https://cdn.jsdelivr.net/npm/signature_pad@4.1.6/dist/signature_pad.umd.min.js"></script>

</body>
</html>
