@extends('layouts.app')

@section('title', 'Monthly Attendance Analytics')

@section('panel-actions')
    <a href="#" onclick="window.print()" class="btn btn-info btn-sm shadow-sm mr-1">
        <i class="fas fa-print mr-1"></i> Print Report
    </a>
    <button id="mainExcelExport" class="btn btn-success btn-sm shadow-sm">
        <i class="fas fa-file-excel mr-1"></i> Excel Export
    </button>
@endsection

@section('content')
<div class="row">
    <div class="col-12">
        <!-- Summary Widgets -->
        <div class="row mb-4">
            <div class="col-md-4">
                <div class="info-box premium-info-box bg-premium-primary shadow-sm">
                    <span class="info-box-icon"><i class="fa-solid fa-chart-line"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Avg. Monthly Presence</span>
                        <span class="info-box-number h5 mb-0" id="widget_avg_p">0%</span>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="info-box premium-info-box bg-premium-success shadow-sm">
                    <span class="info-box-icon"><i class="fa-solid fa-award"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">100% Attendance Stars</span>
                        <span class="info-box-number h5 mb-0" id="widget_stars">0</span>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="info-box premium-info-box bg-premium-danger shadow-sm">
                    <span class="info-box-icon"><i class="fa-solid fa-user-clock"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Frequent Absentees</span>
                        <span class="info-box-number h5 mb-0" id="widget_absentees">0</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Filter Bar -->
        <div class="card shadow-sm border-0 mb-4">
            <div class="card-body p-3">
                <div class="row align-items-end">
                    <div class="col-md-3">
                        <label class="small font-weight-bold text-muted uppercase">Select Month</label>
                        <select id="report_month" class="form-control form-control-sm border-primary">
                            @foreach(range(1, 12) as $m)
                                <option value="{{ sprintf('%02d', $m) }}" {{ $m == $month ? 'selected' : '' }}>
                                    {{ date('F', mktime(0, 0, 0, $m, 1)) }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="small font-weight-bold text-muted uppercase">Year</label>
                        <select id="report_year" class="form-control form-control-sm border-primary">
                            @foreach(range(date('Y')-5, date('Y')) as $y)
                                <option value="{{ $y }}" {{ $y == $year ? 'selected' : '' }}>{{ $y }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="small font-weight-bold text-muted uppercase">Employee</label>
                        <input type="text" id="employee_search" class="form-control form-control-sm" placeholder="Quick find...">
                    </div>
                    <div class="col-md-4 text-right">
                        <button onclick="refreshTable()" class="btn btn-primary btn-sm px-4 shadow-sm">
                            <i class="fas fa-sync-alt mr-1"></i> Update Dashboard
                        </button>
                        <div class="mt-2 text-muted small">
                            <span class="mr-2"><i class="fas fa-circle text-success mr-1" style="font-size: 8px;"></i>P: Present</span>
                            <span class="mr-2"><i class="fas fa-circle text-danger mr-1" style="font-size: 8px;"></i>A: Absent</span>
                            <span><i class="fas fa-circle text-info mr-1" style="font-size: 8px;"></i>L: Leave</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Main Grid Card -->
        <div class="card card-outline card-primary shadow-sm border-0">
            <div class="card-header bg-white py-3">
                <h3 class="card-title font-weight-bold text-dark">
                    <i class="fas fa-th-list mr-2 text-primary"></i>Detailed Attendance Matrix
                </h3>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-bordered table-sm text-nowrap mb-0" id="monthlyGridTable" width="100%">
                        <!-- Table header will be generated dynamically -->
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
    let listTable;
    
    $(document).ready(function() {
        initGrid();

        $('#employee_search').on('keyup', function() {
            listTable.search(this.value).draw();
        });

        $('#mainExcelExport').on('click', function() {
            listTable.button('.buttons-excel').trigger();
        });
    });

    function initGrid() {
        if (listTable) listTable.destroy();
        $('#monthlyGridTable').empty();

        const month = $('#report_month').val();
        const year = $('#report_year').val();
        const daysInMonth = new Date(year, month, 0).getDate();

        // Build Headers
        let header1 = '<thead><tr class="bg-light text-center"><th rowspan="2" class="align-middle sticky-col-left border-right">Employee Information</th>';
        header1 += `<th colspan="${daysInMonth}" class="bg-primary-light">Monthly Calendar Days</th>`;
        header1 += '<th colspan="3" class="bg-light border-left">Month Totals</th></tr>';
        
        let header2 = '<tr class="bg-white text-center font-weight-bold sticky-header-2">';
        for (let i = 1; i <= daysInMonth; i++) {
            const date = new Date(year, month - 1, i);
            const isWeekend = date.getDay() === 0 || date.getDay() === 6;
            const weekendClass = isWeekend ? 'bg-weekend-header' : '';
            header2 += `<th class="${weekendClass}" style="min-width: 32px; font-size: 11px;">${i}</th>`;
        }
        header2 += '<th class="bg-success-light" style="min-width: 40px;">P</th>';
        header2 += '<th class="bg-danger-light" style="min-width: 40px;">A</th>';
        header2 += '<th class="bg-info-light" style="min-width: 40px;">L</th></tr></thead>';
        
        $('#monthlyGridTable').append(header1 + header2);

        // Define Columns
        const columns = [
            { 
                data: null, 
                name: 'employee_info',
                className: 'sticky-col-left border-right',
                render: function(data){
                    return `<div class="d-flex flex-column" style="min-width: 180px;">
                                <span class="font-weight-bold text-dark">${data.name}</span>
                                <span class="small text-muted">${data.designation}</span>
                            </div>`;
                }
            }
        ];

        for (let i = 1; i <= daysInMonth; i++) {
            columns.push({ 
                data: 'day_' + i, 
                name: 'day_' + i,
                className: 'text-center p-1',
                render: function(data, type, row) {
                    const date = new Date(year, month - 1, i);
                    const isWeekend = date.getDay() === 0 || date.getDay() === 6;
                    
                    if (!data) return '';
                    
                    let colorClass = 'status-default';
                    if (data === 'P') colorClass = 'status-p';
                    else if (data === 'A') colorClass = 'status-a';
                    else if (data === 'L') colorClass = 'status-l';
                    
                    return `<span class="grid-status ${colorClass}">${data}</span>`;
                }
            });
        }

        columns.push({ data: 'total_p', name: 'total_p', className: 'text-center font-weight-bold text-success bg-success-light' });
        columns.push({ data: 'total_a', name: 'total_a', className: 'text-center font-weight-bold text-danger bg-danger-light' });
        columns.push({ data: 'total_l', name: 'total_l', className: 'text-center font-weight-bold text-info bg-info-light' });

        listTable = $('#monthlyGridTable').DataTable({
            processing: true,
            serverSide: true,
            ajax: {
                url: "{{ route('reports.attendance.monthly') }}",
                data: function (d) {
                    d.month = month;
                    d.year = year;
                }
            },
            columns: columns,
            scrollX: true,
            pageLength: 25,
            dom: 'Brtip',
            buttons: [
                {
                    extend: 'excel',
                    title: 'Monthly Attendance Report - ' + month + '/' + year,
                    className: 'd-none' // Triggered via custom button
                }
            ],
            language: {
                paginate: {
                    previous: '<i class="fas fa-chevron-left"></i>',
                    next: '<i class="fas fa-chevron-right"></i>'
                }
            },
            drawCallback: function(settings) {
                $('.dataTables_paginate > .pagination').addClass('pagination-sm mt-3');
                
                // Update widgets
                if (settings.json && settings.json.aggregates) {
                    const agg = settings.json.aggregates;
                    $('#widget_avg_p').text(agg.avg_presence + '%');
                    $('#widget_stars').text(agg.top_performers);
                    $('#widget_absentees').text(agg.frequent_absentees);
                }

                // Colorize weekends
                const api = this.api();
                for (let i = 1; i <= daysInMonth; i++) {
                    const date = new Date(year, month - 1, i);
                    if (date.getDay() === 0 || date.getDay() === 6) {
                        api.columns(i).nodes().to$().addClass('bg-weekend-col');
                    }
                }
            }
        });
    }

    function refreshTable() {
        initGrid();
    }
</script>

<style>
    /* Premium Grid Styles */
    #monthlyGridTable { border-collapse: separate !important; border-spacing: 0 !important; }
    
    .sticky-col-left { 
        position: sticky !important; 
        left: 0; 
        background-color: #fff !important; 
        z-index: 10; 
        box-shadow: 2px 0 5px rgba(0,0,0,0.05);
    }
    
    .bg-primary-light { background-color: #f0f7ff !important; color: #007bff !important; font-size: 13px !important; letter-spacing: 1px; font-weight: 800 !important; }
    .bg-success-light { background-color: #f0fdf4 !important; }
    .bg-danger-light { background-color: #fff1f2 !important; }
    .bg-info-light { background-color: #f0f9ff !important; }
    
    .bg-weekend-header { background-color: #f3f4f6 !important; color: #9ca3af !important; }
    .bg-weekend-col { background-color: #f9fafb !important; }
    
    .grid-status {
        display: inline-flex;
        width: 22px;
        height: 22px;
        align-items: center;
        justify-content: center;
        border-radius: 4px;
        font-size: 10px;
        font-weight: 800;
        line-height: 1;
    }
    
    .status-p { background-color: #22c55e; color: #fff; box-shadow: 0 2px 4px rgba(34, 197, 94, 0.3); }
    .status-a { background-color: #ef4444; color: #fff; box-shadow: 0 2px 4px rgba(239, 68, 68, 0.3); }
    .status-l { background-color: #3b82f6; color: #fff; box-shadow: 0 2px 4px rgba(59, 130, 246, 0.3); }
    .status-default { background-color: #e5e7eb; color: #9ca3af; }

    .table-sm td, .table-sm th { padding: 0.4rem !important; vertical-align: middle !important; }
    
    /* DataTable Pagination Modernization */
    .dataTables_wrapper .dataTables_paginate .paginate_button { padding: 0 !important; border: none !important; background: transparent !important; }
    .page-link { border-radius: 6px !important; margin: 0 2px; }
</style>
@endpush

