<%- include('partials/header') %>

<div class="mb-4">
  <div class="text-secondary small">Absensi Karyawan</div>
  <div class="fs-5 fw-bold"><i class="bi bi-calendar-check text-primary me-2"></i><%= techName %></div>
</div>

<% if (msg) { %>
  <div class="alert alert-<%= msg.type === 'error' ? 'danger' : 'success' %> alert-dismissible fade show rounded-4" role="alert" style="font-size: 13px;">
    <i class="bi bi-<%= msg.type === 'error' ? 'exclamation-circle' : 'check-circle' %>-fill me-2"></i>
    <%= msg.text %>
    <button type="button" class="btn-close btn-close-white" style="font-size: 10px;" data-bs-dismiss="alert"></button>
  </div>
<% } %>

<!-- Status Hari Ini -->
<div class="t-card" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border: none;">
  <h6 class="fw-bold mb-3" style="color: white;"><i class="bi bi-clock-history me-2"></i>Status Hari Ini</h6>
  
  <% if (todayAttendance) { %>
    <% if (todayAttendance.status === 'checked_in') { %>
      <span class="badge-status" style="background: rgba(16, 185, 129, 0.3); color: #10b981; border: 1px solid #10b981;">
        <i class="bi bi-check-circle-fill"></i> Sudah Check-in
      </span>
    <% } else { %>
      <span class="badge-status" style="background: rgba(100, 116, 139, 0.3); color: #cbd5e1; border: 1px solid #94a3b8;">
        <i class="bi bi-check-all"></i> Sudah Check-out
      </span>
    <% } %>

    <div style="background: rgba(255, 255, 255, 0.1); border-radius: 12px; padding: 15px; margin-top: 15px;">
      <div style="display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid rgba(255, 255, 255, 0.1);">
        <span style="color: rgba(255, 255, 255, 0.7); font-size: 13px;">Check-in</span>
        <span style="color: white; font-weight: 600; font-size: 13px;">
          <%= new Date(todayAttendance.check_in_time).toLocaleTimeString('id-ID', {hour: '2-digit', minute: '2-digit'}) %>
        </span>
      </div>

      <% if (todayAttendance.check_out_time) { %>
        <div style="display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid rgba(255, 255, 255, 0.1);">
          <span style="color: rgba(255, 255, 255, 0.7); font-size: 13px;">Check-out</span>
          <span style="color: white; font-weight: 600; font-size: 13px;">
            <%= new Date(todayAttendance.check_out_time).toLocaleTimeString('id-ID', {hour: '2-digit', minute: '2-digit'}) %>
          </span>
        </div>
        <div style="display: flex; justify-content: space-between; padding: 8px 0;">
          <span style="color: rgba(255, 255, 255, 0.7); font-size: 13px;">Durasi Kerja</span>
          <span style="color: white; font-weight: 600; font-size: 13px;">
            <%= Math.floor(todayAttendance.work_duration_minutes / 60) %> jam <%= todayAttendance.work_duration_minutes % 60 %> menit
          </span>
        </div>
      <% } %>

      <% if (todayAttendance.check_in_note) { %>
        <div style="padding: 8px 0; border-top: 1px solid rgba(255, 255, 255, 0.1); margin-top: 8px;">
          <span style="color: rgba(255, 255, 255, 0.7); font-size: 12px;">Catatan Check-in:</span>
          <div style="color: white; font-size: 13px; margin-top: 4px;"><%= todayAttendance.check_in_note %></div>
        </div>
      <% } %>

      <% if (todayAttendance.check_out_note) { %>
        <div style="padding: 8px 0; border-top: 1px solid rgba(255, 255, 255, 0.1); margin-top: 8px;">
          <span style="color: rgba(255, 255, 255, 0.7); font-size: 12px;">Catatan Check-out:</span>
          <div style="color: white; font-size: 13px; margin-top: 4px;"><%= todayAttendance.check_out_note %></div>
        </div>
      <% } %>
    </div>

    <% if (todayAttendance.status === 'checked_in') { %>
      <textarea id="checkoutNote" class="form-control mt-3" placeholder="Catatan check-out (opsional)" rows="2" style="background: rgba(255, 255, 255, 0.1); border: 1px solid rgba(255, 255, 255, 0.2); color: white; font-size: 13px;"></textarea>
      <button class="btn btn-danger btn-action mt-2" onclick="checkout()">
        <i class="bi bi-box-arrow-right me-2"></i>Check-out Sekarang
      </button>
    <% } %>

  <% } else { %>
    <span class="badge-status" style="background: rgba(239, 68, 68, 0.3); color: #ef4444; border: 1px solid #ef4444;">
      <i class="bi bi-x-circle-fill"></i> Belum Check-in
    </span>
    <p style="color: rgba(255, 255, 255, 0.8); margin: 15px 0 0 0; font-size: 13px;">
      Silakan lakukan check-in untuk memulai hari kerja Anda.
    </p>
    
    <textarea id="checkinNote" class="form-control mt-3" placeholder="Catatan check-in (opsional)" rows="2" style="background: rgba(255, 255, 255, 0.1); border: 1px solid rgba(255, 255, 255, 0.2); color: white; font-size: 13px;"></textarea>
    <button class="btn btn-success btn-action mt-2" onclick="checkin()">
      <i class="bi bi-box-arrow-in-right me-2"></i>Check-in Sekarang
    </button>
  <% } %>

  <div id="locationInfo" style="display: none; font-size: 11px; color: rgba(255, 255, 255, 0.7); margin-top: 10px; padding: 8px; background: rgba(0, 0, 0, 0.2); border-radius: 8px;">
    <i class="bi bi-geo-alt-fill"></i> Mengambil lokasi GPS...
  </div>
</div>

<!-- Ringkasan Bulan Ini -->
<h6 class="mb-3 text-secondary fw-bold text-uppercase" style="font-size: 13px; letter-spacing: 1px;">
  <i class="bi bi-calendar3 me-1"></i>Ringkasan Bulan Ini
</h6>

<div class="stat-grid">
  <div class="stat-box" style="border-left: 3px solid #3b82f6;">
    <div class="val text-primary"><%= summary.total_days || 0 %></div>
    <div class="lbl">Total Hari</div>
  </div>
  <div class="stat-box" style="border-left: 3px solid #10b981;">
    <div class="val text-success"><%= summary.completed_days || 0 %></div>
    <div class="lbl">Hari Lengkap</div>
  </div>
  <div class="stat-box" style="border-left: 3px solid #f59e0b;">
    <div class="val text-warning"><%= summary.total_minutes ? Math.floor(summary.total_minutes / 60) : 0 %></div>
    <div class="lbl">Total Jam</div>
  </div>
  <div class="stat-box" style="border-left: 3px solid #8b5cf6;">
    <div class="val" style="color: #a78bfa;"><%= summary.avg_minutes ? Math.floor(summary.avg_minutes / 60) : 0 %></div>
    <div class="lbl">Rata-rata Jam</div>
  </div>
</div>

<!-- Riwayat Terakhir -->
<h6 class="mb-3 text-secondary fw-bold text-uppercase" style="font-size: 13px; letter-spacing: 1px;">
  <i class="bi bi-clock-history me-1"></i>Riwayat Terakhir
</h6>

<% if (history && history.length > 0) { %>
  <% history.forEach(item => { %>
    <div class="t-card">
      <div class="fw-bold mb-2" style="font-size: 14px; color: #f8fafc;">
        <%= new Date(item.check_in_time).toLocaleDateString('id-ID', { 
          weekday: 'long', 
          day: 'numeric',
          month: 'long'
        }) %>
      </div>
      
      <div class="text-secondary mb-1" style="font-size: 12px;">
        <i class="bi bi-box-arrow-in-right text-success me-1"></i>
        Check-in: <%= new Date(item.check_in_time).toLocaleTimeString('id-ID', {hour: '2-digit', minute: '2-digit'}) %>
      </div>
      
      <% if (item.check_out_time) { %>
        <div class="text-secondary mb-1" style="font-size: 12px;">
          <i class="bi bi-box-arrow-right text-danger me-1"></i>
          Check-out: <%= new Date(item.check_out_time).toLocaleTimeString('id-ID', {hour: '2-digit', minute: '2-digit'}) %>
        </div>
        <div class="text-secondary" style="font-size: 12px;">
          <i class="bi bi-clock text-primary me-1"></i>
          Durasi: <%= Math.floor(item.work_duration_minutes / 60) %> jam <%= item.work_duration_minutes % 60 %> menit
        </div>
      <% } else { %>
        <div class="text-danger" style="font-size: 12px;">
          <i class="bi bi-exclamation-triangle-fill me-1"></i>
          Belum check-out
        </div>
      <% } %>
    </div>
  <% }) %>
<% } else { %>
  <div class="text-center py-5">
    <i class="bi bi-inbox text-secondary" style="font-size: 40px;"></i>
    <p class="text-secondary mt-2 small">Belum ada riwayat absensi</p>
  </div>
<% } %>

<%- include('partials/bottom_nav') %>

<script>
  let currentLocation = null;

  // Get current 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.innerHTML = '<i class="bi bi-geo-alt-fill"></i> Mengambil lokasi GPS...';

      navigator.geolocation.getCurrentPosition(
        (position) => {
          currentLocation = {
            lat: position.coords.latitude.toString(),
            lng: position.coords.longitude.toString()
          };
          locationInfo.innerHTML = `<i class="bi bi-geo-alt-fill text-success"></i> Lokasi berhasil didapat`;
          resolve(currentLocation);
        },
        (error) => {
          locationInfo.innerHTML = '<i class="bi bi-exclamation-triangle-fill text-danger"></i> Gagal mendapatkan lokasi GPS';
          reject(error);
        },
        {
          enableHighAccuracy: true,
          timeout: 10000,
          maximumAge: 0
        }
      );
    });
  }

  async function checkin() {
    try {
      const btn = event.target;
      btn.disabled = true;
      btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Memproses...';

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

      const response = await fetch('/tech/attendance/checkin', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          lat: location.lat,
          lng: location.lng,
          note: note
        })
      });

      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-box-arrow-in-right me-2"></i>Check-in Sekarang';
      }
    } catch (error) {
      alert('Gagal check-in: ' + error.message);
      event.target.disabled = false;
      event.target.innerHTML = '<i class="bi bi-box-arrow-in-right me-2"></i>Check-in Sekarang';
    }
  }

  async function checkout() {
    try {
      const btn = event.target;
      btn.disabled = true;
      btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Memproses...';

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

      const response = await fetch('/tech/attendance/checkout', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          lat: location.lat,
          lng: location.lng,
          note: note
        })
      });

      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-box-arrow-right me-2"></i>Check-out Sekarang';
      }
    } catch (error) {
      alert('Gagal check-out: ' + error.message);
      event.target.disabled = false;
      event.target.innerHTML = '<i class="bi bi-box-arrow-right me-2"></i>Check-out Sekarang';
    }
  }

  // Auto-get location on page load
  window.addEventListener('load', () => {
    getLocation().catch(() => {});
  });
</script>