<?php $this->load->view('admin/attendance/attendance_report_search'); ?>

<?php
$department_name = !empty($dept_name->deptname) ? $dept_name->deptname : lang('all');
$employee_count = !empty($employee_info) ? count($employee_info) : 0;
$report_dates = array();
$attendance_rows = array();
$present_count = 0;
$holiday_count = 0;
$leave_count = 0;
$absent_count = 0;
$total_minutes_logged = 0;

if (!empty($employee_info)) {
    foreach ($employee_info as $employee) {
        $attendance_rows[$employee->user_id] = array(
            'employee' => $employee,
            'days' => array(),
            'total_minutes' => 0,
            'present_days' => 0,
            'holiday_days' => 0,
            'leave_days' => 0,
            'absent_days' => 0,
        );
    }
}

if (!empty($attendace_info)) {
    foreach ($attendace_info as $week_data) {
        if (empty($week_data)) {
            continue;
        }
        foreach ($week_data as $loop_date => $attendance_day) {
            $report_dates[$loop_date] = true;
            if (empty($attendance_day)) {
                continue;
            }
            foreach ($attendance_day as $user_id => $entries) {
                if (!isset($attendance_rows[$user_id])) {
                    continue;
                }
                $cell = array(
                    'minutes' => 0,
                    'holiday' => false,
                    'leave' => false,
                    'absent' => false,
                    'hourly_leave' => false,
                );
                if (empty($entries)) {
                    continue;
                }
                foreach ($entries as $entry) {
                    if (!is_object($entry)) {
                        continue;
                    }
                    if ($entry->attendance_status == 1) {
                        if (!empty($entry->clockout_time)) {
                            $startdatetime = safe_strtotime($entry->date_in . ' ' . $entry->clockin_time);
                            $enddatetime = safe_strtotime($entry->date_out . ' ' . $entry->clockout_time);
                            $difference = max(0, $enddatetime - $startdatetime);
                            $minutes = (int) floor($difference / 60);
                            $cell['minutes'] += $minutes;
                            if (!empty($entry->leave_application_id)) {
                                $is_hours = get_row('tbl_leave_application', array('leave_application_id' => $entry->leave_application_id));
                                if (!empty($is_hours) && $is_hours->leave_type == 'hours') {
                                    $cell['hourly_leave'] = true;
                                }
                            }
                        }
                    } elseif ($entry->attendance_status == 'H') {
                        $cell['holiday'] = true;
                    } elseif ($entry->attendance_status == '3') {
                        $cell['leave'] = true;
                    } elseif ($entry->attendance_status == '0') {
                        $cell['absent'] = true;
                    }
                }
                $attendance_rows[$user_id]['days'][$loop_date] = $cell;
            }
        }
    }
}

$all_dates = array_keys($report_dates);
usort($all_dates, function ($a, $b) {
    return safe_strtotime($a) <=> safe_strtotime($b);
});

foreach ($attendance_rows as $user_id => $row) {
    foreach ($all_dates as $loop_date) {
        if (empty($attendance_rows[$user_id]['days'][$loop_date])) {
            $attendance_rows[$user_id]['days'][$loop_date] = array(
                'minutes' => 0,
                'holiday' => false,
                'leave' => false,
                'absent' => false,
                'hourly_leave' => false,
            );
        }

        $cell = $attendance_rows[$user_id]['days'][$loop_date];
        if ($cell['minutes'] > 0) {
            $attendance_rows[$user_id]['present_days']++;
            $attendance_rows[$user_id]['total_minutes'] += $cell['minutes'];
            $present_count++;
            $total_minutes_logged += $cell['minutes'];
        } elseif ($cell['holiday']) {
            $attendance_rows[$user_id]['holiday_days']++;
            $holiday_count++;
        } elseif ($cell['leave']) {
            $attendance_rows[$user_id]['leave_days']++;
            $leave_count++;
        } elseif ($cell['absent']) {
            $attendance_rows[$user_id]['absent_days']++;
            $absent_count++;
        }
    }
}

$total_hours_logged = floor($total_minutes_logged / 60);
$remaining_minutes_logged = $total_minutes_logged % 60;
$report_day_count = count($all_dates);
$average_minutes_per_present_day = $present_count > 0 ? (int) floor($total_minutes_logged / $present_count) : 0;
$average_hours = floor($average_minutes_per_present_day / 60);
$average_minutes = $average_minutes_per_present_day % 60;
?>

<?php if (!empty($date) && !empty($attendace_info)) : ?>
    <div id="printableArea" class="space-y-4">
        <section class="overflow-hidden rounded-2xl border border-border bg-card shadow-sm">
            <div class="border-b border-border px-5 py-4">
                <div class="flex flex-col gap-4 xl:flex-row xl:items-start xl:justify-between">
                    <div class="space-y-2">
                        <div class="inline-flex items-center gap-2 rounded-full border border-border bg-background px-3 py-1 text-xs font-medium text-muted-foreground">
                            <i data-lucide="calendar-range" class="h-3.5 w-3.5"></i>
                            <?= $month ?>
                        </div>
                        <div>
                            <h3 class="text-xl font-semibold text-foreground"><?= lang('attendance_report') ?></h3>
                            <p class="mt-1 text-sm text-muted-foreground"><?= lang('department') ?>: <?= $department_name ?></p>
                        </div>
                    </div>
                    <div class="flex flex-wrap items-center gap-2">
                        <a href="<?= base_url() ?>admin/attendance/attendance_pdf/1/<?= $departments_id . '/' . $date; ?>" class="inline-flex items-center gap-2 rounded-lg border border-border bg-background px-4 py-2.5 text-sm font-medium text-foreground transition hover:bg-muted/60">
                            <i data-lucide="file-text" class="h-4 w-4"></i>
                            <?= lang('pdf') ?>
                        </a>
                        <button type="button" onclick="printEmp_report('printableArea')" class="inline-flex items-center gap-2 rounded-lg bg-primary px-4 py-2.5 text-sm font-semibold text-primary-foreground transition hover:bg-primary/90">
                            <i data-lucide="printer" class="h-4 w-4"></i>
                            <?= lang('print') ?>
                        </button>
                    </div>
                </div>
            </div>

            <div class="grid grid-cols-2 gap-3 border-b border-border px-5 py-4 xl:grid-cols-6">
                <div class="rounded-xl border border-border bg-background/70 p-3">
                    <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('employee') ?></p>
                    <p class="mt-1 text-lg font-semibold text-foreground"><?= $employee_count ?></p>
                </div>
                <div class="rounded-xl border border-border bg-background/70 p-3">
                    <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('days') ?></p>
                    <p class="mt-1 text-lg font-semibold text-foreground"><?= $report_day_count ?></p>
                </div>
                <div class="rounded-xl border border-border bg-background/70 p-3">
                    <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('present') ?></p>
                    <p class="mt-1 text-lg font-semibold text-emerald-600 dark:text-emerald-300"><?= $present_count ?></p>
                </div>
                <div class="rounded-xl border border-border bg-background/70 p-3">
                    <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('on_leave') ?></p>
                    <p class="mt-1 text-lg font-semibold text-amber-600 dark:text-amber-300"><?= $leave_count ?></p>
                </div>
                <div class="rounded-xl border border-border bg-background/70 p-3">
                    <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('absent') ?></p>
                    <p class="mt-1 text-lg font-semibold text-rose-600 dark:text-rose-300"><?= $absent_count ?></p>
                </div>
                <div class="rounded-xl border border-border bg-background/70 p-3">
                    <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('average') . ' ' . lang('hours') ?></p>
                    <p class="mt-1 text-lg font-semibold text-primary"><?= $average_hours . ' : ' . str_pad($average_minutes, 2, '0', STR_PAD_LEFT) . ' m' ?></p>
                </div>
            </div>

            <div class="flex flex-col gap-3 border-b border-border px-5 py-4 lg:flex-row lg:items-center lg:justify-between">
                <div>
                    <h4 class="text-base font-semibold text-foreground"><?= lang('attendance_matrix') ?></h4>
                    <p class="text-sm text-muted-foreground">Day-wise attendance status and working hours for each employee.</p>
                </div>
                <div class="flex flex-wrap items-center gap-2">
                    <span class="inline-flex items-center gap-2 rounded-full border border-border bg-background px-3 py-1.5 text-xs font-medium text-muted-foreground"><span class="h-2 w-2 rounded-full bg-emerald-500"></span><?= lang('present') ?></span>
                    <span class="inline-flex items-center gap-2 rounded-full border border-border bg-background px-3 py-1.5 text-xs font-medium text-muted-foreground"><span class="h-2 w-2 rounded-full bg-amber-500"></span><?= lang('on_leave') ?></span>
                    <span class="inline-flex items-center gap-2 rounded-full border border-border bg-background px-3 py-1.5 text-xs font-medium text-muted-foreground"><span class="h-2 w-2 rounded-full bg-sky-500"></span><?= lang('holiday') ?></span>
                    <span class="inline-flex items-center gap-2 rounded-full border border-border bg-background px-3 py-1.5 text-xs font-medium text-muted-foreground"><span class="h-2 w-2 rounded-full bg-rose-500"></span><?= lang('absent') ?></span>
                </div>
            </div>

            <div class="p-5">
                <div class="overflow-x-auto rounded-xl border border-border">
                    <table class="min-w-full border-separate border-spacing-0 text-sm">
                        <thead>
                        <tr class="bg-muted/30 text-xs uppercase tracking-wide text-muted-foreground">
                            <th class="sticky left-0 z-20 border-b border-border bg-card px-4 py-3 text-left"><?= lang('employee') ?></th>
                            <?php foreach ($all_dates as $loop_date) : ?>
                                <th class="min-w-[84px] border-b border-l border-border bg-card px-2 py-3 text-center">
                                    <div class="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground"><?= date('D', safe_strtotime($loop_date)) ?></div>
                                    <div class="mt-1 text-sm font-semibold text-foreground"><?= date('d', safe_strtotime($loop_date)) ?></div>
                                </th>
                            <?php endforeach; ?>
                            <th class="sticky right-0 z-20 min-w-[116px] border-b border-l border-border bg-card px-4 py-3 text-center"><?= lang('total') ?></th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($attendance_rows as $row) : ?>
                            <tr class="group">
                                <td class="sticky left-0 z-10 border-b border-border bg-card px-4 py-3 align-top">
                                    <div class="font-medium text-foreground"><?= $row['employee']->fullname ?></div>
                                    <div class="mt-1 text-xs text-muted-foreground">
                                        <?= !empty($row['employee']->employment_id) ? $row['employee']->employment_id : lang('employee') ?>
                                        <?php if (!empty($row['employee']->designations)) : ?>
                                            <span class="mx-1">•</span><?= $row['employee']->designations ?>
                                        <?php endif; ?>
                                    </div>
                                </td>
                                <?php foreach ($all_dates as $loop_date) : ?>
                                    <?php $cell = $row['days'][$loop_date]; ?>
                                    <td class="border-b border-l border-border px-2 py-3 text-center">
                                        <?php if ($cell['minutes'] > 0) : ?>
                                            <?php
                                            $cell_hours = floor($cell['minutes'] / 60);
                                            $cell_minutes = $cell['minutes'] % 60;
                                            ?>
                                            <div class="inline-flex min-w-[60px] flex-col items-center rounded-lg bg-emerald-500/10 px-2 py-1.5 text-emerald-700 dark:text-emerald-300">
                                                <span class="text-xs font-semibold"><?= $cell_hours . ':' . str_pad($cell_minutes, 2, '0', STR_PAD_LEFT) ?></span>
                                                <?php if ($cell['hourly_leave']) : ?>
                                                    <span class="mt-1 text-[10px] font-medium"><?= lang('hourly') ?></span>
                                                <?php endif; ?>
                                            </div>
                                        <?php elseif ($cell['holiday']) : ?>
                                            <span class="inline-flex min-w-[60px] items-center justify-center rounded-lg bg-sky-500/10 px-2 py-1.5 text-xs font-semibold text-sky-700 dark:text-sky-300"><?= lang('holiday') ?></span>
                                        <?php elseif ($cell['leave']) : ?>
                                            <span class="inline-flex min-w-[60px] items-center justify-center rounded-lg bg-amber-500/10 px-2 py-1.5 text-xs font-semibold text-amber-700 dark:text-amber-300"><?= lang('leave') ?></span>
                                        <?php elseif ($cell['absent']) : ?>
                                            <span class="inline-flex min-w-[60px] items-center justify-center rounded-lg bg-rose-500/10 px-2 py-1.5 text-xs font-semibold text-rose-700 dark:text-rose-300"><?= lang('absent') ?></span>
                                        <?php else : ?>
                                            <span class="inline-flex min-w-[60px] items-center justify-center rounded-lg bg-muted/40 px-2 py-1.5 text-xs font-medium text-muted-foreground">--</span>
                                        <?php endif; ?>
                                    </td>
                                <?php endforeach; ?>
                                <?php
                                $row_total_hours = floor($row['total_minutes'] / 60);
                                $row_total_minutes = $row['total_minutes'] % 60;
                                ?>
                                <td class="sticky right-0 z-10 border-b border-l border-border bg-card px-4 py-3 text-center">
                                    <div class="inline-flex flex-col items-center rounded-lg bg-primary/10 px-3 py-2 text-primary">
                                        <span class="text-sm font-semibold"><?= $row_total_hours . ':' . str_pad($row_total_minutes, 2, '0', STR_PAD_LEFT) ?></span>
                                        <span class="mt-1 text-[10px] font-medium uppercase tracking-wide"><?= lang('hours') ?></span>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <div class="mt-4 grid grid-cols-1 gap-3 xl:grid-cols-3">
                    <div class="rounded-xl border border-border bg-background/70 p-4">
                        <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('working') . ' ' . lang('hours') ?></p>
                        <p class="mt-2 text-lg font-semibold text-foreground"><?= $total_hours_logged . ' : ' . str_pad($remaining_minutes_logged, 2, '0', STR_PAD_LEFT) . ' m' ?></p>
                        <p class="mt-1 text-sm text-muted-foreground">Total approved attendance hours in the selected report period.</p>
                    </div>
                    <div class="rounded-xl border border-border bg-background/70 p-4">
                        <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('attendance') . ' ' . lang('coverage') ?></p>
                        <p class="mt-2 text-lg font-semibold text-foreground"><?= $present_count + $leave_count + $holiday_count + $absent_count ?></p>
                        <p class="mt-1 text-sm text-muted-foreground">Tracked employee-day records across the selected department and dates.</p>
                    </div>
                    <div class="rounded-xl border border-border bg-background/70 p-4">
                        <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('report') . ' ' . lang('range') ?></p>
                        <p class="mt-2 text-lg font-semibold text-foreground"><?= $report_day_count ?> <?= lang('days') ?></p>
                        <p class="mt-1 text-sm text-muted-foreground"><?= !empty($all_dates) ? display_date(reset($all_dates)) . ' - ' . display_date(end($all_dates)) : lang('nothing_to_display') ?></p>
                    </div>
                </div>
            </div>
        </section>
    </div>
<?php endif; ?>

<script type="text/javascript">
    function printEmp_report(printableArea) {
        $('div.wrapper').find('.collapse').css('display', 'block');
        var printContents = document.getElementById(printableArea).innerHTML;
        var originalContents = document.body.innerHTML;
        document.body.innerHTML = printContents;
        window.print();
        document.body.innerHTML = originalContents;
    }
</script>
