<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Book an appointment — {{ $brand->name }}</title>
<style>
 :root{ --accent: {{ $brand->accent_hex ?: '#0d9488' }}; }
 *{box-sizing:border-box} body{margin:0;font-family:system-ui,'Segoe UI',Roboto,sans-serif;background:#f1f5f9;color:#0f172a}
 .wrap{max-width:560px;margin:0 auto;padding:18px}
 .card{background:#fff;border:1px solid #e2e8f0;border-radius:12px;padding:18px;margin-bottom:14px}
 .brand{display:flex;align-items:center;gap:12px;margin-bottom:14px}
 .brand h1{font-size:20px;margin:0}
 label{display:block;font-size:13px;font-weight:600;margin:10px 0 4px}
 input,select{width:100%;padding:10px;border:1px solid #cbd5e1;border-radius:8px;font-size:14px}
 .row{display:flex;gap:10px} .row>div{flex:1}
 .slots{display:flex;flex-wrap:wrap;gap:8px;margin-top:8px}
 .slot{padding:8px 10px;border:1px solid #cbd5e1;border-radius:8px;background:#fff;cursor:pointer;font-size:13px}
 .slot.sel{background:var(--accent);color:#fff;border-color:var(--accent)}
 .slot[disabled]{opacity:.4;cursor:not-allowed;text-decoration:line-through}
 .btn{width:100%;padding:12px;border:0;border-radius:8px;background:var(--accent);color:#fff;font-size:15px;font-weight:600;cursor:pointer;margin-top:14px}
 .btn[disabled]{opacity:.6;cursor:not-allowed}
 .muted{color:#64748b;font-size:12px}
 .ok{background:#ecfdf5;border:1px solid #a7f3d0;color:#065f46;padding:14px;border-radius:10px}
 .err{color:#b91c1c;font-size:13px;margin-top:8px}
</style>
</head>
<body>
<div class="wrap">
  <div class="card">
    <div class="brand">
      @if($brand->logo_url)<img src="{{ $brand->logo_url }}" alt="" style="height:42px;border-radius:8px;">@endif
      <div><h1>{{ $brand->name }}</h1><div class="muted">Book an appointment</div></div>
    </div>

    <div id="form">
      <label>Pick a date</label>
      <input type="date" id="date" value="{{ now()->toDateString() }}" min="{{ now()->toDateString() }}">

      <label>Doctor (optional)</label>
      <select id="doctor">
        <option value="">Any available</option>
        @foreach($doctors as $doc)<option value="{{ $doc['id'] }}">{{ $doc['name'] }}</option>@endforeach
      </select>

      <label>Available times</label>
      <div class="slots" id="slots"><span class="muted">Choose a date to see times…</span></div>

      <hr style="margin:16px 0;border:0;border-top:1px solid #e2e8f0;">

      <div class="row">
        <div><label>Your name</label><input id="owner_name" maxlength="120"></div>
        <div><label>Phone</label><input id="owner_phone" maxlength="30" inputmode="tel"></div>
      </div>
      <label>Email (optional)</label><input id="owner_email" type="email" maxlength="120">
      <div class="row">
        <div><label>{{ $subjectLabel }} name</label><input id="subject_name" maxlength="60"></div>
        @if($showSpecies)<div><label>Species</label><input id="species" maxlength="40" placeholder="Dog, Cat…"></div>@endif
      </div>
      <label>Reason (optional)</label><input id="reason" maxlength="200">

      <div id="otpBox" style="display:none;">
        <label>Verification code <small class="muted">— sent to your phone</small></label>
        <input id="otp_code" maxlength="6" inputmode="numeric" autocomplete="one-time-code" placeholder="6-digit code">
      </div>

      {{-- Honeypot — hidden from humans, catches bots. --}}
      <input type="text" id="website" name="website" tabindex="-1" autocomplete="off"
             aria-hidden="true" style="position:absolute;left:-9999px;width:1px;height:1px;opacity:0;">

      <button class="btn" id="submit">Request appointment</button>
      <div class="err" id="err"></div>
    </div>

    <div id="done" style="display:none;"></div>
  </div>
  <div class="muted" style="text-align:center;">You will receive a confirmation once the clinic reviews your request.</div>
</div>

<script>
(function(){
  var slug = @json($slug);
  var token = document.querySelector('meta[name=csrf-token]').content;
  var availUrl = @json(route('portal-api.book.availability'));
  var submitUrl = @json(route('portal-api.book.submit'));
  var otpUrl = @json(route('portal-api.book.otp'));
  var otpRequired = @json($otpRequired);
  var picked = null;
  var otpChallenge = null;
  function q(id){ return document.getElementById(id); }
  function defaultLabel(){ return otpRequired ? (otpChallenge ? 'Confirm booking' : 'Send code & continue') : 'Request appointment'; }

  function loadSlots(){
    picked = null;
    var box = q('slots'); box.innerHTML = '<span class="muted">Loading…</span>';
    var u = availUrl + '?date=' + encodeURIComponent(q('date').value)
          + (q('doctor').value ? '&doctor_id=' + q('doctor').value : '')
          + (slug ? '&slug=' + encodeURIComponent(slug) : '');
    fetch(u, {headers:{'Accept':'application/json'}}).then(function(r){ return r.json(); }).then(function(d){
      var slots = (d && d.slots) ? d.slots : [];
      if(!slots.length){ box.innerHTML = '<span class="muted">No times available on this day.</span>'; return; }
      box.innerHTML = '';
      slots.forEach(function(s){
        var b = document.createElement('button');
        b.className = 'slot'; b.type = 'button'; b.textContent = s.label || s.start;
        if(s.available === false){ b.disabled = true; }
        b.onclick = function(){ picked = s.start; [].forEach.call(box.children, function(c){ c.classList.remove('sel'); }); b.classList.add('sel'); };
        box.appendChild(b);
      });
    }).catch(function(){ box.innerHTML = '<span class="muted">Could not load times.</span>'; });
  }
  q('date').onchange = loadSlots; q('doctor').onchange = loadSlots;
  loadSlots();
  q('submit').textContent = defaultLabel();

  q('submit').onclick = function(){
    q('err').textContent = '';
    if(!picked){ q('err').textContent = 'Please choose an available time.'; return; }

    // When the clinic requires it, send a one-time code to the phone first.
    if(otpRequired && !otpChallenge){
      var phone = q('owner_phone').value.trim();
      if(phone.length < 8){ q('err').textContent = 'Enter your phone number to receive a code.'; return; }
      var b = q('submit'); b.disabled = true; b.textContent = 'Sending code…';
      fetch(otpUrl, {method:'POST', headers:{'Content-Type':'application/json','X-CSRF-TOKEN':token,'Accept':'application/json'}, body: JSON.stringify({slug:slug, phone:phone})})
        .then(function(r){ return r.json(); })
        .then(function(d){
          b.disabled = false;
          if(d.sent && d.challenge){
            otpChallenge = d.challenge;
            q('otpBox').style.display = 'block';
            if(d.dev_code){ q('otp_code').value = d.dev_code; }
            b.textContent = 'Confirm booking';
          } else {
            q('err').textContent = d.message || 'Could not send a code. Please try again.';
            b.textContent = defaultLabel();
          }
        }).catch(function(){ b.disabled = false; q('err').textContent = 'Could not send a code. Please try again.'; b.textContent = defaultLabel(); });
      return;
    }

    doSubmit();
  };

  function doSubmit(){
    var payload = {
      slug: slug, website: q('website').value,
      owner_name: q('owner_name').value, owner_phone: q('owner_phone').value, owner_email: q('owner_email').value,
      subject_name: q('subject_name').value, species: (q('species') ? q('species').value : ''), reason: q('reason').value,
      doctor_id: q('doctor').value || null,
      date: String(picked).substring(0, 10),
      time: String(picked).substring(11, 16),
      otp_challenge: otpChallenge, otp_code: (q('otp_code') ? q('otp_code').value : '')
    };
    var btn = q('submit'); btn.disabled = true; btn.textContent = 'Sending…';
    fetch(submitUrl, {method:'POST', headers:{'Content-Type':'application/json','X-CSRF-TOKEN':token,'Accept':'application/json'}, body: JSON.stringify(payload)})
      .then(function(r){ return r.json().then(function(j){ return {ok:r.ok, j:j}; }); })
      .then(function(res){
        if(res.ok && res.j.ok){
          q('form').style.display = 'none';
          var done = q('done'); done.style.display = 'block';
          done.innerHTML = '<div class="ok"><strong>Request received!</strong><br>Your reference is <b>' + res.j.ref_no + '</b>.<br>' + (res.j.message || '') + '</div>';
        } else {
          var msg = res.j.message || 'Could not submit. Please check your details.';
          if(res.j.errors){ msg = Object.values(res.j.errors)[0][0]; }
          q('err').textContent = msg; btn.disabled = false; btn.textContent = defaultLabel();
        }
      }).catch(function(){ q('err').textContent = 'Network error. Please try again.'; btn.disabled = false; btn.textContent = defaultLabel(); });
  }
})();
</script>
</body>
</html>
