<!DOCTYPE html>
<html lang="<%= lang || 'id' %>">
<head>
  <meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
  <title><%= title %> | <%= company %></title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
  <link rel="stylesheet" href="/css/admin.css">
  <style>
    .attendance-card {
      background: var(--bg2);
      border-radius: 12px;
      padding: 24px;
      margin-bottom: 20px;
      border: 1px solid var(--border);
    }
    .status-badge {
      display: inline-block;
      padding: 8px 16px;
      border-radius: 20px;
      font-size: 14px;
      font-weight: 600;
      margin-bottom: 16px;
    }
    .status-checked-in {
      background: rgba(34, 197, 94, 0.15);
      color: #22c55e;
    }
    .status-checked-out {
      background: rgba(59, 130, 246, 0.15);
      color: #3b82f6;
    }
    .status-not-checked-in {
      background: rgba(239, 68, 68, 0.15);
      color: #ef4444;
    }
    .info-row {
      display: flex;
      justify-content: space-between;
      padding: 12px 0;
      border-bottom: 1px solid var(--border);
    }
    .info-row:last-child {
      border-bottom: none;
    }
    .info-label {
      color: var(--muted);
      font-weight: 500;
    }
    .info-value {
      color: var(--text);
      font-weight: 600;
    }
    .note-input {
      width: 100%;
      padding: 12px;
      border: 1px solid var(--border);
      border-radius: 8px;
      margin-top: 12px;
      font-size: 14px;
      background: var(--bg3);
      color: var(--text);
    }
    .location-info {
      font-size: 12px;
      color: var(--muted);
      margin-top: 8px;
      padding: 8px;
      background: var(--bg3);
      border-radius: 4px;
    }
    .photo-help {
      font-size: 12px;
      color: var(--muted);
      margin-top: 6px;
    }
  </style>
</head>
<body>
<%- include('partials/sidebar', { activePage: 'cashier_attendance', company }) %>

<div class="mw">
  <div class="topbar">
    <div class="tb-title">
      <button class="hb-menu" onclick="toggleSidebar()"><i class="bi bi-list"></i></button>
      <i class="bi bi-calendar-check"></i> <%= title %>
    </div>
    <div class="tb-right">
      <span class="adm-badge">
        <i class="bi bi-person-fill"></i> Kasir
      </span>
      <a href="/admin/logout" class="btn btn-g btn-sm"><i class="bi bi-box-arrow-left"></i></a>
    </div>
  </div>

  <div class="page">
    <% if (msg) { %>
    <div class="alert alert-<%= msg.type === 'success' ? 's' : 'd' %>">
      <i class="bi bi-<%= msg.type === 'success' ? 'check-circle' : 'exclamation-circle' %>"></i> <%= msg.text %>
    </div>
    <% } %>

    <!-- Today's Status -->
    <div class="card">
      <div class="card-hd">
        <h6><i class="bi bi-calendar-day"></i> Status Hari Ini</h6>
      </div>
      <div class="card-bd">
        <% if (todayAttendance) { %>
          <% if (todayAttendance.status === 'checked_in') { %>
            <span class="status-badge status-checked-in">✓ Sudah Check-in</span>
          <% } else { %>
            <span class="status-badge status-checked-out">✓ Sudah Check-out</span>
          <% } %>

          <div class="info-row">
            <span class="info-label">Check-in</span>
            <span class="info-value"><%= new Date(todayAttendance.check_in_time).toLocaleString('id-ID') %></span>
          </div>

          <% if (todayAttendance.check_out_time) { %>
            <div class="info-row">
              <span class="info-label">Check-out</span>
              <span class="info-value"><%= new Date(todayAttendance.check_out_time).toLocaleString('id-ID') %></span>
            </div>
            <div class="info-row">
              <span class="info-label">Durasi Kerja</span>
              <span class="info-value">
                <%= Math.floor(todayAttendance.work_duration_minutes / 60) %> jam 
                <%= todayAttendance.work_duration_minutes % 60 %> menit
              </span>
            </div>
          <% } %>

          <% if (todayAttendance.check_in_note) { %>
            <div class="info-row">
              <span class="info-label">Catatan Check-in</span>
              <span class="info-value"><%= todayAttendance.check_in_note %></span>
            </div>
          <% } %>

          <% if (todayAttendance.check_out_note) { %>
            <div class="info-row">
              <span class="info-label">Catatan Check-out</span>
              <span class="info-value"><%= todayAttendance.check_out_note %></span>
            </div>
          <% } %>

          <% if (todayAttendance.check_in_photo || todayAttendance.check_out_photo) { %>
            <div class="info-row" style="align-items:flex-start">
              <span class="info-label">Foto Absensi</span>
              <span class="info-value" style="display:flex;gap:10px;flex-wrap:wrap;justify-content:flex-end">
                <% if (todayAttendance.check_in_photo) { %>
                  <a href="<%= todayAttendance.check_in_photo %>" target="_blank" style="text-decoration:none;color:var(--text);font-size:12px;text-align:center">
                    <img src="<%= todayAttendance.check_in_photo %>" alt="Foto check-in" style="width:72px;height:72px;object-fit:cover;border-radius:10px;display:block;margin-bottom:4px">
                    Check-in
                  </a>
                <% } %>
                <% if (todayAttendance.check_out_photo) { %>
                  <a href="<%= todayAttendance.check_out_photo %>" target="_blank" style="text-decoration:none;color:var(--text);font-size:12px;text-align:center">
                    <img src="<%= todayAttendance.check_out_photo %>" alt="Foto check-out" style="width:72px;height:72px;object-fit:cover;border-radius:10px;display:block;margin-bottom:4px">
                    Check-out
                  </a>
                <% } %>
              </span>
            </div>
          <% } %>

          <% if (todayAttendance.status === 'checked_in') { %>
            <textarea id="checkoutNote" class="note-input" placeholder="Catatan check-out (opsional)"></textarea>
            <input id="checkoutPhoto" class="note-input" type="file" accept="image/*" capture="user" onchange="updatePhotoInfo('checkoutPhoto', 'checkoutPhotoInfo', 'checkoutPhotoPreviewWrap', 'checkoutPhotoPreview')">
            <div id="checkoutPhotoInfo" class="photo-help">Belum ada foto dipilih. Foto wajib untuk check-out.</div>
            <div id="checkoutPhotoStatus" class="photo-help" style="display:inline-block;padding:4px 10px;border-radius:999px;background:rgba(239,68,68,0.18);color:#fecaca">Foto wajib</div>
            <div style="display:flex;gap:8px;margin-top:8px">
              <button type="button" onclick="document.getElementById('checkoutPhoto').click()" class="btn btn-p btn-sm">Pilih/Ganti Foto</button>
              <button type="button" onclick="clearSelectedPhoto('checkoutPhoto')" class="btn btn-d btn-sm">Hapus Foto</button>
            </div>
            <div id="checkoutPhotoPreviewWrap" style="display:none;margin-top:8px">
              <div class="photo-help" style="margin-bottom:6px">Preview foto final yang akan dikirim:</div>
              <img id="checkoutPhotoPreview" alt="Preview foto check-out" style="width:100%;max-width:240px;border-radius:12px;border:1px solid var(--border);object-fit:cover">
            </div>
            <button id="checkoutSubmitBtn" class="btn btn-d btn-sm" style="width:100%;margin-top:12px;opacity:0.55;cursor:not-allowed" onclick="checkout(event)" disabled>
              <i class="bi bi-door-open"></i> Check-out Sekarang
            </button>
          <% } %>

        <% } else { %>
          <span class="status-badge status-not-checked-in">✗ Belum Check-in</span>
          <p style="color: var(--muted); margin: 16px 0;">Silakan lakukan check-in untuk memulai hari kerja Anda.</p>
          
          <textarea id="checkinNote" class="note-input" placeholder="Catatan check-in (opsional)"></textarea>
          <input id="checkinPhoto" class="note-input" type="file" accept="image/*" capture="user" onchange="updatePhotoInfo('checkinPhoto', 'checkinPhotoInfo', 'checkinPhotoPreviewWrap', 'checkinPhotoPreview')">
          <div id="checkinPhotoInfo" class="photo-help">Belum ada foto dipilih. Foto wajib untuk check-in.</div>
          <div id="checkinPhotoStatus" class="photo-help" style="display:inline-block;padding:4px 10px;border-radius:999px;background:rgba(239,68,68,0.18);color:#fecaca">Foto wajib</div>
          <div style="display:flex;gap:8px;margin-top:8px">
            <button type="button" onclick="document.getElementById('checkinPhoto').click()" class="btn btn-p btn-sm">Pilih/Ganti Foto</button>
            <button type="button" onclick="clearSelectedPhoto('checkinPhoto')" class="btn btn-d btn-sm">Hapus Foto</button>
          </div>
          <div id="checkinPhotoPreviewWrap" style="display:none;margin-top:8px">
            <div class="photo-help" style="margin-bottom:6px">Preview foto final yang akan dikirim:</div>
            <img id="checkinPhotoPreview" alt="Preview foto check-in" style="width:100%;max-width:240px;border-radius:12px;border:1px solid var(--border);object-fit:cover">
          </div>
          <button id="checkinSubmitBtn" class="btn btn-s btn-sm" style="width:100%;margin-top:12px;opacity:0.55;cursor:not-allowed" onclick="checkin(event)" disabled>
            <i class="bi bi-check-circle"></i> Check-in Sekarang
          </button>
        <% } %>

        <div id="locationInfo" class="location-info" style="display: none;">
          📍 Mengambil lokasi GPS...
        </div>
      </div>
    </div>

    <!-- Monthly Summary -->
    <div class="stat-grid" style="grid-template-columns:repeat(4,1fr)">
      <div class="sc p">
        <i class="bi bi-calendar-month sc-icon"></i>
        <div class="sc-label">Total Hari</div>
        <div class="sc-val"><%= summary.total_days || 0 %></div>
        <div class="sc-sub">Bulan ini</div>
      </div>
      <div class="sc s">
        <i class="bi bi-check-circle sc-icon"></i>
        <div class="sc-label">Hari Lengkap</div>
        <div class="sc-val"><%= summary.completed_days || 0 %></div>
        <div class="sc-sub">Check-in & out</div>
      </div>
      <div class="sc p">
        <i class="bi bi-clock sc-icon"></i>
        <div class="sc-label">Total Jam</div>
        <div class="sc-val">
          <%= summary.total_minutes ? Math.floor(summary.total_minutes / 60) : 0 %>
        </div>
        <div class="sc-sub">Jam kerja</div>
      </div>
      <div class="sc s">
        <i class="bi bi-graph-up sc-icon"></i>
        <div class="sc-label">Rata-rata</div>
        <div class="sc-val">
          <%= summary.avg_minutes ? Math.floor(summary.avg_minutes / 60) : 0 %>
        </div>
        <div class="sc-sub">Jam/hari</div>
      </div>
    </div>

    <!-- Recent History -->
    <div class="card" style="margin-top:20px">
      <div class="card-hd">
        <h6><i class="bi bi-clock-history"></i> Riwayat Terakhir</h6>
      </div>
      <% if (history && history.length > 0) { %>
      <div class="tbl-wrap">
        <table class="dtbl">
          <thead>
            <tr>
              <th>Tanggal</th>
              <th>Check-in</th>
              <th>Check-out</th>
              <th>Durasi</th>
              <th>Status</th>
            </tr>
          </thead>
          <tbody>
            <% history.forEach(item => { %>
              <tr>
                <td class="fw6">
                  <%= new Date(item.check_in_time).toLocaleDateString('id-ID', { 
                    weekday: 'short', 
                    year: 'numeric', 
                    month: 'short', 
                    day: 'numeric' 
                  }) %>
                </td>
                <td><%= new Date(item.check_in_time).toLocaleTimeString('id-ID') %></td>
                <td>
                  <% if (item.check_out_time) { %>
                    <%= new Date(item.check_out_time).toLocaleTimeString('id-ID') %>
                  <% } else { %>
                    <span class="text-muted">-</span>
                  <% } %>
                </td>
                <td>
                  <% if (item.work_duration_minutes > 0) { %>
                    <%= Math.floor(item.work_duration_minutes / 60) %>j <%= item.work_duration_minutes % 60 %>m
                  <% } else { %>
                    <span class="text-muted">-</span>
                  <% } %>
                </td>
                <td>
                  <% if (item.status === 'checked_in') { %>
                    <span class="badge badge-w">Belum selesai</span>
                  <% } else { %>
                    <span class="badge badge-s">Selesai</span>
                  <% } %>
                </td>
              </tr>
            <% }) %>
          </tbody>
        </table>
      </div>
      <% } else { %>
      <div class="card-bd" style="text-align:center;padding:40px 20px">
        <p style="color:var(--muted)">Belum ada riwayat absensi</p>
      </div>
      <% } %>
    </div>

  </div>
</div>

<script>
  let currentLocation = null;
  const processedAttendancePhotos = {};
  const photoFieldConfig = {
    checkinPhoto: { infoId: 'checkinPhotoInfo', previewWrapId: 'checkinPhotoPreviewWrap', previewImgId: 'checkinPhotoPreview', statusId: 'checkinPhotoStatus', submitBtnId: 'checkinSubmitBtn' },
    checkoutPhoto: { infoId: 'checkoutPhotoInfo', previewWrapId: 'checkoutPhotoPreviewWrap', previewImgId: 'checkoutPhotoPreview', statusId: 'checkoutPhotoStatus', submitBtnId: 'checkoutSubmitBtn' }
  };

  function setPhotoStatus(statusId, text, mode = 'idle') {
    const el = document.getElementById(statusId);
    if (!el) return;
    const palette = {
      idle: ['rgba(239, 68, 68, 0.18)', '#fecaca'],
      waiting: ['rgba(245, 158, 11, 0.18)', '#fde68a'],
      processing: ['rgba(59, 130, 246, 0.18)', '#bfdbfe'],
      ready: ['rgba(16, 185, 129, 0.18)', '#bbf7d0'],
      error: ['rgba(239, 68, 68, 0.18)', '#fecaca']
    };
    const [bg, color] = palette[mode] || palette.idle;
    el.style.background = bg;
    el.style.color = color;
    el.textContent = text;
  }

  function setSubmitButtonState(buttonId, enabled) {
    const button = document.getElementById(buttonId);
    if (!button) return;
    button.disabled = !enabled;
    button.style.opacity = enabled ? '1' : '0.55';
    button.style.cursor = enabled ? 'pointer' : 'not-allowed';
  }

  function resetPhotoPreview(previewWrapId, previewImgId) {
    const previewWrap = document.getElementById(previewWrapId);
    const previewImg = document.getElementById(previewImgId);
    if (previewImg && previewImg.dataset.objectUrl) {
      URL.revokeObjectURL(previewImg.dataset.objectUrl);
      delete previewImg.dataset.objectUrl;
    }
    if (previewImg) previewImg.removeAttribute('src');
    if (previewWrap) previewWrap.style.display = 'none';
  }

  function setPhotoPreview(previewWrapId, previewImgId, file) {
    const previewWrap = document.getElementById(previewWrapId);
    const previewImg = document.getElementById(previewImgId);
    if (!previewWrap || !previewImg) return;

    resetPhotoPreview(previewWrapId, previewImgId);
    const objectUrl = URL.createObjectURL(file);
    previewImg.src = objectUrl;
    previewImg.dataset.objectUrl = objectUrl;
    previewWrap.style.display = 'block';
  }

  function updatePhotoInfo(inputId, infoId, previewWrapId, previewImgId) {
    const input = document.getElementById(inputId);
    const info = document.getElementById(infoId);
    const config = getPhotoState(inputId);
    if (!input || !info) return;
    const file = input.files && input.files[0];
    delete processedAttendancePhotos[inputId];
    if (!file) {
      info.textContent = 'Belum ada foto dipilih.';
      resetPhotoPreview(previewWrapId, previewImgId);
      if (config) setPhotoStatus(config.statusId, 'Foto wajib', 'idle');
      if (config) setSubmitButtonState(config.submitBtnId, false);
      return;
    }
    info.textContent = `Foto dipilih: ${file.name} (${Math.round(file.size / 1024)} KB)`;
    if (config) setPhotoStatus(config.statusId, 'Menyiapkan preview', 'processing');
    refreshPhotoPreview(inputId).catch((error) => {
      info.textContent = error.message;
      resetPhotoPreview(previewWrapId, previewImgId);
      if (config) setPhotoStatus(config.statusId, 'Preview gagal', 'error');
    });
  }

  function getPhotoState(inputId) {
    return photoFieldConfig[inputId];
  }

  function clearSelectedPhoto(inputId) {
    const config = getPhotoState(inputId);
    const input = document.getElementById(inputId);
    if (!config || !input) return;
    input.value = '';
    delete processedAttendancePhotos[inputId];
    const info = document.getElementById(config.infoId);
    if (info) info.textContent = 'Belum ada foto dipilih. Foto wajib untuk absensi.';
    resetPhotoPreview(config.previewWrapId, config.previewImgId);
    setPhotoStatus(config.statusId, 'Foto wajib', 'idle');
    setSubmitButtonState(config.submitBtnId, false);
  }

  async function refreshPhotoPreview(inputId, force = false) {
    const config = getPhotoState(inputId);
    const input = document.getElementById(inputId);
    const info = config ? document.getElementById(config.infoId) : null;
    const file = input && input.files && input.files[0];
    if (!config || !info) return null;

    if (!file) {
      info.textContent = 'Belum ada foto dipilih. Foto wajib untuk absensi.';
      resetPhotoPreview(config.previewWrapId, config.previewImgId);
      delete processedAttendancePhotos[inputId];
      setPhotoStatus(config.statusId, 'Foto wajib', 'idle');
      setSubmitButtonState(config.submitBtnId, false);
      return null;
    }

    if (!currentLocation) {
      info.textContent = `Foto dipilih: ${file.name} (${Math.round(file.size / 1024)} KB). Preview menunggu lokasi GPS.`;
      resetPhotoPreview(config.previewWrapId, config.previewImgId);
      setPhotoStatus(config.statusId, 'Menunggu GPS', 'waiting');
      setSubmitButtonState(config.submitBtnId, false);
      return null;
    }

    const cacheKey = [file.name, file.size, file.lastModified, currentLocation.lat, currentLocation.lng].join('|');
    const cached = processedAttendancePhotos[inputId];
    if (!force && cached && cached.cacheKey === cacheKey && cached.file) {
      setPhotoPreview(config.previewWrapId, config.previewImgId, cached.file);
      info.textContent = `Preview siap: ${cached.file.name} (${Math.round(cached.file.size / 1024)} KB).`;
      setPhotoStatus(config.statusId, 'Preview siap dikirim', 'ready');
      setSubmitButtonState(config.submitBtnId, true);
      return cached.file;
    }

    info.textContent = 'Memproses foto untuk preview...';
    setPhotoStatus(config.statusId, 'Memproses foto', 'processing');
    setSubmitButtonState(config.submitBtnId, false);
    const processedFile = await processAttendancePhotoFile(file, currentLocation);
    processedAttendancePhotos[inputId] = { cacheKey, file: processedFile };
    setPhotoPreview(config.previewWrapId, config.previewImgId, processedFile);
    info.textContent = `Preview siap: ${processedFile.name} (${Math.round(processedFile.size / 1024)} KB).`;
    setPhotoStatus(config.statusId, 'Preview siap dikirim', 'ready');
    setSubmitButtonState(config.submitBtnId, true);
    return processedFile;
  }

  function refreshAllPhotoPreviews() {
    Object.keys(photoFieldConfig).forEach((inputId) => {
      refreshPhotoPreview(inputId, true).catch(() => {});
    });
  }

  function buildAttendanceFormData(location, note, photoInputId) {
    const formData = new FormData();
    formData.append('lat', location.lat);
    formData.append('lng', location.lng);
    formData.append('note', note);

    return getProcessedAttendancePhoto(photoInputId, location).then((processedPhoto) => {
      if (processedPhoto) {
        formData.append('photo', processedPhoto);
      }
      return formData;
    });
  }

  function loadImageFromFile(file) {
    return new Promise((resolve, reject) => {
      const img = new Image();
      const objectUrl = URL.createObjectURL(file);
      img.onload = () => {
        URL.revokeObjectURL(objectUrl);
        resolve(img);
      };
      img.onerror = () => {
        URL.revokeObjectURL(objectUrl);
        reject(new Error('Gagal membaca foto yang dipilih'));
      };
      img.src = objectUrl;
    });
  }

  function canvasToBlob(canvas, type, quality) {
    return new Promise((resolve, reject) => {
      const fallback = () => {
        try {
          const dataUrl = canvas.toDataURL(type, quality);
          const parts = dataUrl.split(',');
          if (parts.length < 2) throw new Error('Gagal memproses foto absensi');
          const mime = (parts[0].match(/data:(.*?);base64/) || [])[1] || type || 'image/jpeg';
          const binary = atob(parts[1]);
          const len = binary.length;
          const bytes = new Uint8Array(len);
          for (let i = 0; i < len; i++) bytes[i] = binary.charCodeAt(i);
          resolve(new Blob([bytes], { type: mime }));
        } catch (e) {
          reject(new Error('Gagal memproses foto absensi'));
        }
      };

      if (typeof canvas.toBlob !== 'function') return fallback();

      canvas.toBlob((blob) => {
        if (blob) return resolve(blob);
        fallback();
      }, type, quality);
    });
  }

  function buildWatermarkLines(location) {
    const timestamp = new Date().toLocaleString('id-ID', {
      timeZone: '<%= settings.timezone %>',
      weekday: 'long',
      year: 'numeric',
      month: 'long',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
    return [
      'Absensi Kasir',
      `Waktu: ${timestamp}`,
      `GPS: ${location.lat}, ${location.lng}`
    ];
  }

  async function processAttendancePhotoFile(originalFile, location) {
    const image = await loadImageFromFile(originalFile);
    const maxWidth = 1280;
    const scale = Math.min(1, maxWidth / image.width);
    const width = Math.max(1, Math.round(image.width * scale));
    const height = Math.max(1, Math.round(image.height * scale));
    const watermarkLines = buildWatermarkLines(location);
    const fontSize = Math.max(20, Math.round(width * 0.028));
    const lineGap = Math.round(fontSize * 0.35);
    const padding = Math.round(fontSize * 0.8);
    const overlayHeight = Math.round((fontSize + lineGap) * watermarkLines.length + padding * 1.6);

    const canvas = document.createElement('canvas');
    canvas.width = width;
    canvas.height = height;

    const ctx = canvas.getContext('2d');
    ctx.drawImage(image, 0, 0, width, height);

    ctx.fillStyle = 'rgba(0, 0, 0, 0.55)';
    ctx.fillRect(0, height - overlayHeight, width, overlayHeight);

    ctx.fillStyle = '#ffffff';
    ctx.font = `600 ${fontSize}px Arial, sans-serif`;
    ctx.textBaseline = 'top';

    let textY = height - overlayHeight + padding;
    watermarkLines.forEach((line, index) => {
      if (index > 0) {
        ctx.font = `500 ${Math.max(16, Math.round(fontSize * 0.88))}px Arial, sans-serif`;
      } else {
        ctx.font = `600 ${fontSize}px Arial, sans-serif`;
      }
      ctx.fillText(line, padding, textY);
      textY += (index > 0 ? Math.max(16, Math.round(fontSize * 0.88)) : fontSize) + lineGap;
    });

    const blob = await canvasToBlob(canvas, 'image/jpeg', 0.82);
    const baseName = (originalFile.name || 'attendance-photo').replace(/\.[^.]+$/, '');
    return new File([blob], `${baseName}-wm.jpg`, { type: 'image/jpeg' });
  }

  async function getProcessedAttendancePhoto(photoInputId, location) {
    currentLocation = location;
    const processed = await refreshPhotoPreview(photoInputId);
    if (processed) return processed;

    const input = document.getElementById(photoInputId);
    const originalFile = input && input.files && input.files[0];
    if (!originalFile) return null;
    return processAttendancePhotoFile(originalFile, location);
  }

  function getLocation() {
    return new Promise((resolve, reject) => {
      if (!navigator.geolocation) {
        reject(new Error('Geolocation tidak didukung browser Anda'));
        return;
      }

      const locationInfo = document.getElementById('locationInfo');
      locationInfo.style.display = 'block';
      locationInfo.textContent = '📍 Mengambil lokasi GPS...';

      navigator.geolocation.getCurrentPosition(
        (position) => {
          currentLocation = {
            lat: position.coords.latitude.toString(),
            lng: position.coords.longitude.toString()
          };
          locationInfo.textContent = `📍 Lokasi: ${currentLocation.lat}, ${currentLocation.lng}`;
        refreshAllPhotoPreviews();
          resolve(currentLocation);
        },
        (error) => {
          locationInfo.textContent = '⚠️ Gagal mendapatkan lokasi GPS';
          locationInfo.style.color = '#ef4444';
          reject(error);
        },
        {
          enableHighAccuracy: true,
          timeout: 10000,
          maximumAge: 0
        }
      );
    });
  }

  async function checkin(evt) {
    const btn = evt.currentTarget;
    if (!document.getElementById('checkinPhoto')?.files?.[0]) {
      alert('Foto check-in wajib diunggah sebelum absensi.');
      return;
    }
    try {
      btn.disabled = true;
      btn.innerHTML = '<i class="bi bi-hourglass-split"></i> Memproses...';

      const location = await getLocation();
      const note = document.getElementById('checkinNote').value.trim();

      const response = await fetch('/admin/cashiers/attendance/checkin', {
        method: 'POST',
        body: await buildAttendanceFormData(location, note, 'checkinPhoto')
      });

      const result = await response.json();
      
      if (result.success) {
        alert('✓ ' + result.message);
        window.location.reload();
      } else {
        alert('✗ ' + result.message);
        btn.disabled = false;
        btn.innerHTML = '<i class="bi bi-check-circle"></i> Check-in Sekarang';
      }
    } catch (error) {
      alert('Gagal check-in: ' + error.message);
      btn.disabled = false;
      btn.innerHTML = '<i class="bi bi-check-circle"></i> Check-in Sekarang';
    }
  }

  async function checkout(evt) {
    const btn = evt.currentTarget;
    if (!document.getElementById('checkoutPhoto')?.files?.[0]) {
      alert('Foto check-out wajib diunggah sebelum absensi.');
      return;
    }
    try {
      btn.disabled = true;
      btn.innerHTML = '<i class="bi bi-hourglass-split"></i> Memproses...';

      const location = await getLocation();
      const note = document.getElementById('checkoutNote').value.trim();

      const response = await fetch('/admin/cashiers/attendance/checkout', {
        method: 'POST',
        body: await buildAttendanceFormData(location, note, 'checkoutPhoto')
      });

      const result = await response.json();
      
      if (result.success) {
        alert('✓ ' + result.message);
        window.location.reload();
      } else {
        alert('✗ ' + result.message);
        btn.disabled = false;
        btn.innerHTML = '<i class="bi bi-door-open"></i> Check-out Sekarang';
      }
    } catch (error) {
      alert('Gagal check-out: ' + error.message);
      btn.disabled = false;
      btn.innerHTML = '<i class="bi bi-door-open"></i> Check-out Sekarang';
    }
  }

  window.addEventListener('load', () => {
    getLocation().catch(() => {});
  });
</script>
</body>
</html>
