<?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 {
        header('Location: login.php');
        exit;
    }
}

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

// Get cuti data
$cuti_result = api_get_cuti($token);
$cuti_data = $cuti_result['success'] ? $cuti_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 — Cuti</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">Cuti</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>

        <!-- Cuti Overview -->
        <div class="dashboard-card p-4 mb-4">
            <h2 class="text-lg font-bold text-gray-800 mb-3">Informasi Cuti</h2>
            <div class="grid grid-cols-2 gap-4">
                <div class="text-center p-3 bg-blue-50 rounded-lg">
                    <p class="text-2xl font-bold text-blue-700">12</p>
                    <p class="text-sm text-gray-600">Hari Tersisa</p>
                </div>
                <div class="text-center p-3 bg-green-50 rounded-lg">
                    <p class="text-2xl font-bold text-green-700">3</p>
                    <p class="text-sm text-gray-600">Cuti Terpakai</p>
                </div>
            </div>
        </div>

        <!-- Action Button -->
        <div class="mb-6">
            <a href="pengajuan-cuti.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-plus text-blue-700 text-xl"></i>
                </div>
                <h3 class="font-semibold text-gray-800">Ajukan Cuti</h3>
                <p class="text-sm text-gray-600">Buat pengajuan cuti baru</p>
            </a>
        </div>

        <!-- Daftar Cuti -->
        <div class="dashboard-card p-4">
            <h2 class="text-lg font-bold text-gray-800 mb-4">Daftar Cuti</h2>

            <?php if (!empty($cuti_data) && is_array($cuti_data)): ?>
                <div class="space-y-3">
                    <?php
                    $cuti_items = $cuti_data['data'] ?? $cuti_data;
                    if (is_array($cuti_items)) {
                        foreach (array_slice($cuti_items, 0, 5) as $cuti):
                            $tanggal_mulai = $cuti['tanggal_mulai'] ?? '';
                            $tanggal_selesai = $cuti['tanggal_selesai'] ?? '';
                            $status = $cuti['status'] ?? 'pending';
                            $alasan = $cuti['alasan'] ?? 'Tidak ada alasan';

                            // 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-3 border border-gray-200 rounded-lg">
                                <div class="flex justify-between items-start mb-2">
                                    <div>
                                        <p class="font-medium text-gray-800"><?php echo formatTanggalIndonesia($tanggal_mulai); ?></p>
                                        <p class="text-sm text-gray-600">s/d <?php echo formatTanggalIndonesia($tanggal_selesai); ?></p>
                                    </div>
                                    <span class="px-2 py-1 text-xs rounded-full <?php echo $status_color; ?>">
                                        <?php echo ucfirst($status); ?>
                                    </span>
                                </div>
                                <p class="text-sm text-gray-600"><?php echo htmlspecialchars($alasan); ?></p>
                            </div>
                        <?php endforeach; ?>
                    <?php } ?>
                </div>
            <?php else: ?>
                <div class="text-center py-8">
                    <i class="fas fa-calendar-times text-gray-400 text-4xl mb-3"></i>
                    <p class="text-gray-500">Belum ada data cuti</p>
                </div>
            <?php endif; ?>
        </div>

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

    <script>
        // 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>