
<?php $__env->startSection('content'); ?>

<style>
    .dashboard-card {
        border: none;
        border-radius: 12px;
        box-shadow: 0 4px 15px rgba(0,0,0,0.05);
        transition: all 0.3s ease-in-out;
    }
    .dashboard-card:hover {
        transform: translateY(-3px);
        box-shadow: 0 6px 20px rgba(0,0,0,0.1);
    }
    .dashboard-icon {
        font-size: 36px;
        padding: 15px;
        border-radius: 12px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
    }
    .numbers p {
        margin: 0;
        font-size: 14px;
        font-weight: 500;
        color: #6c757d;
    }
    .numbers h4 {
        margin: 0;
        font-size: 20px;
        font-weight: 600;
    }
    /* SweetAlert2 Custom Styles */
    .swal2-popup {
        border-radius: 12px;
        box-shadow: 0 10px 30px rgba(0,0,0,0.15);
    }
    .swal2-title {
        font-size: 1.5rem;
        font-weight: 600;
        margin-bottom: 1rem;
    }
    .swal2-content {
        padding: 0 1rem 1rem;
    }
    .swal2-html-container {
        padding: 0;
    }
    .modal-card {
        border: none;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        margin-bottom: 1rem;
    }
    .modal-icon {
        font-size: 24px;
        padding: 10px;
        border-radius: 8px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 50px;
        height: 50px;
    }
    .modal-numbers p {
        margin: 0;
        font-size: 12px;
        font-weight: 500;
        color: #6c757d;
    }
    .modal-numbers h5 {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
    }
    /* Collapse */
    .custom-pill {
        border-radius: 20px;
        padding: 6px 14px;
        transition: all 0.3s ease;
    }
    .custom-pill.active {
        background-color: #007bff;
        color: #fff;
    }
    .class-content {
        display: none;
        padding: 10px;
        animation: fadeIn 0.3s ease;
    }
    .class-content.active {
        display: block;
    }
    @keyframes fadeIn {
        from { opacity: 0; transform: translateY(5px); }
        to { opacity: 1; transform: translateY(0); }
    }
</style>

<div class="container-fluid">

    <!-- Top Row: Cards + Pie Chart -->
    <div class="row g-4 mb-4">
        <div class="col-lg-6">
            <div class="row g-4">
                <!-- Student Capacity -->
                <div class="col-md-6">
                    <div class="card dashboard-card p-3">
                        <div class="d-flex align-items-center">
                            <div class="dashboard-icon bg-warning text-white me-3">
                                <i class="ti-user"></i>
                            </div>
                            <div class="numbers">
                                <p><?php echo e(_lang('Student Capacity')); ?></p>
                                <h4><?php echo e(total_student_capacity()); ?></h4>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- Occupied Seats -->
                <div class="col-md-6">
                    <div class="card dashboard-card p-3">
                        <div class="d-flex align-items-center">
                            <div class="dashboard-icon bg-danger text-white me-3">
                                <i class="ti-user"></i>
                            </div>
                            <div class="numbers">
                                <p><?php echo e(_lang('Occupied Seats')); ?></p>
                                <h4><?php echo e(total_student_occupied()); ?></h4>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- Vacant Seats -->
                <div class="col-md-6">
                    <div class="card dashboard-card p-3">
                        <div class="d-flex align-items-center">
                            <div class="dashboard-icon bg-info text-white me-3">
                                <i class="ti-user"></i>
                            </div>
                            <div class="numbers">
                                <p><?php echo e(_lang('Vacant Seats')); ?></p>
                                <h4><?php echo e(total_student_vacant()); ?></h4>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- Monthly Payments -->
                <div class="col-md-6">
                    <div class="card dashboard-card p-3">
                        <div class="d-flex align-items-center">
                            <div class="dashboard-icon bg-primary text-white me-3">
                                <i class="ti-credit-card"></i>
                            </div>
                            <div class="numbers">
                                <p><?php echo e(_lang('Monthly Payments')); ?></p>
                                <h4><?php echo e($currency." ".$student_payments); ?></h4>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- More Metrics Button -->
                <div class="col-md-12 text-center">
                    <button type="button" class="btn btn-primary" onclick="showMoreMetrics()">
                        <?php echo e(_lang('View More Metrics')); ?>

                    </button>
                </div>
            </div>
        </div>

        <!-- Pie Chart -->
        <div class="col-lg-6">
            <div class="card dashboard-card p-3" style="height:350px;">
                <h5 class="text-center mb-3"><?php echo e(_lang('Income vs Expense (Total - ') . date("Y") . ')'); ?></h5>
                <canvas id="incomeExpensePie" height="250"></canvas>
            </div>
        </div>
    </div>

    <!-- Bar Chart for Student Status -->
    <div class="row g-4 mb-4">
        <div class="col-lg-12">
            <div class="card dashboard-card p-3" style="height:500px;">
                <h5 class="text-center mb-3"><?php echo e(_lang('Student Status by Month and Year')); ?></h5>
                <canvas id="studentStatusBar" height="300"></canvas>
            </div>
        </div>
    </div>

    <!-- Collapsible Sections -->
    <?php if(count($total_class) > 0): ?>
    <div class="card mb-4">
        <div class="card-header">
            <div class="d-flex flex-wrap gap-2">
                <?php $__currentLoopData = $total_class; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $class): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                <button class="btn btn-outline-primary custom-pill" 
                        onclick="showClassContent('class-<?php echo e($class->id); ?>', this)">
                    <?php echo e($class->class_name); ?>

                </button>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            </div>
        </div>

        <div class="card-body">
            <?php $__currentLoopData = $total_class; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $index => $class): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
            <div class="class-content" id="class-<?php echo e($class->id); ?>">
                <?php if(count($class->class_section) > 0): ?>
                <table class="table table-bordered mt-5">
                    <thead>
                        <tr>
                            <th class="text-center"><?php echo e(_lang('Room')); ?></th>
                            <th class="text-center"><?php echo e(_lang('Capacity')); ?></th>
                            <th class="text-center"><?php echo e(_lang('Vacant')); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $__currentLoopData = $class->class_section; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $section): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <?php 
                                $per = $section->capacity / 100;
                                $percentage = ($section->capacity - section_wise_occupied($section->id)) / $per;
                                $vacant = $section->capacity - section_wise_occupied($section->id);
                            ?>
                            <tr>
                                <td class="text-center"><?php echo e($section->section_name); ?></td>
                                <td class="text-center"><?php echo e($section->capacity); ?></td>
                                <td class="text-center 
                                    <?php if($percentage<1): ?> bg-danger text-white
                                    <?php elseif($percentage>0 && $percentage<26): ?> bg-warning text-dark
                                    <?php elseif($percentage>25 && $percentage<51): ?> bg-light text-dark
                                    <?php elseif($percentage>50 && $percentage<76): ?> bg-success text-dark
                                    <?php elseif($percentage>75): ?> bg-success text-white
                                    <?php endif; ?>">
                                    <?php echo e($vacant); ?>

                                </td>
                            </tr>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </tbody>
                </table>
                <?php else: ?>
                    <small class="text-danger"><?php echo e(_lang('Section not found!')); ?></small>
                <?php endif; ?>
            </div>
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
        </div>
    </div>
    <?php endif; ?>


</div>

<?php $__env->stopSection(); ?>

<?php $__env->startSection('js-script'); ?>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.4/dist/chart.umd.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
    document.addEventListener("DOMContentLoaded", function () {
        // Parse JSON safely function
        function parseJSONSafely(jsonString) {
            try {
                let cleanedString = jsonString.trim();
                cleanedString = cleanedString.replace(/,\s*]$/, ']');
                const parsed = JSON.parse(cleanedString);
                return Array.isArray(parsed) ? parsed.map(Number) : [Number(parsed)];
            } catch (e) {
                console.error('Invalid JSON:', jsonString, 'Error:', e.message);
                return [];
            }
        }

        // Income vs Expense Pie Chart
        const pieCtx = document.getElementById('incomeExpensePie').getContext('2d');
        const incomeData = parseJSONSafely('<?php echo e($yearly_income); ?>');
        const expenseData = parseJSONSafely('<?php echo e($yearly_expense); ?>');
        const totalIncome = incomeData.reduce((a, b) => a + b, 0);
        const totalExpense = expenseData.reduce((a, b) => a + b, 0);

        new Chart(pieCtx, {
            type: 'doughnut',
            data: {
                labels: ['<?php echo e(_lang("Income")); ?>', '<?php echo e(_lang("Expense")); ?>'],
                datasets: [{
                    data: [totalIncome, totalExpense],
                    backgroundColor: ['#28a745', '#dc3545'],
                    borderColor: ['#ffffff', '#ffffff'],
                    borderWidth: 2
                }]
            },
            options: {
                responsive: true,
                aspectRatio: 2,
                plugins: {
                    legend: {
                        position: 'top'
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                let value = context.raw || 0;
                                return context.label + ': ' + value.toLocaleString();
                            }
                        }
                    }
                }
            }
        });

        // Student Status Bar Chart
        const barCtx = document.getElementById('studentStatusBar').getContext('2d');
const studentData = <?php echo json_encode($student_active_report, 15, 512) ?>;

// Check if studentData is valid
if (!Array.isArray(studentData)) {
    console.error('studentData is not an array:', studentData);
    throw new Error('Invalid student data format');
}

// Flatten the data to create an array of month-year entries
const flattenedData = [];
studentData.forEach(yearData => {
    if (yearData.months && Array.isArray(yearData.months)) {
        yearData.months.forEach(monthData => {
            flattenedData.push({
                year: yearData.year,
                month: monthData.month,
                status_0_count: monthData.status_0_count,
                status_1_count: monthData.status_1_count
            });
        });
    }
});

// Sort by year and month to ensure chronological order
flattenedData.sort((a, b) => {
    if (a.year === b.year) {
        return a.month - b.month;
    }
    return a.year - b.year;
});

// Create labels (e.g., "Jan 2023", "Feb 2023", etc.)
const labels = flattenedData.map(item => {
    const monthName = new Date(0, item.month - 1).toLocaleString('default', { month: 'short' });
    return `${monthName} ${item.year}`;
});

// Create datasets for status 0 and status 1
const status0Data = flattenedData.map(item => item.status_0_count);
const status1Data = flattenedData.map(item => item.status_1_count);

new Chart(barCtx, {
    type: 'bar',
    data: {
        labels: labels,
        datasets: [
            {
                label: '<?php echo e(_lang("Status 0 (Inactive)")); ?>',
                data: status0Data,
                backgroundColor: '#36A2EB',
                borderColor: '#36A2EB',
                borderWidth: 1
            },
            {
                label: '<?php echo e(_lang("Status 1 (Active)")); ?>',
                data: status1Data,
                backgroundColor: '#FF6384',
                borderColor: '#FF6384',
                borderWidth: 1
            }
        ]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        scales: {
            y: {
                beginAtZero: true,
                title: {
                    display: true,
                    text: '<?php echo e(_lang("Number of Students")); ?>'
                }
            },
            x: {
                title: {
                    display: true,
                    text: '<?php echo e(_lang("Month and Year")); ?>'
                },
                ticks: {
                    autoSkip: false, // Ensure all labels are shown
                    maxRotation: 45, // Rotate labels for better readability
                    minRotation: 45
                }
            }
        },
        plugins: {
            legend: {
                display: true,
                position: 'top'
            },
            title: {
                display: true,
                text: '<?php echo e(_lang("Student Status by Month and Year")); ?>'
            }
        }
    }
});

        // Function to show more metrics in SweetAlert2 modal
        function showMoreMetrics() {
            Swal.fire({
                title: '<?php echo e(_lang("Additional Metrics")); ?>',
                html: `
                    <div class="row g-3">
                        <!-- Others Income -->
                        <div class="col-md-6">
                            <div class="card modal-card p-3">
                                <div class="d-flex align-items-center">
                                    <div class="modal-icon bg-success text-white me-2">
                                        <i class="ti-wallet"></i>
                                    </div>
                                    <div class="modal-numbers">
                                        <p><?php echo e(_lang('Others Income')); ?></p>
                                        <h5><?php echo e($currency." ".$monthly_income); ?></h5>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- Expenses -->
                        <div class="col-md-6">
                            <div class="card modal-card p-3">
                                <div class="d-flex align-items-center">
                                    <div class="modal-icon bg-danger text-white me-2">
                                        <i class="ti-stats-down"></i>
                                    </div>
                                    <div class="modal-numbers">
                                        <p><?php echo e(_lang('Monthly Expense')); ?></p>
                                        <h5><?php echo e($currency." ".$monthly_expense); ?></h5>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- Cash in Hand -->
                        <div class="col-md-6">
                            <div class="card modal-card p-3">
                                <div class="d-flex align-items-center">
                                    <div class="modal-icon bg-warning text-white me-2">
                                        <i class="ti-money"></i>
                                    </div>
                                    <div class="modal-numbers">
                                        <p><?php echo e(_lang('Cash in Hand')); ?></p>
                                        <h5><?php echo e($cash_in_hand); ?></h5>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- Atif Sahb (Bank) -->
                        <div class="col-md-6">
                            <div class="card modal-card p-3">
                                <div class="d-flex align-items-center">
                                    <div class="modal-icon bg-primary text-white me-2">
                                        <i class="ti-bank"></i>
                                    </div>
                                    <div class="modal-numbers">
                                        <p><?php echo e(_lang('Atif Sahb (Bank)')); ?></p>
                                        <h5><?php echo e($atif_bank); ?></h5>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- Atif Sahb (Cash) -->
                        <div class="col-md-6">
                            <div class="card modal-card p-3">
                                <div class="d-flex align-items-center">
                                    <div class="modal-icon bg-info text-white me-2">
                                        <i class="ti-wallet"></i>
                                    </div>
                                    <div class="modal-numbers">
                                        <p><?php echo e(_lang('Atif Sahb (Cash)')); ?></p>
                                        <h5><?php echo e($atif_sahb); ?></h5>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                `,
                width: '800px',
                showCancelButton: false,
                showConfirmButton: false,
                allowOutsideClick: true,
                allowEscapeKey: true,
                customClass: {
                    container: 'swal2-container',
                    popup: 'swal2-popup'
                }
            });
        }

        // Collapse function
        function showClassContent(id, btn) {
            const content = document.getElementById(id);
            const isActive = content.classList.contains("active");

            // Hide all contents
            document.querySelectorAll(".class-content").forEach(el => el.classList.remove("active"));
            // Remove active from all buttons
            document.querySelectorAll(".custom-pill").forEach(b => b.classList.remove("active"));

            if (!isActive) {
                // Show selected if it was not already active
                content.classList.add("active");
                btn.classList.add("active");
            }
        }
    });
</script>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('layouts.backend', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH /home/hostelmanager/public_html/test.hostelmanager.pk/resources/views/backend/dashboard/Admin.blade.php ENDPATH**/ ?>