<?php

$pageTitle = 'Dashboard';
if (!Auth::isLoggedIn()) { redirect(base_url('login')); }

$userId = $_SESSION['user_id'];
$userRole = $_SESSION['user_role'];
$isAdmin = ($userRole === 'admin');

$userBalance = $userBalance ?? 0; 
$totalOrdersValueUser = 0;
$totalDepositValueUser = 0;

$totalUsersAdmin = 0;
$totalOrdersAdmin = 0;
$totalRevenueAdmin = 0;
$totalPendingOrdersAdmin = 0;
$totalPendingTicketsAdmin = 0;
$totalServicesAdmin = 0;

$latestInformations = [];

try {
    if ($isAdmin) {
        $stmtTotalUsers = $pdo->query("SELECT COUNT(id) FROM users");
        $totalUsersAdmin = $stmtTotalUsers->fetchColumn() ?: 0;

        $stmtTotalOrders = $pdo->query("SELECT COUNT(id) FROM orders");
        $totalOrdersAdmin = $stmtTotalOrders->fetchColumn() ?: 0;

        $stmtTotalRevenue = $pdo->query("SELECT SUM(price) FROM orders WHERE status = 'success'");
        $totalRevenueAdmin = $stmtTotalRevenue->fetchColumn() ?: 0;

        $stmtPendingOrders = $pdo->query("SELECT COUNT(id) FROM orders WHERE status = 'pending'");
        $totalPendingOrdersAdmin = $stmtPendingOrders->fetchColumn() ?: 0;

        $stmtPendingTickets = $pdo->query("SELECT COUNT(id) FROM tickets WHERE status != 'closed' AND is_read_admin = 0");
        $totalPendingTicketsAdmin = $stmtPendingTickets->fetchColumn() ?: 0;

        $stmtTotalServices = $pdo->query("SELECT COUNT(id) FROM services WHERE status = 'active'");
        $totalServicesAdmin = $stmtTotalServices->fetchColumn() ?: 0;

    } else {
        $stmtOrders = $pdo->prepare("SELECT SUM(price) as total FROM orders WHERE user_id = :user_id");
        $stmtOrders->bindParam(':user_id', $userId, PDO::PARAM_INT);
        $stmtOrders->execute();
        $resultOrders = $stmtOrders->fetch(PDO::FETCH_ASSOC);
        $totalOrdersValueUser = $resultOrders['total'] ?? 0;

        $stmtDeposits = $pdo->prepare("SELECT SUM(amount) as total FROM deposits WHERE user_id = :user_id AND status = 'success'");
        $stmtDeposits->bindParam(':user_id', $userId, PDO::PARAM_INT);
        $stmtDeposits->execute();
        $resultDeposits = $stmtDeposits->fetch(PDO::FETCH_ASSOC);
        $totalDepositValueUser = $resultDeposits['total'] ?? 0;
    }

    $stmtInfo = $pdo->query("SELECT id, title, content, image_filename, created_at FROM informations WHERE status = 'active' ORDER BY created_at DESC LIMIT 5");
    $latestInformations = $stmtInfo->fetchAll(PDO::FETCH_ASSOC);

} catch (\PDOException $e) {
    error_log("Error fetching dashboard data: " . $e->getMessage());
    $latestInformations = [['id' => 0, 'title' => 'Error Database', 'content' => 'Gagal memuat informasi terbaru karena kesalahan database.', 'image_filename' => null, 'created_at' => date("Y-m-d H:i:s")]];
    if ($isAdmin) {
        $totalUsersAdmin = 'Error';
        $totalOrdersAdmin = 'Error';
        $totalRevenueAdmin = 'Error';
        $totalPendingOrdersAdmin = 'Error';
        $totalPendingTicketsAdmin = 'Error';
        $totalServicesAdmin = 'Error';
    } else {
        $totalOrdersValueUser = 'Error';
        $totalDepositValueUser = 'Error';
    }
}

?>
<main class="flex-1 overflow-x-hidden overflow-y-auto p-6 md:p-8 bg-gradient-to-b from-gray-900 to-gray-800 text-gray-200">

    <h2 class="text-3xl font-semibold text-white mb-8">Dashboard <?php echo $isAdmin ? '<span class="text-sm font-normal text-red-400">(Admin)</span>' : ''; ?></h2>

    <div class="grid grid-cols-1 sm:grid-cols-2 <?php echo $isAdmin ? 'lg:grid-cols-3 xl:grid-cols-6' : 'md:grid-cols-3'; ?> gap-6 mb-8">
        <?php if ($isAdmin): ?>
            <div class="bg-gray-800 border border-gray-700 p-5 rounded-xl shadow-lg transform transition hover:scale-105 hover:shadow-blue-500/30">
                <div class="flex items-center justify-between mb-2">
                    <p class="text-xs font-medium text-gray-400 uppercase">Total Pengguna</p>
                    <div class="p-2 rounded-full bg-blue-600 text-white shadow-md"><i class="fas fa-users text-base"></i></div>
                </div>
                <p class="text-2xl font-bold text-white"><?php echo number_format($totalUsersAdmin); ?></p>
                <a href="<?php echo base_url('admin/users'); ?>" class="text-xs text-blue-400 hover:text-blue-300 mt-1 inline-block">Kelola Pengguna &rarr;</a>
            </div>
            <div class="bg-gray-800 border border-gray-700 p-5 rounded-xl shadow-lg transform transition hover:scale-105 hover:shadow-green-500/30">
                <div class="flex items-center justify-between mb-2">
                    <p class="text-xs font-medium text-gray-400 uppercase">Total Pesanan</p>
                    <div class="p-2 rounded-full bg-green-600 text-white shadow-md"><i class="fas fa-shopping-cart text-base"></i></div>
                </div>
                <p class="text-2xl font-bold text-white"><?php echo number_format($totalOrdersAdmin); ?></p>
                <a href="<?php echo base_url('admin/orders'); ?>" class="text-xs text-green-400 hover:text-green-300 mt-1 inline-block">Kelola Pesanan &rarr;</a>
            </div>
            <div class="bg-gray-800 border border-gray-700 p-5 rounded-xl shadow-lg transform transition hover:scale-105 hover:shadow-yellow-500/30">
                <div class="flex items-center justify-between mb-2">
                    <p class="text-xs font-medium text-gray-400 uppercase">Total Pendapatan</p>
                    <div class="p-2 rounded-full bg-yellow-500 text-white shadow-md"><i class="fas fa-dollar-sign text-base"></i></div>
                </div>
                <p class="text-2xl font-bold text-white">Rp <?php echo number_format($totalRevenueAdmin, 0, ',', '.'); ?></p>
                 <span class="text-xs text-yellow-400 mt-1 inline-block">(Dari Pesanan Sukses)</span>
            </div>
            <div class="bg-gray-800 border border-gray-700 p-5 rounded-xl shadow-lg transform transition hover:scale-105 hover:shadow-orange-500/30">
                <div class="flex items-center justify-between mb-2">
                    <p class="text-xs font-medium text-gray-400 uppercase">Pesanan Pending</p>
                    <div class="p-2 rounded-full bg-orange-500 text-white shadow-md"><i class="fas fa-hourglass-half text-base"></i></div>
                </div>
                <p class="text-2xl font-bold text-white"><?php echo number_format($totalPendingOrdersAdmin); ?></p>
                <a href="<?php echo base_url('admin/orders?status=pending'); ?>" class="text-xs text-orange-400 hover:text-orange-300 mt-1 inline-block">Lihat Detail &rarr;</a>
            </div>
             <div class="bg-gray-800 border border-gray-700 p-5 rounded-xl shadow-lg transform transition hover:scale-105 hover:shadow-red-500/30">
                <div class="flex items-center justify-between mb-2">
                    <p class="text-xs font-medium text-gray-400 uppercase">Tiket Belum Dibaca</p>
                    <div class="p-2 rounded-full bg-red-500 text-white shadow-md"><i class="fas fa-ticket-alt text-base"></i></div>
                </div>
                <p class="text-2xl font-bold text-white"><?php echo number_format($totalPendingTicketsAdmin); ?></p>
                 <a href="<?php echo base_url('admin/tickets?unread=admin'); ?>" class="text-xs text-red-400 hover:text-red-300 mt-1 inline-block">Lihat Tiket &rarr;</a>
            </div>
             <div class="bg-gray-800 border border-gray-700 p-5 rounded-xl shadow-lg transform transition hover:scale-105 hover:shadow-purple-500/30">
                <div class="flex items-center justify-between mb-2">
                    <p class="text-xs font-medium text-gray-400 uppercase">Total Layanan Aktif</p>
                    <div class="p-2 rounded-full bg-purple-600 text-white shadow-md"><i class="fas fa-list-alt text-base"></i></div>
                </div>
                <p class="text-2xl font-bold text-white"><?php echo number_format($totalServicesAdmin); ?></p>
                 <a href="<?php echo base_url('admin/services?status=active'); ?>" class="text-xs text-purple-400 hover:text-purple-300 mt-1 inline-block">Kelola Layanan &rarr;</a>
            </div>

        <?php else: ?>
            <div class="bg-gray-800 border border-gray-700 p-6 rounded-xl shadow-lg transform transition hover:scale-105 hover:shadow-blue-500/30">
                <div class="flex items-center justify-between mb-3">
                    <p class="text-sm font-medium text-gray-400">Saldo Anda</p>
                    <div class="p-2 rounded-full bg-blue-600 text-white shadow-md">
                        <i class="fas fa-wallet text-lg"></i>
                    </div>
                </div>
                <p class="text-3xl font-bold text-white">Rp <?php echo number_format($userBalance, 0, ',', '.'); ?></p>
                <a href="<?php echo base_url('deposit/new'); ?>" class="text-xs text-blue-400 hover:text-blue-300 mt-2 inline-block">
                    + Isi Saldo
                </a>
            </div>
            <div class="bg-gray-800 border border-gray-700 p-6 rounded-xl shadow-lg transform transition hover:scale-105 hover:shadow-green-500/30">
                <div class="flex items-center justify-between mb-3">
                    <p class="text-sm font-medium text-gray-400">Total Pesanan Anda</p>
                    <div class="p-2 rounded-full bg-green-600 text-white shadow-md">
                        <i class="fas fa-shopping-cart text-lg"></i>
                    </div>
                </div>
                <p class="text-3xl font-bold text-white">Rp <?php echo number_format($totalOrdersValueUser, 0, ',', '.'); ?></p>
                <a href="<?php echo base_url('order/history'); ?>" class="text-xs text-green-400 hover:text-green-300 mt-2 inline-block">
                    Lihat Riwayat
                </a>
            </div>
            <div class="bg-gray-800 border border-gray-700 p-6 rounded-xl shadow-lg transform transition hover:scale-105 hover:shadow-yellow-500/30">
                <div class="flex items-center justify-between mb-3">
                    <p class="text-sm font-medium text-gray-400">Total Deposit Anda</p>
                    <div class="p-2 rounded-full bg-yellow-500 text-white shadow-md">
                        <i class="fas fa-coins text-lg"></i>
                    </div>
                </div>
                <p class="text-3xl font-bold text-white">Rp <?php echo number_format($totalDepositValueUser, 0, ',', '.'); ?></p>
                <a href="<?php echo base_url('deposit/history'); ?>" class="text-xs text-yellow-400 hover:text-yellow-300 mt-2 inline-block">
                    Lihat Riwayat
                </a>
            </div>
        <?php endif; ?>
    </div>

    <div class="bg-gray-800 border border-gray-700 p-6 rounded-xl shadow-lg">
        <h3 class="text-xl font-semibold text-white mb-5 flex items-center">
            <i class="fas fa-bullhorn mr-3 text-cyan-400"></i> Informasi Terbaru
        </h3>
        <div id="information-container" class="space-y-6">
            <?php if (!empty($latestInformations)): ?>
                <?php foreach ($latestInformations as $info): ?>
                    <?php
                        $imageFilename = $info['image_filename'] ?? null;
                        $imageUrl = $imageFilename ? base_url('uploads/informations/' . $imageFilename) : null;
                        $placeholderUrl = "https://placehold.co/600x300/374151/9ca3af?text=Info";
                        $imageOnError = "this.onerror=null; this.src='{$placeholderUrl}';";
                        $contentPreview = nl2br(htmlspecialchars(mb_substr(strip_tags($info['content'] ?? ''), 0, 150)));
                        $hasMoreContent = mb_strlen(strip_tags($info['content'] ?? '')) > 150;
                    ?>
                    <article class="flex flex-col md:flex-row bg-gray-700 rounded-lg shadow-md overflow-hidden border border-gray-600 hover:shadow-cyan-500/20 transition-shadow duration-300">
                        <?php if ($imageUrl): ?>
                            <div class="md:w-1/3 flex-shrink-0">
                                <img src="<?php echo htmlspecialchars($imageUrl); ?>"
                                     alt="<?php echo htmlspecialchars($info['title']); ?>"
                                     class="w-full h-48 md:h-full object-cover"
                                     onerror="<?php echo $imageOnError; ?>">
                            </div>
                        <?php endif; ?>
                        <div class="p-5 flex flex-col justify-between <?php echo $imageUrl ? 'md:w-2/3' : 'w-full'; ?>">
                            <div>
                                <div class="flex justify-between items-start mb-2 gap-2">
                                    <h4 class="text-lg font-semibold text-gray-100 hover:text-cyan-300 transition-colors">
                                        <?php echo htmlspecialchars($info['title']); ?>
                                    </h4>
                                    <span class="text-xs text-gray-400 flex-shrink-0 ml-2 whitespace-nowrap"><?php echo date('d M Y, H:i', strtotime($info['created_at'])); ?></span>
                                </div>
                                <div class="text-sm text-gray-300 leading-relaxed prose prose-sm prose-invert max-w-none mb-4 info-preview">
                                    <?php echo $contentPreview . ($hasMoreContent ? '...' : ''); ?>
                                </div>
                            </div>
                            <div class="mt-auto pt-3 border-t border-gray-600 text-right">
                                <button type="button" class="text-xs text-cyan-400 hover:text-cyan-300 hover:underline open-info-detail-btn" data-info-id="<?php echo $info['id']; ?>" data-info-title="<?php echo htmlspecialchars($info['title']); ?>" data-info-image="<?php echo htmlspecialchars($imageUrl ?? ''); ?>" data-info-content="<?php echo htmlspecialchars($info['content'] ?? ''); ?>">
                                    Baca Selengkapnya &rarr;
                                </button>
                            </div>
                        </div>
                    </article>
                <?php endforeach; ?>
            <?php else: ?>
                <p class="text-center text-gray-500 italic py-5">Tidak ada informasi terbaru saat ini.</p>
            <?php endif; ?>
        </div>
    </div>

    <div id="info-detail-modal" class="fixed inset-0 z-50 hidden items-center justify-center bg-black bg-opacity-75 transition-opacity duration-300 ease-in-out" aria-labelledby="info-detail-modal-title" role="dialog" aria-modal="true">
        <div class="relative bg-gray-800 rounded-lg shadow-xl w-full max-w-2xl mx-4 max-h-[90vh] flex flex-col transform transition-all duration-300 ease-in-out scale-95 opacity-0" id="info-detail-modal-content">
            <div class="flex items-center justify-between px-6 py-4 border-b border-gray-700 flex-shrink-0">
                <h3 class="text-lg font-semibold text-gray-100 flex items-center" id="info-detail-modal-title">
                    <i class="fas fa-info-circle mr-2 text-cyan-400"></i> Detail Informasi
                </h3>
                <button type="button" id="close-info-detail-modal" class="text-gray-400 hover:text-white focus:outline-none">
                    <span class="sr-only">Tutup</span>
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>
            <div class="p-6 space-y-4 text-sm overflow-y-auto flex-grow" id="info-detail-modal-body">
            </div>
            <div class="px-6 py-3 bg-gray-700 rounded-b-lg flex justify-end flex-shrink-0">
                 <button type="button" id="close-info-detail-modal-footer" class="px-4 py-2 text-sm font-medium text-gray-200 bg-red-600 rounded-lg hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-gray-800 focus:ring-red-500 transition">
                     Tutup
                 </button>
             </div>
        </div>
    </div>

    <style>
        .prose-invert a { color: #67e8f9; text-decoration: underline; }
        .prose-invert a:hover { color: #a5f3fc; }
        .prose-invert code { color: #a5f3fc; background-color: #4b5563; padding: 0.1em 0.3em; border-radius: 0.25em; font-size: 0.85em; }
        .prose-invert strong { color: #e5e7eb; }
        .prose-invert ul > li::marker { color: #9ca3af; }
        .prose-invert blockquote { border-left-color: #6b7280; color: #d1d5db; }
        #info-detail-modal-body::-webkit-scrollbar { width: 5px; }
        #info-detail-modal-body::-webkit-scrollbar-track { background: #4b5563; border-radius: 10px; }
        #info-detail-modal-body::-webkit-scrollbar-thumb { background: #6b7280; border-radius: 10px; }
        #info-detail-modal-body::-webkit-scrollbar-thumb:hover { background: #9ca3af; }
    </style>
</main>