<?php
require_once __DIR__ . '/includes/auth.php';
require_once __DIR__ . '/includes/cwsn_validate.php';
requireLogin();

$pdo = getPDO();
$role = currentRole();
$clrccode = currentClrcCode();

$id = $_GET['id'] ?? null;
$isEdit = !!$id;
$record = null;

if ($isEdit) {
    $stmt = $pdo->prepare('SELECT * FROM cwsn WHERE cwsn_code = ?');
    $stmt->execute([$id]);
    $record = $stmt->fetch();
    if (!$record) { header('Location: cwsn_list.php'); exit; }
    if ($role === 'clrc' && $record['clrccode'] !== $clrccode) { header('Location: cwsn_list.php'); exit; }
}

// Small master lists — embedded directly as JSON so the wizard doesn't need
// an AJAX round trip for every field (school/AWC/IFSC are still AJAX-backed
// via api/search.php since those are too large to embed).
$clrcs = $pdo->query('SELECT clrccode, clrcname FROM clrc ORDER BY clrcname')->fetchAll();
$clusters = $pdo->query('SELECT clucd, cluname, clrccode FROM cluster ORDER BY cluname')->fetchAll();
$disabilities = $pdo->query('SELECT disability_id, disability_name FROM disability ORDER BY disability_name')->fetchAll();
$appliances = $pdo->query("SELECT appliance_id, appliance_name FROM appliance WHERE status='1' ORDER BY appliance_name")->fetchAll();
$banks = $pdo->query("SELECT bank_id, bank_name FROM bank WHERE status='1' ORDER BY bank_name")->fetchAll();
$spledus = $pdo->query("SELECT regno, spl_edu_name FROM spledu WHERE status='1' ORDER BY spl_edu_name")->fetchAll();
$classes = $pdo->query('SELECT schcat_id, sclass FROM class ORDER BY id')->fetchAll();

$formData = $record ?: [
    'cwsn_code' => '', 'clrccode' => ($role === 'clrc' ? $clrccode : ''), 'clucd' => '',
    'cwsn_name' => '', 'dob' => '', 'gender' => '', 'cwsn_f_name' => '', 'cwsn_m_name' => '',
    'aadhaar' => '', 'add1' => '', 'add2' => '', 'add3' => '', 'pin' => '', 'contact_no' => '',
    'disability_id' => '', 'dis_certi_yn' => '', 'dis_certi_valid_yn' => '', 'appliance_id' => '',
    'therapy_reqd_yn' => '', 'therapy_provide_yn' => '', 'legalgurdian' => '', 'manabik_yn' => '',
    'in_school_yn' => '', 'school_awc' => '', 'schcd' => '', 'awc_no' => '', 'class' => '',
    'acno' => '', 'ac_holder' => '', 'bank_id' => '', 'branch_name' => '', 'micr' => '', 'ifsc' => '',
    'spledu_reg_no' => '', 'date_of_entry' => '', 'pen' => '', 'status' => '',
];
$currentSchoolName = '';
$currentSchcat = '';
if (!empty($formData['schcd'])) {
    $s = $pdo->prepare('SELECT schname, schcat_id FROM school WHERE schcd = ?');
    $s->execute([$formData['schcd']]);
    if ($row = $s->fetch()) { $currentSchoolName = $row['schname']; $currentSchcat = $row['schcat_id']; }
}
$currentAwcName = '';
if (!empty($formData['awc_no'])) {
    $s = $pdo->prepare('SELECT awc_name FROM awc WHERE awc_no = ?');
    $s->execute([$formData['awc_no']]);
    if ($row = $s->fetch()) $currentAwcName = $row['awc_name'];
}

$pageTitle = $isEdit ? 'Edit CWSN Record' : 'Add CWSN Record';
require __DIR__ . '/includes/header.php';
?>
<style>
  .field-label{display:block;font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.03em;color:#64748b;margin-bottom:.3rem}
  .field-hint{font-size:.72rem;color:#94a3b8;margin-top:.25rem}
  .field-error{font-size:.72rem;color:#e11d48;margin-top:.25rem;font-weight:600}
  .field-input.error, .field-select.error{border-color:#fb7185;box-shadow:0 0 0 1px #fda4af}
  .wizard-step{display:none}
  .wizard-step.active{display:block}
  .step-grid{display:grid;grid-template-columns:1fr;gap:1rem}
  @media(min-width:640px){.step-grid{grid-template-columns:1fr 1fr}}
  @media(min-width:1024px){.step-grid{grid-template-columns:1fr 1fr 1fr}}
  .stepper{display:flex;align-items:center;overflow-x:auto;gap:.25rem}
  .step-dot{width:2rem;height:2rem;border-radius:9999px;display:flex;align-items:center;justify-content:center;font-size:.8rem;font-weight:700;cursor:pointer;flex-shrink:0}
  .step-dot.pending{background:#f1f5f9;color:#94a3b8}
  .step-dot.complete{background:#d1fae5;color:#047857}
  .step-dot.current{background:#2563eb;color:#fff}
  .step-label{font-size:.68rem;font-weight:600;color:#64748b;text-align:center;max-width:6rem}
  .step-label.current{color:#1d4ed8}
  .step-line{flex:1;height:2px;background:#e2e8f0;margin:0 .4rem;min-width:1rem}
  .step-line.complete{background:#a7f3d0}
  .searchable{position:relative}
  .searchable-results{position:absolute;z-index:30;top:100%;left:0;right:0;background:#fff;border:1px solid #e2e8f0;border-radius:.5rem;box-shadow:0 8px 24px rgba(15,23,42,.15);max-height:14rem;overflow-y:auto;margin-top:.25rem;display:none}
  .searchable-results.open{display:block}
  .searchable-item{padding:.5rem .75rem;font-size:.85rem;cursor:pointer}
  .searchable-item:hover{background:#eff6ff}
  .searchable-item .sub{font-size:.7rem;color:#94a3b8}
  .badge{display:inline-flex;align-items:center;border-radius:9999px;padding:.15rem .6rem;font-size:.72rem;font-weight:600}
  .badge-green{background:#d1fae5;color:#047857}
  .badge-rose{background:#ffe4e6;color:#be123c}
  .badge-amber{background:#fef3c7;color:#b45309}
  .udise-panel{background:#f0fdfa;border:1px solid #99f6e4;border-radius:.75rem;padding:1rem}
  #reviewArea .review-row{padding:.15rem 0;font-size:.85rem}
  #reviewArea .review-label{font-weight:600;color:#334155}
  @media print {
    body * { visibility:hidden; }
    #printArea, #printArea * { visibility:visible; }
    #printArea { position:absolute; left:0; top:0; width:100%; }
  }
  .print-form{font-family:Georgia,serif;font-size:11px;line-height:1.5;color:#000}
  .print-form-header{text-align:center;border-bottom:1.5px solid #000;padding-bottom:6px;margin-bottom:8px}
  .print-form-title{font-size:14px;font-weight:700}
  .print-form-section-title{font-weight:700;text-transform:uppercase;border-bottom:.75px solid #000;margin-top:8px;padding-bottom:2px}
  .print-form-value{display:inline-block;min-width:220px;text-decoration:underline;padding:0 4px}
</style>

<div class="max-w-5xl mx-auto space-y-4" id="wizardRoot"
     data-edit="<?= $isEdit ? '1' : '0' ?>" data-code="<?= htmlspecialchars($formData['cwsn_code']) ?>"
     data-role="<?= htmlspecialchars($role) ?>" data-clrccode="<?= htmlspecialchars($clrccode ?? '') ?>">

  <div class="flex items-start justify-between gap-3">
    <div class="flex items-center gap-3">
      <a href="cwsn_list.php" class="text-slate-400 hover:text-slate-600">&larr;</a>
      <div>
        <h1 class="text-lg font-bold text-slate-800"><?= $isEdit ? 'Edit CWSN Record' : 'Add CWSN Record' ?></h1>
        <p class="text-sm text-slate-500">Step <span id="stepNumLabel">1</span> of 7 · Fields marked * are needed to mark this record complete.</p>
      </div>
    </div>
    <span id="statusBadge">
      <?php if ($isEdit): ?>
        <?= $formData['status'] === '2' ? '<span class="badge badge-amber">Incomplete</span>' : ($formData['status'] === '1' ? '<span class="badge badge-rose">Deleted</span>' : '<span class="badge badge-green">Complete</span>') ?>
      <?php endif; ?>
    </span>
  </div>

  <div class="card p-4">
    <div class="stepper" id="stepper"></div>
  </div>

  <div id="formError" class="hidden rounded-lg bg-rose-50 border border-rose-200 px-4 py-3 text-sm text-rose-700"></div>
  <div id="formSuccess" class="hidden rounded-lg border px-4 py-3 text-sm"></div>

  <div class="wizard-step card p-5" data-step="0">
    <h2 class="text-sm font-bold text-slate-700 uppercase tracking-wide mb-4">Location &amp; Identity</h2>
    <div class="step-grid">
      <div>
        <label class="field-label">CLRC *</label>
        <select id="f_clrccode" class="field-select" <?= $role === 'clrc' ? 'disabled' : '' ?>>
          <option value="">Select CLRC</option>
          <?php foreach ($clrcs as $c): ?>
            <option value="<?= htmlspecialchars($c['clrccode']) ?>" <?= $formData['clrccode'] === $c['clrccode'] ? 'selected' : '' ?>><?= htmlspecialchars($c['clrcname']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div>
        <label class="field-label">School / Cluster *</label>
        <select id="f_clucd" class="field-select"></select>
        <div class="field-error hidden" data-err="clucd"></div>
      </div>
    </div>
  </div>

  <div class="wizard-step card p-5" data-step="1">
    <h2 class="text-sm font-bold text-slate-700 uppercase tracking-wide mb-4">Personal Details</h2>
    <div class="step-grid">
      <div><label class="field-label">CWSN Name *</label><input id="f_cwsn_name" maxlength="75" class="field-input"><div class="field-error hidden" data-err="cwsn_name"></div></div>
      <div><label class="field-label">Date of Birth *</label><input type="date" id="f_dob" class="field-input"><div class="field-hint">Age must be between 2 and 30 years.</div><div class="field-error hidden" data-err="dob"></div></div>
      <div><label class="field-label">Gender *</label>
        <select id="f_gender" class="field-select"><option value="">-- Select --</option><option value="BOY">Boy</option><option value="GIRL">Girl</option><option value="TRANSGENDER">Transgender</option></select>
        <div class="field-error hidden" data-err="gender"></div>
      </div>
      <div><label class="field-label">Father's Name *</label><input id="f_cwsn_f_name" maxlength="75" class="field-input"><div class="field-error hidden" data-err="cwsn_f_name"></div></div>
      <div><label class="field-label">Mother's Name *</label><input id="f_cwsn_m_name" maxlength="75" class="field-input"><div class="field-error hidden" data-err="cwsn_m_name"></div></div>
      <div><label class="field-label">Legal Guardian (optional)</label><input id="f_legalgurdian" class="field-input"></div>
      <div>
        <label class="field-label">Aadhaar Number (optional)</label>
        <input id="f_aadhaar_display" class="field-input" autocomplete="off">
        <input type="hidden" id="f_aadhaar">
        <div class="field-hint">Only the last 4 digits are ever shown, including while typing.</div>
        <div class="field-error hidden" data-err="aadhaar"></div>
      </div>
      <div><label class="field-label">Contact Number *</label><input id="f_contact_no" maxlength="10" inputmode="numeric" class="field-input" placeholder="10-digit mobile number"><div class="field-error hidden" data-err="contact_no"></div></div>
      <div><label class="field-label">Manabik Registered? *</label>
        <select id="f_manabik_yn" class="field-select"><option value="">-- Select Yes / No --</option><option value="YES">YES</option><option value="NO">NO</option></select>
        <div class="field-error hidden" data-err="manabik_yn"></div>
      </div>
    </div>

    <div class="udise-panel mt-4">
      <div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <div class="text-sm font-bold text-teal-900">UDISE+ Match Check</div>
          <div class="text-xs text-teal-700">Cheap, targeted check — uses Aadhaar first, then Name + Father's + Mother's Name + DOB.</div>
        </div>
        <button type="button" id="btnUdiseCheck" class="btn btn-secondary" style="border-color:#0d9488;color:#0f766e">Check UDISE+ Match</button>
      </div>
      <div id="udiseResult" class="mt-3"></div>
    </div>
  </div>

  <div class="wizard-step card p-5" data-step="2">
    <h2 class="text-sm font-bold text-slate-700 uppercase tracking-wide mb-4">Address</h2>
    <div class="step-grid">
      <div><label class="field-label">Address Line 1 *</label><input id="f_add1" maxlength="100" class="field-input" placeholder="Habitation / locality / village / road"><div class="field-error hidden" data-err="add1"></div></div>
      <div><label class="field-label">Address Line 2 *</label><input id="f_add2" maxlength="100" class="field-input" placeholder="Post Office"><div class="field-error hidden" data-err="add2"></div></div>
      <div><label class="field-label">Address Line 3 *</label><input id="f_add3" maxlength="60" class="field-input" placeholder="Thana"><div class="field-error hidden" data-err="add3"></div></div>
      <div><label class="field-label">PIN Code *</label><input id="f_pin" maxlength="6" inputmode="numeric" class="field-input"><div class="field-error hidden" data-err="pin"></div></div>
    </div>
  </div>

  <div class="wizard-step card p-5" data-step="3">
    <h2 class="text-sm font-bold text-slate-700 uppercase tracking-wide mb-4">Disability &amp; Support</h2>
    <div class="step-grid">
      <div><label class="field-label">Disability Type *</label>
        <select id="f_disability_id" class="field-select"><option value="">Select disability</option>
          <?php foreach ($disabilities as $d): ?><option value="<?= htmlspecialchars($d['disability_id']) ?>"><?= htmlspecialchars($d['disability_name']) ?></option><?php endforeach; ?>
        </select>
        <div class="field-error hidden" data-err="disability_id"></div>
      </div>
      <div><label class="field-label">Disability Certificate? *</label>
        <select id="f_dis_certi_yn" class="field-select"><option value="">-- Select Yes / No --</option><option value="YES">YES</option><option value="NO">NO</option></select>
        <div class="field-error hidden" data-err="dis_certi_yn"></div>
      </div>
      <div id="wrap_dis_certi_valid_yn" class="hidden"><label class="field-label">Certificate Valid? *</label>
        <select id="f_dis_certi_valid_yn" class="field-select"><option value="">-- Select Yes / No --</option><option value="YES">YES</option><option value="NO">NO</option></select>
        <div class="field-error hidden" data-err="dis_certi_valid_yn"></div>
      </div>
      <div><label class="field-label">Assistive Appliance (optional)</label>
        <select id="f_appliance_id" class="field-select"><option value="">None / not required</option>
          <?php foreach ($appliances as $a): ?><option value="<?= htmlspecialchars($a['appliance_id']) ?>"><?= htmlspecialchars($a['appliance_name']) ?></option><?php endforeach; ?>
        </select>
      </div>
      <div><label class="field-label">Therapy Required? *</label>
        <select id="f_therapy_reqd_yn" class="field-select"><option value="">-- Select Yes / No --</option><option value="YES">YES</option><option value="NO">NO</option></select>
        <div class="field-error hidden" data-err="therapy_reqd_yn"></div>
      </div>
      <div id="wrap_therapy_provide_yn" class="hidden"><label class="field-label">Therapy Provided? *</label>
        <select id="f_therapy_provide_yn" class="field-select"><option value="">-- Select Yes / No --</option><option value="YES">YES</option><option value="NO">NO</option></select>
        <div class="field-error hidden" data-err="therapy_provide_yn"></div>
      </div>
      <div><label class="field-label">Special Educator (optional)</label>
        <select id="f_spledu_reg_no" class="field-select"><option value="">Not assigned</option>
          <?php foreach ($spledus as $s): ?><option value="<?= htmlspecialchars($s['regno']) ?>"><?= htmlspecialchars($s['spl_edu_name']) ?> (<?= htmlspecialchars($s['regno']) ?>)</option><?php endforeach; ?>
        </select>
      </div>
    </div>
  </div>

  <div class="wizard-step card p-5" data-step="4">
    <h2 class="text-sm font-bold text-slate-700 uppercase tracking-wide mb-4">Education Status</h2>
    <div class="step-grid">
      <div><label class="field-label">Currently Enrolled? *</label>
        <select id="f_in_school_yn" class="field-select"><option value="">-- Select Yes / No --</option><option value="YES">YES</option><option value="NO">NO</option></select>
        <div class="field-error hidden" data-err="in_school_yn"></div>
      </div>
      <div id="wrap_school_awc" class="hidden"><label class="field-label">Enrolled at School or AWC *</label>
        <select id="f_school_awc" class="field-select"><option value="">-- Select --</option><option value="SCHOOL">School</option><option value="AWC">Anganwadi Centre (AWC)</option></select>
        <div class="field-error hidden" data-err="school_awc"></div>
      </div>
      <div id="wrap_school_fields" class="hidden contents">
        <div><label class="field-label">School (UDISE) *</label>
          <div class="searchable">
            <input id="f_schcd_display" class="field-input" placeholder="Search school by name or UDISE code..." autocomplete="off">
            <input type="hidden" id="f_schcd"><input type="hidden" id="f_schcat_id">
            <div class="searchable-results" id="schoolResults"></div>
          </div>
          <div class="field-error hidden" data-err="schcd"></div>
        </div>
        <div><label class="field-label">Class *</label>
          <select id="f_class" class="field-select"><option value="">Select a school first</option></select>
          <div class="field-error hidden" data-err="class"></div>
        </div>
      </div>
      <div id="wrap_awc_field" class="hidden"><label class="field-label">AWC *</label>
        <div class="searchable">
          <input id="f_awc_no_display" class="field-input" placeholder="Search AWC by name or number..." autocomplete="off">
          <input type="hidden" id="f_awc_no">
          <div class="searchable-results" id="awcResults"></div>
        </div>
        <div class="field-error hidden" data-err="awc_no"></div>
      </div>
      <div><label class="field-label">Date of Entry (optional)</label><input type="date" id="f_date_of_entry" class="field-input"></div>
      <div><label class="field-label">PEN (optional)</label><input id="f_pen" class="field-input"><div class="field-hint">Can also be pulled in from UDISE+ Match Check.</div></div>
    </div>
  </div>

  <div class="wizard-step card p-5" data-step="5">
    <h2 class="text-sm font-bold text-slate-700 uppercase tracking-wide mb-4">Bank Details (for benefit transfer)</h2>
    <div class="step-grid">
      <div><label class="field-label">IFSC Code (optional)</label>
        <div class="searchable">
          <input id="f_ifsc_display" class="field-input" placeholder="Search / type IFSC..." autocomplete="off">
          <input type="hidden" id="f_ifsc">
          <div class="searchable-results" id="ifscResults"></div>
        </div>
        <div class="field-hint">Bank and branch details fill in automatically.</div>
        <div class="field-error hidden" data-err="ifsc"></div>
      </div>
      <div><label class="field-label">Bank</label><input id="f_bank_display" class="field-input bg-slate-50" readonly placeholder="Auto-filled from IFSC"><input type="hidden" id="f_bank_id"></div>
      <div id="wrap_branch_pick" class="hidden"><label class="field-label">Select Branch *</label>
        <select id="f_branch_pick" class="field-select"></select>
        <div class="field-hint">This IFSC is shared by multiple branches — pick yours.</div>
        <div class="field-error hidden" data-err="branch_name"></div>
      </div>
      <div id="wrap_branch_readonly"><label class="field-label">Branch Name</label><input id="f_branch_name" class="field-input bg-slate-50" readonly placeholder="Auto-filled from IFSC"></div>
      <div><label class="field-label">MICR Code</label><input id="f_micr" class="field-input bg-slate-50" readonly placeholder="Auto-filled from IFSC"></div>
      <div><label class="field-label">Account Number</label><input id="f_acno" class="field-input"><div class="field-error hidden" data-err="acno"></div></div>
      <div><label class="field-label">Account Holder Name</label>
        <select id="f_ac_holder" class="field-select"><option value="">Fill in names first</option></select>
        <div class="field-hint">Must be the CWSN's own, father's, or mother's name.</div>
        <div class="field-error hidden" data-err="ac_holder"></div>
      </div>
    </div>
  </div>

  <div class="wizard-step card p-5" data-step="6">
    <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between mb-3">
      <div>
        <h2 class="text-sm font-bold text-slate-700 uppercase tracking-wide">Review Before Saving</h2>
        <p class="text-xs text-slate-500 mt-1">Check everything below, jump back to fix anything, then save.</p>
      </div>
      <button type="button" id="btnPrint" class="btn btn-secondary" disabled title="Save the record at least once before downloading a PDF.">Download / Print PDF</button>
    </div>
    <div id="incompleteWarning" class="hidden rounded-lg bg-amber-50 border border-amber-200 px-4 py-3 text-sm text-amber-800 mb-3"></div>
    <div id="reviewArea" class="space-y-4"></div>
  </div>

  <div id="printArea" class="hidden print:block print-form">
    <div class="print-form-header">
      <div class="print-form-title">CWSN Portal — SSM Purba Bardhaman</div>
      <div id="printSubtitle"></div>
    </div>
    <div id="printBody"></div>
  </div>

  <div class="flex flex-col-reverse gap-2 pb-8 sm:flex-row sm:justify-between">
    <a href="cwsn_list.php" class="btn btn-secondary">Cancel</a>
    <div class="flex flex-col-reverse gap-2 sm:flex-row">
      <button type="button" id="btnBack" class="btn btn-secondary hidden">&larr; Back</button>
      <button type="button" id="btnSave" class="btn btn-secondary">Save</button>
      <button type="button" id="btnSaveNext" class="btn btn-primary">Save &amp; Next</button>
    </div>
  </div>
</div>

<script>
const MASTER = {
  clrc: <?= json_encode($clrcs) ?>,
  clusters: <?= json_encode($clusters) ?>,
  disabilities: <?= json_encode($disabilities) ?>,
  appliances: <?= json_encode($appliances) ?>,
  banks: <?= json_encode($banks) ?>,
  spledus: <?= json_encode($spledus) ?>,
  classes: <?= json_encode($classes) ?>,
};
const INITIAL = <?= json_encode($formData) ?>;
const INITIAL_SCHOOL_NAME = <?= json_encode($currentSchoolName) ?>;
const INITIAL_SCHCAT_ID = <?= json_encode($currentSchcat) ?>;
const INITIAL_AWC_NAME = <?= json_encode($currentAwcName) ?>;
const IS_EDIT = <?= $isEdit ? 'true' : 'false' ?>;
</script>
<script src="assets/js/cwsn_form.js"></script>

<?php require __DIR__ . '/includes/footer.php'; ?>
