<?php
// /edenrms/pages/student_detail.php
declare(strict_types=1);
@header('Content-Type: text/html; charset=utf-8');
function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }

$err=null; $student=[]; $photo=''; $student_id=(int)($_GET['id'] ?? $_POST['id'] ?? 0);
try{
  $mysqli=null; $inc=__DIR__.'/../includes/db.php';
  if (is_file($inc)) { require_once $inc; if (isset($conn) && $conn instanceof mysqli) $mysqli=$conn; }
  if (!$mysqli instanceof mysqli) { $mysqli=new mysqli('localhost','root','','edencamp_edencampus'); }
  $mysqli->set_charset('utf8mb4');
  mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
  if ($student_id<=0) throw new InvalidArgumentException('Invalid student ID');

  $st=$mysqli->prepare("SELECT * FROM studentss WHERE id=? LIMIT 1");
  $st->bind_param('i',$student_id); $st->execute();
  $res=$st->get_result(); $student=$res?($res->fetch_assoc()?:[]):[]; $st->close();
  if(!$student) throw new RuntimeException('Student not found');

  $photoFile=(string)($student['photograph'] ?? '');
  $photo = $photoFile ? ('../uploads/'.basename($photoFile))
                      : 'data:image/svg+xml;utf8,'.rawurlencode('<svg xmlns="http://www.w3.org/2000/svg" width="120" height="120"><rect width="100%" height="100%" fill="#e9ecef"/><text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" font-family="sans-serif" font-size="12" fill="#6c757d">Photo</text></svg>');
}catch(Throwable $e){ $err=$e->getMessage(); }
$asModal = !empty($_GET['modal']) || !empty($_POST['modal']);
?>
<style>
#actionModal .modal-body, #studentDetailModal .modal-body { font-size:.90rem; }
#studentDetailModal .modal-header{padding:.45rem .75rem}
#studentDetailModal .modal-title{font-size:1rem}
.detail-container { max-width: 920px; margin: 0 auto; padding: 16px 20px; }
.detail-table { table-layout: fixed; width: 100%; }
.detail-table col:first-child { width: 220px; }
#studentDetailModal .form-label{font-size:.82rem; margin-bottom:.2rem; color:#495057;}
#studentDetailModal .form-control,#studentDetailModal .form-select{font-size:.90rem; padding:.30rem .55rem; height:2.15rem; border-radius:.4rem;}
#studentDetailModal textarea{height:auto; min-height:2.15rem;}
#studentDetailModal #photoPreview{width:88px; height:88px; object-fit:cover;}
#studentDetailModal #photoInput{ max-width:320px }
#studentDetailModal .form-text{ margin-top:.15rem; font-size:.78rem }
</style>

<div class="detail-container" data-student-id="<?= (int)$student_id ?>">
  <?php if ($err): ?>
    <div class="alert alert-danger mb-2"><strong>Failed to load student.</strong><div class="small"><?= h($err) ?></div></div>
  <?php else: ?>
    <input type="hidden" name="id" value="<?= (int)$student_id ?>">

    <!-- VIEW -->
    <div id="viewWrap">
      <div class="d-flex mb-3">
        <div class="flex-shrink-0 me-3"><img src="<?= h($photo) ?>" class="rounded border" width="96" height="96" alt=""></div>
        <div class="flex-grow-1">
          <p class="mb-1"><strong>Student ID:</strong> <?= h($student['center_reg_no'] ?? '—') ?></p>
          <p class="mb-1"><strong>Full Name:</strong> <?= h($student['full_name'] ?? '—') ?></p>
          <p class="mb-1"><strong>Date of Birth / Gender:</strong> <?= h($student['dob'] ?? '—') ?>
            <?php if(!empty($student['gender'])): ?><span class="badge bg-secondary"><?= h($student['gender']) ?></span><?php endif; ?>
          </p>
          <p class="mb-1"><strong>NIC/Passport / Nationality:</strong> <?= h($student['nic_passport'] ?? ($student['nic'] ?? '')) ?> (<?= h($student['nationality'] ?? '') ?>)</p>
        </div>
      </div>

      <h6 class="mt-3">Contact Details</h6>
      <table class="table table-bordered mb-3 detail-table"><colgroup><col><col></colgroup>
        <tr><th>Mobile</th><td><?= h($student['mobile'] ?? '') ?></td></tr>
        <tr><th>Email</th><td><?= h($student['email'] ?? '') ?></td></tr>
        <tr><th>Address</th><td><?= h(trim(($student['address1'] ?? '').' '.($student['address2'] ?? ''))) ?></td></tr>
        <tr><th>City / Country</th><td><?= h($student['city'] ?? '') ?> / <?= h($student['country'] ?? '') ?></td></tr>
      </table>

      <h6>Guardian Details</h6>
      <table class="table table-bordered mb-3 detail-table"><colgroup><col><col></colgroup>
        <tr><th>Name</th><td><?= h($student['guardian_name'] ?? '') ?></td></tr>
        <tr><th>Relationship</th><td><?= h($student['guardian_relationship'] ?? '') ?></td></tr>
        <tr><th>Contact</th><td><?= h($student['guardian_contact'] ?? '') ?></td></tr>
      </table>

      <div class="text-end">
        <button class="btn btn-secondary btn-sm js-edit">EDIT</button>
        <button class="btn btn-primary  btn-sm" disabled>RE-ISSUE ID</button>
        <button class="btn btn-danger   btn-sm js-delete">DELETE</button>
      </div>
    </div>

  <!-- ===== EDIT FORM (includes file + camera) ===== -->
  <div id="editWrap" style="display:none;">
    <form id="editStudentForm" class="needs-validation" novalidate enctype="multipart/form-data">
      <input type="hidden" name="id" value="<?= (int)$student_id ?>">

      <div class="row g-3">
        <!-- Photo block -->
        <div class="col-12">
          <label class="form-label d-block">Photo</label>
          <div class="d-flex align-items-center gap-3 flex-wrap">
            <img id="photoPreview" src="<?= htmlspecialchars($photo) ?>" class="rounded border" width="120" height="120" alt="Preview">
            <div class="d-flex gap-2">
              <input type="file" id="photoInput" name="photo" class="form-control" accept="image/*">
              <button type="button" id="btnOpenCamera" class="btn btn-outline-secondary">
                <i class="bi bi-camera-video"></i> Use Camera
              </button>
            </div>
            <small class="text-muted w-100">Accepted: JPG, PNG, WEBP, GIF. Max 2 MB.</small>
          </div>
        </div>

        <div class="col-md-6">
          <label class="form-label">Full Name</label>
          <input type="text" name="full_name" class="form-control" value="<?= htmlspecialchars($student['full_name'] ?? '') ?>">
        </div>
        <div class="col-md-3">
          <label class="form-label">Gender</label>
          <select name="gender" class="form-select">
            <option value="" <?= empty($student['gender'])?'selected':''; ?>>—</option>
            <option value="Male"   <?= ($student['gender']??'')==='Male'?'selected':''; ?>>Male</option>
            <option value="Female" <?= ($student['gender']??'')==='Female'?'selected':''; ?>>Female</option>
          </select>
        </div>
        <div class="col-md-3">
          <label class="form-label">Date of Birth</label>
          <input type="date" name="dob" class="form-control" value="<?= htmlspecialchars($student['dob'] ?? '') ?>">
        </div>
<div class="col-md-4">
  <label class="form-label">NIC / Passport</label>
  <input
    type="text"
    name="<?= array_key_exists('nic_passport', $student) ? 'nic_passport' : 'nic' ?>"
    class="form-control"
    value="<?= htmlspecialchars($student['nic_passport'] ?? ($student['nic'] ?? '')) ?>">
</div>

<div class="col-md-4">
  <label class="form-label">Nationality</label>
  
  <select name="nationality" class="form-select">
    <?php $nat = strtolower(trim((string)($student['nationality'] ?? ''))); ?>
    <option value="Sinhala" <?= $nat === 'sinhala' ? 'selected' : '' ?>>Sinhala</option>
    <option value="Tamil" <?= $nat === 'tamil' ? 'selected' : '' ?>>Tamil</option>
    <option value="Muslim" <?= $nat === 'muslim' ? 'selected' : '' ?>>Muslim</option>
  </select>
</div>
<div class="col-md-4">
    <label class="form-label fw-semibold">LMS Status</label>

    <?php $lms = strtolower((string)($student['lms_status'] ?? 'active')); ?>

    <select name="lms_status" class="form-select">
        <option value="active" <?= $lms === 'active' ? 'selected' : '' ?>>
            Active
        </option>

        <option value="inactive" <?= $lms === 'inactive' ? 'selected' : '' ?>>
            Inactive
        </option>

        <option value="suspended" <?= $lms === 'suspended' ? 'selected' : '' ?>>
            Suspended
        </option>
    </select>

    <small class="text-muted">
        Controls only this student's ELMS login access
    </small>
</div>
        <div class="col-md-4">
          <label class="form-label">Mobile</label>
          <input type="text" name="mobile" class="form-control" value="<?= htmlspecialchars($student['mobile'] ?? '') ?>">
        </div>
        <div class="col-md-4">
          <label class="form-label">Email</label>
          <input type="email" name="email" class="form-control" value="<?= htmlspecialchars($student['email'] ?? '') ?>">
        </div>

        <div class="col-md-6">
          <label class="form-label">Address Line 1</label>
          <input type="text" name="address1" class="form-control" value="<?= htmlspecialchars($student['address1'] ?? '') ?>">
        </div>
        <div class="col-md-6">
          <label class="form-label">Address Line 2</label>
          <input type="text" name="address2" class="form-control" value="<?= htmlspecialchars($student['address2'] ?? '') ?>">
        </div>

        <div class="col-md-4">
          <label class="form-label">City</label>
          <input type="text" name="city" class="form-control" value="<?= htmlspecialchars($student['city'] ?? '') ?>">
        </div>
        <div class="col-md-4">
          <label class="form-label">Country</label>
          <input type="text" name="country" class="form-control" value="<?= htmlspecialchars($student['country'] ?? '') ?>">
        </div>

        <div class="col-12"><hr></div>

        <div class="col-md-4">
          <label class="form-label">Guardian Name</label>
          <input type="text" name="guardian_name" class="form-control" value="<?= htmlspecialchars($student['guardian_name'] ?? '') ?>">
        </div>
        <div class="col-md-4">
          <label class="form-label">Guardian Relationship</label>
          <input type="text" name="guardian_relationship" class="form-control" value="<?= htmlspecialchars($student['guardian_relationship'] ?? '') ?>">
        </div>
        <div class="col-md-4">
          <label class="form-label">Guardian Contact</label>
          <input type="text" name="guardian_contact" class="form-control" value="<?= htmlspecialchars($student['guardian_contact'] ?? '') ?>">
        </div>
      </div>

      <div class="text-end mt-4">
        <button type="button" id="btnCancelEdit" class="btn btn-outline-secondary">Cancel</button>
        <button type="submit" class="btn btn-success">Save</button>
      </div>
    </form>
  </div>
</div>

<!-- Camera Modal -->
<div class="modal fade" id="cameraModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"><i class="bi bi-camera-video me-2"></i>Capture Photo</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div class="text-center">
          <video id="camVideo" autoplay muted playsinline style="max-width:100%; border-radius:8px;"></video>
          <canvas id="camCanvas" width="640" height="480" class="d-none"></canvas>
        </div>
        <div class="d-flex justify-content-center gap-2 mt-3">
          <button class="btn btn-outline-secondary" id="btnSwitchFacing" type="button">Switch Camera</button>
          <button class="btn btn-primary" id="btnCapture" type="button">Capture</button>
          <button class="btn btn-success d-none" id="btnUsePhoto" type="button">Use Photo</button>
          <button class="btn btn-outline-danger d-none" id="btnRetake" type="button">Retake</button>
        </div>
        <div class="form-text text-center mt-2">Tip: Works over HTTPS or localhost.</div>
      </div>
    </div>
  </div>
</div>

  <?php endif; ?>
</div>


<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
function wrapOf(el){ return $(el).closest('.detail-container'); }

/* ========= UI: View ↔ Edit ========= */
$(document).off('click.sdEdit').on('click.sdEdit', '.detail-container .js-edit', function () {
  const $w = wrapOf(this);
  $w.find('#viewWrap').hide();
  $w.find('#editWrap').show()[0]?.scrollIntoView({ behavior: 'smooth' });
});
$(document).off('click.sdCancel').on('click.sdCancel', '.detail-container .js-cancel-edit, #btnCancelEdit', function () {
  const $w = wrapOf(this);
  $w.find('#editWrap').hide();
  $w.find('#viewWrap').show();
});

/* ========= Live preview (file chooser) ========= */
$(document).off('change.sdPhoto').on('change.sdPhoto', '.detail-container #photoInput', function () {
  const $w = wrapOf(this);
  const f = this.files && this.files[0];
  if (f) {
    $w.find('#photoPreview').attr('src', URL.createObjectURL(f));
    window.capturedBlob = null; // if user picked a file, prefer it
  }
});

/* ========= Camera support ========= */
let camStream = null;
window.capturedBlob = null; // global so submit handler can read it
let facing = 'user'; // 'user' | 'environment'

async function startCamera(){
  try {
    const constraints = { video: { width: {ideal: 640}, height: {ideal: 480}, facingMode: facing } };
    const stream = await navigator.mediaDevices.getUserMedia(constraints);
    camStream = stream;
    const v = document.getElementById('camVideo');
    v.srcObject = stream;
    v.onloadedmetadata = () => v.play();
  } catch (err) {
    alert('Unable to access camera: ' + (err.message || err));
  }
}
function stopCamera(){
  if (camStream) { camStream.getTracks().forEach(t => t.stop()); camStream = null; }
}
function showVideoMode(){
  $('#camVideo').removeClass('d-none');
  $('#camCanvas').addClass('d-none');
  $('#btnUsePhoto, #btnRetake').addClass('d-none');
  $('#btnCapture').removeClass('d-none');
}
function showPreviewMode(){
  $('#camVideo').addClass('d-none');
  $('#camCanvas').removeClass('d-none');
  $('#btnUsePhoto, #btnRetake').removeClass('d-none');
  $('#btnCapture').addClass('d-none');
}
$('#btnOpenCamera').on('click', async function(){
  window.capturedBlob = null;
  showVideoMode();
  const modal = new bootstrap.Modal(document.getElementById('cameraModal'));
  modal.show();
  await startCamera();
});
$('#btnSwitchFacing').on('click', async function(){
  facing = (facing === 'user') ? 'environment' : 'user';
  stopCamera(); showVideoMode(); await startCamera();
});
$('#btnCapture').on('click', function(){
  const v = document.getElementById('camVideo');
  const c = document.getElementById('camCanvas');
  const ctx = c.getContext('2d');
  const vw = v.videoWidth, vh = v.videoHeight;
  if (!vw || !vh) return;
  const cw = c.width, ch = c.height;

  // cover crop to canvas size
  const videoRatio = vw / vh, canvasRatio = cw / ch;
  let sx, sy, sw, sh;
  if (videoRatio > canvasRatio) {
    sh = vh; sw = vh * canvasRatio; sx = (vw - sw) / 2; sy = 0;
  } else {
    sw = vw; sh = vw / canvasRatio; sx = 0; sy = (vh - sh) / 2;
  }
  ctx.clearRect(0,0,cw,ch);
  ctx.drawImage(v, sx, sy, sw, sh, 0, 0, cw, ch);
  showPreviewMode();
});
$('#btnUsePhoto').on('click', function(){
  const c = document.getElementById('camCanvas');
  c.toBlob(function(blob){
    window.capturedBlob = blob;                // prefer camera
    $('#photoPreview').attr('src', URL.createObjectURL(blob));
    $('#photoInput').val('');                  // clear file picker
    const modalEl = document.getElementById('cameraModal');
    const modal = bootstrap.Modal.getInstance(modalEl);
    modal.hide();
  }, 'image/jpeg', 0.90);
});
$('#btnRetake').on('click', function(){ showVideoMode(); });
document.getElementById('cameraModal').addEventListener('hidden.bs.modal', function(){ stopCamera(); });

/* ========= JS Compression helper ========= */
// Resize+compress any File/Blob into JPEG Blob (strip metadata)
function compressImageBlob(inputBlob, {maxW = 800, maxH = 800, quality = 0.82} = {}) {
  return new Promise((resolve, reject) => {
    const url = URL.createObjectURL(inputBlob);
    const img = new Image();
    img.onload = () => {
      let w = img.naturalWidth || img.width;
      let h = img.naturalHeight || img.height;
      const ratio = Math.min(maxW / w, maxH / h, 1); // never upscale
      const cw = Math.round(w * ratio);
      const ch = Math.round(h * ratio);

      const canvas = document.createElement('canvas');
      canvas.width = cw; canvas.height = ch;
      const ctx = canvas.getContext('2d', {alpha:false});
      // fill white bg for transparent PNG/WebP so JPEG looks right
      ctx.fillStyle = '#fff'; ctx.fillRect(0,0,cw,ch);
      ctx.drawImage(img, 0, 0, cw, ch);

      canvas.toBlob((blob) => {
        URL.revokeObjectURL(url);
        if (!blob) return reject(new Error('Compression failed'));
        resolve(blob);
      }, 'image/jpeg', quality);
    };
    img.onerror = () => { URL.revokeObjectURL(url); reject(new Error('Image load failed')); };
    img.src = url;
  });
}

/* ========= Save (AJAX with compression) ========= */
$(document).off('submit.sdSave').on('submit.sdSave', '.detail-container #editStudentForm', function (e) {
  e.preventDefault();
  const $form = $(this);
  const sid = Number($form.find('input[name=id]').val() || 0);
  const $btn = $form.find('button[type=submit]').prop('disabled', true).text('Saving…');

  const fd = new FormData(this);
  fd.set('id', String(sid));
  fd.set('student_id', String(sid));

  const fileFromPicker = $form.find('#photoInput')[0]?.files?.[0];

  (async () => {
    // choose source (prefer camera)
    let srcBlob = null, filename = 'photo.jpg';
    if (window.capturedBlob instanceof Blob) {
      srcBlob = window.capturedBlob; filename = 'camera.jpg';
    } else if (fileFromPicker) {
      srcBlob = fileFromPicker;
      filename = (fileFromPicker.name || 'photo').replace(/\.(png|webp|gif)$/i, '.jpg');
    }

    if (srcBlob) {
      try {
        // compress to <=800×800 @ ~82% quality
        const compressed = await compressImageBlob(srcBlob, {maxW: 800, maxH: 800, quality: 0.82});
        fd.delete('photo');
        fd.append('photo', compressed, filename || 'photo.jpg');
      } catch (err) {
        console.warn('Compression failed, sending original:', err);
        fd.delete('photo');
        fd.append('photo', srcBlob, filename || 'photo.jpg');
      }
    }

    $.ajax({
      url: '/edenrms/pages/update_student.php?sid=' + sid,
      method: 'POST',
      data: fd,
      contentType: false,
      processData: false,
      dataType: 'json',
      timeout: 120000
    })
    .done(function (res) {
      if (res && res.ok) {
        window.openStudentDetail?.(sid, 'student_detail.php?id=' + sid);
      } else {
        alert(res && res.error ? res.error : 'Update failed');
      }
    })
    .fail(function (xhr, status) {
      alert('Update failed: ' + (xhr.responseText || status || 'unknown'));
    })
    .always(function () { $btn.prop('disabled', false).text('Save'); });
  })();
});

$(document).off('click.sdDelete').on('click.sdDelete', '.detail-container .js-delete', function () {
  const sid = Number(wrapOf(this).data('student-id') || 0);
  if (!sid) return;

  if (!confirm('Delete this student?\n• Admin: hard delete now\n• Others: send approval request')) return;

  const reason = prompt('Reason for deletion (optional):', '') || '';
  const fd = new FormData();
  fd.append('student_id', String(sid));
  if (reason) fd.append('reason', reason);

  fetch('/edenrms/ajax/delete_student.php', {
    method: 'POST',
    body: fd,
    credentials: 'same-origin',
    headers: {
      'X-Requested-With': 'XMLHttpRequest',
      'Accept': 'application/json'
    }
  })
  .then(async (r) => {
    const text = await r.text();
    try {
      return JSON.parse(text);
    } catch (e) {
      alert('Server returned invalid response:\n' + text.slice(0, 200));
      throw e;
    }
  })
  .then((j) => {
    if (!j || !j.ok) {
      alert(j && j.error ? j.error : 'Delete failed');
      return;
    }

    if (j.hard) {
      alert(j.message || 'Student deleted successfully');
      location.reload();
      return;
    }

    alert(j.message || 'Delete request sent for approval.');
  })
  .catch((err) => {
    alert('Failed: ' + (err.message || err));
  });
});


