<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <title><%= title %> - <%= company %></title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
  <style>
    body {
      background-color: #0f172a;
      color: #f8fafc;
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
      padding-top: 60px;
      padding-bottom: 80px;
      -webkit-tap-highlight-color: transparent;
    }

    /* Top Navigation */
    .top-nav {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      height: 60px;
      background: rgba(88, 28, 135, 0.9);
      backdrop-filter: blur(10px);
      border-bottom: 1px solid rgba(168, 85, 247, 0.3);
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 20px;
      z-index: 1000;
    }

    .top-nav-title {
      font-weight: 700;
      font-size: 18px;
      margin: 0;
      color: white;
    }

    .top-nav-btn {
      background: transparent;
      border: none;
      color: white;
      font-size: 20px;
      padding: 5px;
      text-decoration: none;
    }

    /* Bottom Navigation */
    .bottom-nav {
      position: fixed;
      bottom: 0;
      left: 0;
      right: 0;
      height: 65px;
      background: rgba(88, 28, 135, 0.95);
      backdrop-filter: blur(10px);
      border-top: 1px solid rgba(168, 85, 247, 0.3);
      display: flex;
      justify-content: space-around;
      align-items: center;
      z-index: 1000;
      padding-bottom: env(safe-area-inset-bottom);
    }

    .nav-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      color: #c4b5fd;
      text-decoration: none;
      font-size: 11px;
      font-weight: 500;
      transition: all 0.2s;
    }

    .nav-item i {
      font-size: 22px;
      margin-bottom: 2px;
    }

    .nav-item.active {
      color: white;
    }

    /* Cards */
    .t-card {
      background: #1e293b;
      border-radius: 16px;
      padding: 15px;
      margin-bottom: 15px;
      border: 1px solid #334155;
    }

    .badge-status {
      padding: 4px 10px;
      border-radius: 20px;
      font-size: 11px;
      font-weight: 600;
    }

    .btn-action {
      width: 100%;
      border-radius: 12px;
      padding: 10px;
      font-weight: 600;
      margin-top: 10px;
    }

    /* Stats Grid */
    .stat-grid {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 15px;
      margin-bottom: 20px;
    }

    .stat-box {
      background: #1e293b;
      border-radius: 16px;
      padding: 15px;
      border: 1px solid #334155;
      text-align: center;
    }

    .stat-box .val {
      font-size: 24px;
      font-weight: 700;
      margin: 5px 0 0 0;
    }

    .stat-box .lbl {
      font-size: 12px;
      color: #94a3b8;
    }
  </style>
</head>
<body>

  <div class="top-nav">
    <h1 class="top-nav-title"><%= title %></h1>
    <a href="/collector/logout" class="top-nav-btn" onclick="return confirm('Apakah Anda yakin ingin logout?')">
      <i class="bi bi-box-arrow-right"></i>
    </a>
  </div>

  <div class="container py-3">
    <div class="mb-4">
      <div class="text-secondary small">Absensi Kolektor</div>
      <div class="fs-5 fw-bold"><i class="bi bi-calendar-check text-purple me-2" style="color: #a78bfa;"></i><%= collectorName %></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, #7c3aed 0%, #a855f7 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 #a78bfa;">
        <div class="val" style="color: #a78bfa;"><%= 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 #3b82f6;">
        <div class="val text-primary"><%= 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" style="color: #a78bfa;" 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>
    <% } %>
  </div>

  <div class="bottom-nav">
    <a href="/collector/dashboard" class="nav-item">
      <i class="bi bi-house-door-fill"></i>
      <span>Beranda</span>
    </a>
    <a href="/collector/attendance" class="nav-item active">
      <i class="bi bi-calendar-check-fill"></i>
      <span>Absensi</span>
    </a>
  </div>

  <script>
    let currentLocation = null;

    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('/collector/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('/collector/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';
      }
    }

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