<?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
$profile_test = api_get_profil($token);
if (!$profile_test['success']) {
    $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 {
        header('Location: login.php');
        exit;
    }
}

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

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

// Extract user info
$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';

// 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 — Lembur</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">Lembur</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>

        <nav class="ios-nav-back" aria-label="Navigasi">
            <a href="dashboard.php"><i class="fas fa-chevron-left" aria-hidden="true"></i> Dashboard</a>
        </nav>


        <!-- Daftar Lembur -->
        <div class="dashboard-card p-4">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-lg font-bold text-gray-800">Daftar Lembur</h2>
                <div class="flex items-center space-x-2">
                    <span class="text-sm text-gray-500">Total: <span id="totalLembur">0</span> hari</span>
                    <button onclick="refreshLembur()" class="p-2 text-gray-500 hover:text-gray-700 transition-colors">
                        <i class="fas fa-sync-alt"></i>
                    </button>
                </div>
            </div>

            <div id="lemburList">
                <?php
                // Check if we have valid lembur data
                $has_data = false;
                $lembur_items = [];

                if (!empty($lembur_data) && is_array($lembur_data)) {
                    $lembur_items = $lembur_data['data'] ?? $lembur_data;
                    if (is_array($lembur_items) && count($lembur_items) > 0) {
                        $has_data = true;
                    }
                }

                if ($has_data):
                ?>
                    <div class="space-y-3">
                        <?php
                        $total_lembur = count($lembur_items);
                        foreach ($lembur_items as $index => $lembur):
                            $tanggal = $lembur['tanggal'] ?? '';
                            $jam_mulai = $lembur['jam_mulai'] ?? '';
                            $jam_selesai = $lembur['jam_selesai'] ?? '';
                            $durasi = $lembur['durasi'] ?? '';
                            $status = $lembur['status'] ?? 'pending';
                            $keterangan = $lembur['keterangan'] ?? 'Tidak ada keterangan';
                            $dibuat_oleh = $lembur['dibuat_oleh'] ?? 'HRD';

                            // Status color
                            $status_color = 'bg-yellow-100 text-yellow-800';
                            if ($status === 'approved') $status_color = 'bg-green-100 text-green-800';
                            if ($status === 'rejected') $status_color = 'bg-red-100 text-red-800';
                        ?>
                            <div class="p-4 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors" data-bulan="<?php echo date('m', strtotime($tanggal)); ?>" data-status="<?php echo $status; ?>">
                                <div class="flex justify-between items-start mb-3">
                                    <div class="flex-1">
                                        <div class="flex items-center mb-2">
                                            <i class="fas fa-calendar-day text-orange-500 mr-2"></i>
                                            <p class="font-medium text-gray-800"><?php echo formatTanggalIndonesia($tanggal); ?></p>
                                        </div>
                                        <div class="flex items-center text-sm text-gray-600 mb-1">
                                            <i class="fas fa-clock text-gray-400 mr-2"></i>
                                            <span><?php echo $jam_mulai; ?> - <?php echo $jam_selesai; ?></span>
                                            <span class="mx-2">•</span>
                                            <span class="font-medium text-orange-600"><?php echo $durasi; ?> jam</span>
                                        </div>
                                        <div class="flex items-center text-xs text-gray-500">
                                            <i class="fas fa-user text-gray-400 mr-1"></i>
                                            <span>Ditentukan oleh: <?php echo htmlspecialchars($dibuat_oleh); ?></span>
                                        </div>
                                    </div>
                                    <span class="px-3 py-1 text-xs rounded-full <?php echo $status_color; ?> ml-3">
                                        <?php echo ucfirst($status); ?>
                                    </span>
                                </div>
                                <div class="bg-gray-50 p-3 rounded-lg">
                                    <p class="text-sm text-gray-700">
                                        <i class="fas fa-info-circle text-gray-400 mr-2"></i>
                                        <?php echo htmlspecialchars($keterangan); ?>
                                    </p>
                                </div>
                            </div>
                        <?php endforeach; ?>
                        <script>
                            document.getElementById('totalLembur').textContent = '<?php echo $total_lembur; ?>';
                        </script>
                    </div>
                <?php else: ?>
                    <div class="text-center py-12">
                        <i class="fas fa-clock text-gray-400 text-5xl mb-4"></i>
                        <h3 class="text-lg font-medium text-gray-500 mb-2">Belum Ada Data Lembur</h3>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Footer -->
        <div class="text-center mt-6 ios-foot">
            <p>© 2024 Bank BIJ • v2.4.1</p>
        </div>
    </div>

    <script>
        // Refresh lembur data
        function refreshLembur() {
            const refreshBtn = document.querySelector('[onclick="refreshLembur()"] i');
            refreshBtn.classList.add('fa-spin');

            // Simulate refresh (in real app, this would reload data from server)
            setTimeout(() => {
                refreshBtn.classList.remove('fa-spin');
                alert('Data lembur telah diperbarui');
            }, 1000);
        }

        // Update time
        function updateTime() {
            const now = new Date();
            const timeString = now.toLocaleTimeString('id-ID', {
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            });
            const dateString = now.toLocaleDateString('id-ID', {
                weekday: 'long',
                year: 'numeric',
                month: 'long',
                day: 'numeric'
            });

            const timeElement = document.getElementById('current-time');
            const dateElement = document.getElementById('current-date');
            if (timeElement) timeElement.textContent = timeString;
            if (dateElement) dateElement.textContent = dateString;
        }

        // Update time every second
        setInterval(updateTime, 1000);
        updateTime();
    </script>
</body>

</html>