<?php
session_start();
require_once 'config.php';

// Check if user is logged in
if (!isset($_SESSION['token'])) {
  header('Location: login.php');
  exit;
}

$token = $_SESSION['token'];
$user_data = $_SESSION['user_data'] ?? [];

// Test token validity dengan API profil
$profile_test = api_get_profil($token);
if (!$profile_test['success']) {
  // Token tidak valid, coba login fresh
  $login_result = api_login('Widia', 'qwerty5*');
  if ($login_result['success']) {
    $token = $login_result['data']['token'];
    $_SESSION['token'] = $token;
    $_SESSION['user_data'] = $login_result['data'];
    $user_data = $login_result['data'];
  } else {
    // Login fresh gagal, redirect ke login
    header('Location: login.php');
    exit;
  }
}

// Get user profile data
$profile_result = api_get_profil($token);
$profile_data = $profile_result['success'] ? $profile_result['data'] : [];

// Get today's attendance
$presensi_today_result = api_get_presensi_today($token);
$presensi_today = $presensi_today_result['success'] ? $presensi_today_result['data'] : [];

// Get news/berita
$berita_result = api_get_berita($token);
$berita_data = $berita_result['success'] ? $berita_result['data'] : [];

// Debug berita data
error_log("Token: " . $token);
error_log("Berita Result: " . json_encode($berita_result));
error_log("Berita Data: " . json_encode($berita_data));


// Get libur data
$libur_result = api_get_libur($token);
$libur_data = $libur_result['success'] ? $libur_result['data'] : [];

// Get cuti data
$cuti_result = api_get_cuti($token);
$cuti_data = $cuti_result['success'] ? $cuti_result['data'] : [];

// Get lembur data
$lembur_result = api_get_lembur($token);
$lembur_data = $lembur_result['success'] ? $lembur_result['data'] : [];

// Get riwayat presensi (untuk statistik)
$presensi_result = api_get_presensi($token);
$presensi_data = $presensi_result['success'] ? $presensi_result['data'] : [];

// Extract user info from API response - try multiple possible structures
$pegawai = $profile_data['pegawai'] ?? $profile_data['data']['pegawai'] ?? $profile_data['data'] ?? [];
$user_name = $pegawai['nama_lengkap'] ?? $pegawai['nama'] ?? $user_data['nama'] ?? $user_data['nama_lengkap'] ?? 'User';
$user_jabatan = $pegawai['jabatan']['nama_jabatan'] ?? $pegawai['jabatan'] ?? $user_data['jabatan'] ?? $user_data['nama_jabatan'] ?? 'Karyawan';
$user_id = $pegawai['nip'] ?? $pegawai['id'] ?? $user_data['id'] ?? $user_data['nip'] ?? '';
$user_photo = $pegawai['photo'] ?? $pegawai['foto'] ?? $user_data['foto'] ?? $user_data['photo'] ?? '';
$unit_kerja = $pegawai['unit_kerja']['nama_unit_kerja'] ?? $pegawai['unit_kerja'] ?? $user_data['unit_kerja'] ?? 'Unit Kerja';
$kantor = $pegawai['kantor']['nama_kantor'] ?? $pegawai['kantor'] ?? $user_data['kantor'] ?? 'Kantor Pusat';
$alamat_kantor = $pegawai['kantor']['alamat_kantor'] ?? $pegawai['alamat_kantor'] ?? $user_data['alamat_kantor'] ?? '';
$kode_kantor = $pegawai['kantor']['kode_kantor'] ?? $pegawai['kode_kantor'] ?? $user_data['kode_kantor'] ?? '';

// Debug user data
error_log("Profile Data: " . json_encode($profile_data));
error_log("Pegawai Data: " . json_encode($pegawai));
error_log("User Data: " . json_encode($user_data));
error_log("User Name: " . $user_name);
error_log("Kantor: " . $kantor);
error_log("Unit Kerja: " . $unit_kerja);

// Extract attendance info from presensi_today (00:00:00 dari DB ≠ sudah rekam)
$presensi_data_today = $presensi_today['data'] ?? [];
$masuk_time          = $presensi_data_today['jam_masuk'] ?? null;
$istirahat_mulai     = $presensi_data_today['mulai_istirahat'] ?? null;
$istirahat_selesai   = $presensi_data_today['beres_istirahat'] ?? null;
$pulang_time         = $presensi_data_today['jam_pulang'] ?? null;

$masuk_ok            = presensi_waktu_terisi($masuk_time);
$istirahat_ok        = presensi_waktu_terisi($istirahat_mulai);
$istirahat_selesai_ok = presensi_waktu_terisi($istirahat_selesai);
$pulang_ok           = presensi_waktu_terisi($pulang_time);

// Extract work schedule info from profile
$jadwal = $pegawai['jadwal'] ?? [];
$jam_masuk = $jadwal['masuk'] ?? '08:00';
$jam_pulang = $jadwal['pulang'] ?? '17:00';
$jam_istirahat = $jadwal['istirahat'] ?? '12:00';
$toleransi_masuk = $jadwal['toleransi_masuk'] ?? '15';
$toleransi_pulang = $jadwal['toleransi_pulang'] ?? '15';

// Extract statistics
$total_presensi = count($presensi_data);
$presensi_bulan_ini = 0;
$cuti_tersisa = $pegawai['cuti_tersisa'] ?? 0;
$lembur_bulan_ini = 0;

// Calculate monthly attendance
$current_month = date('Y-m');
foreach ($presensi_data as $presensi) {
  if (isset($presensi['tanggal']) && strpos($presensi['tanggal'], $current_month) === 0) {
    $presensi_bulan_ini++;
  }
}

// Calculate monthly overtime
foreach ($lembur_data as $lembur) {
  if (isset($lembur['tanggal']) && strpos($lembur['tanggal'], $current_month) === 0) {
    $lembur_bulan_ini++;
  }
}

// Calculate work days this month
$work_days_this_month = 0;
$current_date = new DateTime();
$current_month_days = $current_date->format('t');
for ($day = 1; $day <= $current_month_days; $day++) {
  $date = new DateTime($current_month . '-' . str_pad($day, 2, '0', STR_PAD_LEFT));
  $day_of_week = $date->format('N'); // 1 = Monday, 7 = Sunday
  if ($day_of_week >= 1 && $day_of_week <= 5) { // Monday to Friday
    $work_days_this_month++;
  }
}

// Helper function untuk format tanggal Indonesia
function formatTanggalIndonesia($tanggal = null, $format = 'l, d F Y')
{
  $hari = ['Sunday' => 'Minggu', 'Monday' => 'Senin', 'Tuesday' => 'Selasa', 'Wednesday' => 'Rabu', 'Thursday' => 'Kamis', 'Friday' => 'Jumat', 'Saturday' => 'Sabtu'];
  $bulan = ['January' => 'Januari', 'February' => 'Februari', 'March' => 'Maret', 'April' => 'April', 'May' => 'Mei', 'June' => 'Juni', 'July' => 'Juli', 'August' => 'Agustus', 'September' => 'September', 'October' => 'Oktober', 'November' => 'November', 'December' => 'Desember'];

  if ($tanggal) {
    $tanggal_inggris = date($format, strtotime($tanggal));
  } else {
    $tanggal_inggris = date($format);
  }

  $tanggal_indonesia = str_replace(array_keys($hari), array_values($hari), str_replace(array_keys($bulan), array_values($bulan), $tanggal_inggris));
  return $tanggal_indonesia;
}
?>
<!DOCTYPE html>
<html lang="id">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover, maximum-scale=1">
  <meta name="theme-color" content="#F2F2F7">
  <meta name="color-scheme" content="light">
  <meta name="mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="default">
  <title>Bank BIJ — Dashboard</title>
  <link rel="icon" type="image/png" href="<?php echo htmlspecialchars(site_public_asset('assets/images/bij_logo.png')); ?>">
  <link rel="stylesheet" href="<?php echo asset('css/style.css'); ?>">
  <link rel="stylesheet" href="<?php echo asset('css/tailwind.css'); ?>">
  <link rel="stylesheet" href="<?php echo asset('css/ios-app.css'); ?>">
  <link rel="stylesheet" href="<?php echo asset('fa-7.1.0-web/css/all.min.css'); ?>">

</head>

<body class="ios-app">
  <div class="mobile-frame p-4">
    <header class="ios-screen-head">
      <div class="ios-screen-head__row">
        <div class="bank-logo flex-shrink-0">
          <img src="<?php echo asset('logo_bij3.png'); ?>" alt="Logo Bank BIJ">
        </div>
        <div class="ios-head-meta">
          <h1 class="ios-head-brand">BPR <span class="ios-accent">Intan Jabar</span></h1>
          <p class="ios-head-page">Dashboard Presensi</p>
        </div>
        <div class="ios-head-user">
          <span class="ios-head-name"><?php echo htmlspecialchars($user_name); ?></span>
          <span class="ios-head-role"><?php echo htmlspecialchars($user_jabatan); ?></span>
        </div>
      </div>
    </header>

    <!-- Tanggal dan Waktu -->
    <div class="dashboard-card p-4 mb-4 text-center">
      <p class="text-gray-500 text-sm" id="current-date"><?php echo formatTanggalIndonesia(); ?></p>
      <p class="text-2xl font-bold text-gray-800" id="current-time">08:45:32</p>
    </div>

    <!-- Tombol Aksi -->
    <div class="grid grid-cols-3 gap-4 mb-0">
      <a href="rekam.php" class="action-btn dashboard-card p-4 text-center block">
        <div class="w-12 h-12 mx-auto mb-2 bg-blue-100 rounded-full flex items-center justify-center">
          <i class="fas fa-fingerprint text-blue-700 text-xl"></i>
        </div>
        <p class="text-sm font-medium text-gray-800">Rekam Kehadiran</p>
      </a>

      <a href="cuti.php" class="action-btn dashboard-card p-4 text-center block">
        <div class="w-12 h-12 mx-auto mb-2 bg-amber-100 rounded-full flex items-center justify-center">
          <i class="fas fa-umbrella-beach text-amber-700 text-xl"></i>
        </div>
        <p class="text-sm font-medium text-gray-800">Cuti</p>
      </a>

      <a href="lembur.php" class="action-btn dashboard-card p-4 text-center block">
        <div class="w-12 h-12 mx-auto mb-2 bg-green-100 rounded-full flex items-center justify-center">
          <i class="fas fa-business-time text-green-700 text-xl"></i>
        </div>
        <p class="text-sm font-medium text-gray-800">Lembur</p>
      </a>
    </div>

    <!-- Informasi Jadwal Kerja -->
    <div class="dashboard-card p-4 mb-4">
      <h2 class="text-lg font-bold text-gray-800 mb-3">Informasi Jadwal Kerja</h2>
      <div class="grid grid-cols-2 gap-4">
        <div>
          <p class="text-sm text-gray-500">Jadwal Kerja :</p>
          <p class="text-sm font-semibold text-gray-800"><?php echo formatTanggalIndonesia(); ?></p>
          <p class="text-sm text-gray-800"><?php echo $jam_masuk; ?> - <?php echo $jam_pulang; ?></p>
          <?php if ($lembur_bulan_ini > 0): ?>
            <p class="text-sm text-amber-600"><?php echo $lembur_bulan_ini; ?> hari lembur bulan ini</p>
          <?php else: ?>
            <p class="text-sm text-gray-500">Tidak ada lembur</p>
          <?php endif; ?>
        </div>
        <div>
          <p class="text-sm text-gray-500">Lokasi Kerja :</p>
          <p class="text-sm font-semibold text-gray-800"><?php echo htmlspecialchars($kantor); ?></p>
          <?php if (!empty($alamat_kantor)): ?>
            <p class="text-sm text-gray-500"><?php echo htmlspecialchars($alamat_kantor); ?></p>
          <?php endif; ?>
        </div>
      </div>
    </div>

    <!-- Status Kehadiran Hari Ini -->
    <div class="dashboard-card p-4 mb-4">
      <h2 class="text-lg font-bold text-gray-800 mb-3">Status Kehadiran Hari Ini</h2>
      <div class="grid grid-cols-3 gap-2">
        <div class="status-card p-3 text-center rounded-lg border border-gray-200 <?php echo $masuk_ok ? 'active' : ''; ?>">
          <p class="text-sm text-gray-500">Masuk</p>
          <p class="font-bold text-gray-800"><?php echo $masuk_ok ? htmlspecialchars((string) $masuk_time) : '00:00'; ?></p>
          <p class="text-sm text-gray-500"><?php echo $masuk_ok ? '(sudah rekam)' : '(belum rekam)'; ?></p>
        </div>
        <div class="status-card p-3 text-center rounded-lg border border-gray-200 <?php echo $istirahat_ok ? 'active' : ''; ?>">
          <p class="text-sm text-gray-500">Istirahat</p>
          <p class="font-bold text-gray-800">
            <?php if ($istirahat_ok): ?>
              <?php echo htmlspecialchars((string) $istirahat_mulai); ?>
              <?php if ($istirahat_selesai_ok): ?>
                - <?php echo htmlspecialchars((string) $istirahat_selesai); ?>
              <?php endif; ?>
            <?php else: ?>
              00:00
            <?php endif; ?>
          </p>
          <p class="text-sm text-gray-500"><?php echo $istirahat_ok ? '(sudah rekam)' : '(belum rekam)'; ?></p>
        </div>
        <div class="status-card p-3 text-center rounded-lg border border-gray-200 <?php echo $pulang_ok ? 'active' : ''; ?>">
          <p class="text-sm text-gray-500">Pulang</p>
          <p class="font-bold text-gray-800"><?php echo $pulang_ok ? htmlspecialchars((string) $pulang_time) : '00:00'; ?></p>
          <p class="text-sm text-gray-500"><?php echo $pulang_ok ? '(sudah rekam)' : '(belum rekam)'; ?></p>
        </div>
      </div>
    </div>



    <!-- Informasi dan Pengumuman -->
    <div class="dashboard-card p-4 mb-4">
      <h2 class="text-lg font-bold text-gray-800 mb-3">Informasi dan Pengumuman</h2>
      <div class="space-y-3">
        <?php
        // Handle berita data structure - sama seperti di debug yang berhasil
        $berita_items = [];
        if ($berita_result['success'] && !empty($berita_result['data'])) {
          $data = $berita_result['data'];

          // Cek struktur data sama persis seperti di debug
          if (isset($data['data']) && is_array($data['data'])) {
            $berita_items = $data['data'];
          } elseif (is_array($data) && isset($data[0])) {
            $berita_items = $data;
          }
        }

        if (!empty($berita_items)):
          $berita_items = array_slice($berita_items, 0, 3);
          foreach ($berita_items as $index => $berita):
            $judul = htmlspecialchars($berita['judul'] ?? 'Pengumuman');
            $tanggal = htmlspecialchars($berita['tanggal'] ?? '');
            $isi_full = strip_tags($berita['isi'] ?? 'Tidak ada informasi');
            $isi_excerpt = strlen($isi_full) > 100 ? substr($isi_full, 0, 100) . '...' : $isi_full;
            $isi_excerpt = htmlspecialchars($isi_excerpt);
            $photoRaw = trim((string) ($berita['photo'] ?? ''));
            $photoUrl = uploads_berita_url($photoRaw);
            $berita_id = $berita['id'] ?? $berita['berita_id'] ?? $index; // ID berita untuk link detail

            // Debug log
            error_log("Berita $index: ID = " . ($berita['id'] ?? 'NO_ID') . ", Judul = " . $judul);
        ?>
            <div class="p-3 bg-blue-50 rounded-lg hover:bg-blue-100 transition-colors">
              <div class="flex items-start">
                <?php if ($photoUrl !== ''): ?>
                  <div class="w-16 h-16 bg-gray-200 rounded-lg mr-3 mt-1 flex-shrink-0 overflow-hidden">
                    <img src="<?php echo htmlspecialchars($photoUrl); ?>"
                      alt="<?php echo $judul; ?>"
                      class="w-full h-full object-cover"
                      onerror="this.style.display='none';">
                  </div>
                <?php else: ?>
                  <div class="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center mr-3 mt-1">
                    <i class="fas fa-info-circle text-blue-700"></i>
                  </div>
                <?php endif; ?>
                <div class="flex-1">
                  <div class="flex items-center mb-2">
                    <a href="detail-info.php?id=<?php echo $berita_id; ?>" class="font-medium text-blue-800 hover:text-blue-900 hover:underline">
                      <?php echo $judul; ?>
                    </a>
                  </div>
                  <?php if ($tanggal): ?>
                    <p class="text-xs text-gray-500 mb-2"><?php echo formatTanggalIndonesia($tanggal); ?></p>
                  <?php endif; ?>
                  <p class="text-sm text-gray-600"><?php echo $isi_excerpt; ?></p>
                </div>
              </div>
            </div>
          <?php endforeach; ?>
        <?php else: ?>
          <div class="p-4 bg-gray-50 rounded-lg text-center">
            <p class="text-gray-500 text-sm">Tidak ada pengumuman saat ini.</p>
          </div>
        <?php endif; ?>
      </div>
    </div>



    <!-- Footer -->
    <div class="text-center mt-4 ios-foot">
      <p>© 2024 Bank BIJ • v2.4.1</p>
      <a href="logout.php" class="inline-flex items-center justify-center mt-3">
        <i class="fas fa-sign-out-alt mr-2"></i> Logout
      </a>
    </div>
  </div>

  <script>
    // Update waktu dan tanggal secara real-time
    function updateDateTime() {
      const now = new Date();

      // Format tanggal
      const optionsDate = {
        weekday: 'long',
        year: 'numeric',
        month: 'long',
        day: 'numeric'
      };
      const formattedDate = now.toLocaleDateString('id-ID', optionsDate);
      document.getElementById('current-date').textContent = formattedDate;

      // Format waktu
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');
      document.getElementById('current-time').textContent = `${hours}:${minutes}:${seconds}`;
    }

    // Update waktu setiap detik
    setInterval(updateDateTime, 1000);
    updateDateTime(); // Panggil sekali saat pertama kali load


    // Simulasi status kehadiran aktif
    const statusCards = document.querySelectorAll('.status-card');
    statusCards.forEach(card => {
      card.addEventListener('click', function() {
        // Hanya untuk simulasi - dalam implementasi nyata ini akan dikontrol oleh status sebenarnya
        if (!this.classList.contains('active')) {
          statusCards.forEach(c => c.classList.remove('active'));
          this.classList.add('active');
        }
      });
    });
  </script>
</body>

</html>