<?php
$e = static fn($v) => htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
$form = $form ?? [];
$session = $session ?? null;
$value = static fn($key, $default = '') => $form[$key] ?? ($session[$key] ?? $default);
$hasNotes = trim((string)$value('interventions')) !== '' || trim((string)$value('activities')) !== '' || trim((string)$value('patient_response')) !== '' || trim((string)$value('progress')) !== '' || trim((string)$value('recommendations')) !== '' || trim((string)$value('notes')) !== '';
?>
<section class="page-header session-page-header">
  <div>
    <p class="eyebrow">Clinical · Session</p>
    <h1><?= $session ? 'Edit Therapy Session' : 'Record Therapy Session' ?></h1>
    <p class="session-subtitle">Capture the essentials first. Add clinical notes when you need them.</p>
  </div>
  <a class="btn btn-secondary" href="/crm/public/sessions">Back to Sessions</a>
</section>

<?php if (!empty($error)): ?><div class="alert alert-danger"><?= $e($error) ?></div><?php endif; ?>
<?php if (!empty($message)): ?><div class="alert alert-success"><?= $e($message) ?></div><?php endif; ?>

<form method="post" action="<?= $session ? '/crm/public/sessions/'.(int)$session['id'].'/edit' : '/crm/public/sessions/create' ?>" class="form-stack session-form">
  <input type="hidden" name="_csrf" value="<?= $e($csrf) ?>">

  <?php if (!empty($value('appointment_id'))): ?>
    <input type="hidden" name="appointment_id" value="<?= (int)$value('appointment_id') ?>">
    <div class="alert alert-success session-linked">✓ Linked to appointment #<?= (int)$value('appointment_id') ?> · saving as completed will finish the appointment.</div>
  <?php endif; ?>

  <section class="card session-card session-main-card">
    <div class="session-card-heading">
      <div>
        <span class="session-step">01</span>
        <div><h2>Session essentials</h2><p>Record who, when and what was provided.</p></div>
      </div>
      <span class="session-badge">Clinical record</span>
    </div>

    <div class="session-patient-grid">
      <label class="form-field session-field session-field-wide">
        <span>Patient</span>
        <select name="patient_id" required <?= $session ? 'disabled' : '' ?> aria-label="Patient">
          <option value="">Select patient</option>
          <?php foreach ($patients as $p): ?>
            <option value="<?= (int)$p['id'] ?>" <?= (string)$value('patient_id') === (string)$p['id'] ? 'selected' : '' ?>><?= $e($p['first_name'].' '.$p['last_name'].' — '.$p['patient_reference']) ?></option>
          <?php endforeach; ?>
        </select>
        <?php if ($session): ?><input type="hidden" name="patient_id" value="<?= (int)$session['patient_id'] ?>"><?php endif; ?>
      </label>
      <label class="form-field session-field session-field-wide">
        <span>Therapist</span>
        <select name="therapist_id" required <?= !empty($therapistLocked) ? 'disabled' : '' ?> aria-label="Therapist">
          <option value="">Select therapist</option>
          <?php foreach ($therapists as $t): ?>
            <option value="<?= (int)$t['id'] ?>" <?= (string)$value('therapist_id') === (string)$t['id'] ? 'selected' : '' ?>><?= $e($t['full_name']) ?><?= !empty($t['professional_title']) ? ' — '.$e($t['professional_title']) : '' ?></option>
          <?php endforeach; ?>
        </select>
        <?php if (!empty($therapistLocked)): ?><input type="hidden" name="therapist_id" value="<?= (int)$therapists[0]['id'] ?>"><?php endif; ?>
      </label>
    </div>

    <div class="session-compact-grid">
      <label class="form-field session-field"><span>Date</span><input type="date" name="session_date" value="<?= $e($value('session_date', date('Y-m-d'))) ?>" required></label>
      <label class="form-field session-field"><span>Service</span><select name="service_id"><option value="">Not specified</option><?php foreach ($services as $service): ?><option value="<?= (int)$service['id'] ?>" <?= (string)$value('service_id') === (string)$service['id'] ? 'selected' : '' ?>><?= $e($service['name']) ?></option><?php endforeach; ?></select></label>
      <label class="form-field session-field"><span>Status</span><select name="status"><?php foreach (['scheduled','completed','cancelled','no_show'] as $s): ?><option value="<?= $s ?>" <?= $value('status','completed') === $s ? 'selected' : '' ?>><?= $e(ucwords(str_replace('_',' ',$s))) ?></option><?php endforeach; ?></select></label>
      <label class="form-field session-field"><span>Session type <em>optional</em></span><input name="session_type" value="<?= $e($value('session_type')) ?>" placeholder="Therapy, review, home visit…" maxlength="80"></label>
    </div>

    <div class="session-time-row">
      <div><span class="session-mini-label">Time</span><span class="session-mini-copy">Optional · use when duration matters</span></div>
      <div class="session-time-fields">
        <label class="form-field"><span>Start</span><input type="time" name="start_time" value="<?= $e($value('start_time')) ?>"></label>
        <span class="session-time-arrow">→</span>
        <label class="form-field"><span>End</span><input type="time" name="end_time" value="<?= $e($value('end_time')) ?>"></label>
      </div>
    </div>

    <div class="session-billing-note"><span class="session-check">✓</span><div><strong>Billable when completed</strong><p>Completed sessions with a service can be included on an invoice. Cancelled and no-show sessions are excluded.</p></div></div>
  </section>

  <details class="card session-card clinical-notes-card" <?= $hasNotes ? 'open' : '' ?>>
    <summary class="clinical-summary">
      <div><span class="session-step">02</span><div><h2>Clinical notes</h2><p><?= $hasNotes ? 'Notes saved for this session.' : 'Optional · add clinical detail only when needed.' ?></p></div></div>
      <span class="clinical-toggle"><span class="clinical-toggle-closed">Add notes</span><span class="clinical-toggle-open">Hide notes</span><span class="clinical-chevron">⌄</span></span>
    </summary>
    <div class="clinical-notes-body">
      <div class="clinical-note-grid">
        <label class="form-field"><span>Interventions</span><textarea name="interventions" rows="4" placeholder="What intervention was provided?"><?= $e($value('interventions')) ?></textarea></label>
        <label class="form-field"><span>Activities</span><textarea name="activities" rows="4" placeholder="Activities completed during the session…"><?= $e($value('activities')) ?></textarea></label>
        <label class="form-field"><span>Patient response</span><textarea name="patient_response" rows="4" placeholder="How did the patient respond?"><?= $e($value('patient_response')) ?></textarea></label>
        <label class="form-field"><span>Progress</span><textarea name="progress" rows="4" placeholder="Progress toward goals…"><?= $e($value('progress')) ?></textarea></label>
        <label class="form-field"><span>Recommendations</span><textarea name="recommendations" rows="4" placeholder="Home programme, follow-up or recommendations…"><?= $e($value('recommendations')) ?></textarea></label>
        <label class="form-field"><span>Additional notes <em>optional</em></span><textarea name="notes" rows="4" placeholder="Anything else worth recording…"><?= $e($value('notes')) ?></textarea></label>
      </div>
    </div>
  </details>

  <div class="form-actions session-actions">
    <a class="btn btn-secondary" href="/crm/public/sessions">Cancel</a>
    <button class="btn btn-primary session-save" type="submit"><span>✓</span><?= $session ? 'Update Session' : 'Save Session' ?></button>
  </div>
</form>

<style>
.session-page-header{align-items:center}.session-subtitle{max-width:620px}.session-form{max-width:1040px}.session-card{border:1px solid #e5edf2;box-shadow:0 10px 28px rgba(35,91,120,.06);border-radius:18px}.session-card-heading,.clinical-summary{display:flex;align-items:center;justify-content:space-between;gap:18px}.session-card-heading>div,.clinical-summary>div{display:flex;align-items:center;gap:12px}.session-card-heading h2,.clinical-summary h2{margin:0}.session-card-heading p,.clinical-summary p{margin:3px 0 0;color:#71808b;font-size:.9rem}.session-step{display:grid;place-items:center;width:34px;height:34px;border-radius:11px;background:#eaf5fa;color:#3d7896;font-weight:800;font-size:.8rem}.session-badge{padding:7px 11px;border-radius:999px;background:#f2f8fb;color:#4c7488;font-size:.78rem;font-weight:700}.session-patient-grid{display:grid;grid-template-columns:1fr 1fr;gap:18px;margin-top:24px}.session-compact-grid{display:grid;grid-template-columns:1.05fr 1.35fr .9fr 1.25fr;gap:14px;margin-top:4px}.session-field em,.clinical-notes-card em{font-style:normal;font-size:.72rem;color:#8997a0;font-weight:500;margin-left:4px}.session-time-row{margin-top:18px;padding-top:18px;border-top:1px solid #edf2f5;display:flex;align-items:center;justify-content:space-between;gap:20px}.session-mini-label{font-weight:700;display:block}.session-mini-copy{font-size:.8rem;color:#7b8992}.session-time-fields{display:flex;align-items:end;gap:10px}.session-time-fields .form-field{min-width:145px}.session-time-arrow{padding-bottom:12px;color:#8aa0ad}.session-billing-note{display:flex;gap:12px;align-items:flex-start;margin-top:20px;padding:13px 15px;border-radius:12px;background:#f3f9fb}.session-check{display:grid;place-items:center;width:24px;height:24px;border-radius:50%;background:#dceff6;color:#39728e;font-weight:800}.session-billing-note strong{font-size:.88rem}.session-billing-note p{margin:2px 0 0;font-size:.78rem;color:#687b87}.clinical-notes-card{overflow:hidden}.clinical-notes-card summary{list-style:none;cursor:pointer;padding:20px}.clinical-notes-card summary::-webkit-details-marker{display:none}.clinical-notes-body{padding:0 20px 20px}.clinical-note-grid{display:grid;grid-template-columns:1fr 1fr;gap:16px;border-top:1px solid #edf2f5;padding-top:20px}.clinical-toggle{display:flex;align-items:center;gap:10px;color:#4b7487;font-size:.8rem;font-weight:700}.clinical-toggle-open{display:none}.clinical-notes-card[open] .clinical-toggle-closed{display:none}.clinical-notes-card[open] .clinical-toggle-open{display:inline}.clinical-chevron{font-size:1.1rem;transition:transform .2s}.clinical-notes-card[open] .clinical-chevron{transform:rotate(180deg)}.session-actions{justify-content:flex-end}.session-save{min-width:150px}.session-save span{margin-right:7px}@media(max-width:800px){.session-patient-grid,.clinical-note-grid{grid-template-columns:1fr}.session-compact-grid{grid-template-columns:1fr 1fr}.session-time-row{display:block}.session-time-fields{margin-top:12px}.session-time-fields .form-field{flex:1}.session-card-heading,.clinical-summary{align-items:flex-start}.session-badge{display:none}}@media(max-width:520px){.session-compact-grid{grid-template-columns:1fr}.session-card-heading h2,.clinical-summary h2{font-size:1rem}.session-card-heading p,.clinical-summary p{font-size:.8rem}.session-actions{display:grid;grid-template-columns:1fr 1.4fr}.session-actions .btn{width:100%;text-align:center}.clinical-summary{padding:17px}.clinical-notes-body{padding:0 17px 17px}}
</style>
