<?= message_box('success'); ?>
<?= message_box('error'); ?>
<?php
$session_user_id = $this->session->userdata('user_id');
$selected_user_id = !empty($user_id) ? $user_id : $session_user_id;
$selected_user = !empty($selected_user_id) ? get_staff_details($selected_user_id) : null;
$selected_user_label = !empty($selected_user) ? $selected_user->employment_id . ' - ' . $selected_user->fullname . ' ( ' . $selected_user->designations . ' )' : '';
$display_name = !empty($edit) && !empty($selected_user) ? $selected_user->fullname : lang('my');
$active_year = !empty($active) ? $active : (!empty($mytime_info) ? array_key_first($mytime_info) : null);
$year_count = !empty($mytime_info) ? count($mytime_info) : 0;
$day_count = 0;
$total_minutes_logged = 0;
$year_summaries = array();
if (!empty($mytime_info)) {
    foreach ($mytime_info as $year => $year_time) {
        $year_summaries[$year] = array(
            'days' => 0,
            'minutes' => 0,
            'entries' => 0,
            'rows' => array(),
        );
        if (!empty($year_time)) {
            foreach ($year_time as $week_time) {
                if (empty($week_time)) {
                    continue;
                }
                foreach ($week_time as $date_label => $time_entries) {
                    if (empty($time_entries) || !is_array($time_entries)) {
                        continue;
                    }
                    $day_count++;
                    $year_summaries[$year]['days']++;

                    $attendance_row = null;
                    foreach ($time_entries as $attendance_rows) {
                        if (empty($attendance_rows)) {
                            continue;
                        }
                        if (is_array($attendance_rows) && isset($attendance_rows[0]) && is_object($attendance_rows[0])) {
                            $attendance_row = $attendance_rows[0];
                            break;
                        }
                        if (is_object($attendance_rows)) {
                            $attendance_row = $attendance_rows;
                            break;
                        }
                    }
                    if (empty($attendance_row)) {
                        continue;
                    }

                    $sort_date = !empty($attendance_row->date_in) ? safe_strtotime($attendance_row->date_in) : safe_strtotime($date_label);
                    $base_row = array(
                        'date_label' => $date_label,
                        'date_value' => !empty($attendance_row->date_in) ? $attendance_row->date_in : '',
                        'sort_date' => $sort_date,
                        'status' => 'empty',
                        'clock_in' => '-',
                        'clock_out' => '-',
                        'ip_address' => '-',
                        'duration' => '-',
                        'clock_id' => null,
                    );

                    if (!empty($attendance_row->attendance_status) && $attendance_row->attendance_status == 1) {
                        $clock_rows = get_result('tbl_clock', array('attendance_id' => $attendance_row->attendance_id));
                        if (!empty($clock_rows)) {
                            foreach ($clock_rows as $clock_row) {
                                $row = $base_row;
                                $row['clock_in'] = !empty($clock_row->clockin_time) ? display_time($clock_row->clockin_time) : '-';
                                $row['clock_out'] = !empty($clock_row->clockout_time) ? display_time($clock_row->clockout_time) : lang('currently_clock_in');
                                $row['ip_address'] = !empty($clock_row->ip_address) ? $clock_row->ip_address : '-';
                                $row['clock_id'] = !empty($clock_row->clock_id) ? $clock_row->clock_id : null;
                                $row['status'] = empty($clock_row->clockout_time) ? 'open' : 'present';

                                if (!empty($clock_row->clockout_time)) {
                                    $startdatetime = safe_strtotime($attendance_row->date_in . ' ' . $clock_row->clockin_time);
                                    $enddatetime = safe_strtotime($attendance_row->date_out . ' ' . $clock_row->clockout_time);
                                    $difference = max(0, $enddatetime - $startdatetime);
                                    $minutes = (int) floor($difference / 60);
                                    $hours = floor($minutes / 60);
                                    $mins = $minutes % 60;
                                    $row['duration'] = $hours . ' : ' . str_pad($mins, 2, '0', STR_PAD_LEFT) . ' m';
                                    $total_minutes_logged += $minutes;
                                    $year_summaries[$year]['minutes'] += $minutes;
                                }
                                $year_summaries[$year]['entries']++;
                                $year_summaries[$year]['rows'][] = $row;
                            }
                        } else {
                            $base_row['status'] = 'present';
                            $year_summaries[$year]['rows'][] = $base_row;
                        }
                    } elseif ((string) $attendance_row->attendance_status === '0') {
                        $base_row['status'] = 'absent';
                        $year_summaries[$year]['rows'][] = $base_row;
                    } elseif ((string) $attendance_row->attendance_status === '3') {
                        $base_row['status'] = 'leave';
                        $year_summaries[$year]['rows'][] = $base_row;
                    } else {
                        $base_row['status'] = 'holiday';
                        $year_summaries[$year]['rows'][] = $base_row;
                    }
                }
            }
            usort($year_summaries[$year]['rows'], function ($a, $b) {
                return ($b['sort_date'] ?? 0) <=> ($a['sort_date'] ?? 0);
            });
        }
    }
}
$total_hours_logged = floor($total_minutes_logged / 60);
$remaining_minutes_logged = $total_minutes_logged % 60;
?>

<div class="space-y-4">
    <?php if ($this->session->userdata('user_type') == '1') : ?>
        <section class="rounded-2xl border border-border bg-card shadow-sm">
            <div class="border-b border-border px-5 py-4">
                <div class="space-y-1">
                    <h2 class="text-xl font-semibold tracking-tight text-foreground"><?= lang('view_time_history') ?></h2>
                    <p class="max-w-3xl text-sm text-muted-foreground">Search and review employee time logs in a single attendance archive.</p>
                </div>
            </div>
            <div class="px-5 py-4">
                <form id="attendance-form" action="<?= base_url(); ?>admin/attendance/time_history" method="post" class="space-y-4">
                    <div class="grid grid-cols-1 gap-3 xl:grid-cols-12">
                        <div class="xl:col-span-8">
                            <?= form_grouped_lookup_group('user_id', lang('employee'), grouped_staff_lookup_groups(), $selected_user_id, $selected_user_label, true, array('id' => 'employee'), '', array()) ?>
                        </div>
                        <div class="xl:col-span-2 flex items-end">
                            <button type="submit" name="search" value="1" class="inline-flex h-10 w-fit items-center justify-center gap-2 rounded-lg bg-primary px-4  text-sm font-semibold text-primary-foreground transition hover:bg-primary/90">
                                <i data-lucide="search" class="h-4 w-4"></i>
                                <?= lang('go') ?>
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </section>
    <?php endif; ?>

    <section id="printableArea" 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="timer-reset" class="h-3.5 w-3.5"></i>
                        <?= lang('time_logs') ?>
                    </div>
                    <div>
                        <h3 class="text-xl font-semibold text-foreground"><?= $display_name . ' ' . lang('time_logs') ?></h3>
                        <p class="mt-1 text-sm text-muted-foreground">Employee clock archive with yearly attendance history and detailed log records.</p>
                    </div>
                </div>
                <div class="flex flex-wrap items-center gap-2">
                    <div 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('working') . ' ' . lang('hours') ?>
                    </div>
                    <div 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-violet-500"></span><?= lang('currently_clock_in') ?>
                    </div>
                    <div 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') ?>
                    </div>
                </div>
            </div>
        </div>

            <div class="grid grid-cols-2 gap-3 border-b border-border px-5 py-4 xl:grid-cols-4">
                <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"><?= !empty($selected_user) ? $selected_user->fullname : $display_name ?></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">Years</p>
                    <p class="mt-1 text-lg font-semibold text-foreground"><?= $year_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"><?= $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('working') . ' ' . lang('hours') ?></p>
                    <p class="mt-1 text-lg font-semibold text-primary"><?= $total_hours_logged . ' : ' . str_pad($remaining_minutes_logged, 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('time_log_archive') ?></h4>
                    <p class="text-sm text-muted-foreground">Browse year-by-year attendance history in one clean continuous time ledger.</p>
                </div>
        </div>

        <?php if (!empty($mytime_info)) : ?>
            <div class="p-5">
                <div class="mb-4 flex flex-wrap gap-2">
                    <?php foreach ($mytime_info as $year => $v_time_info) : ?>
                        <?php if (!empty($v_time_info)) : ?>
                            <button type="button"
                                    class="js-time-year-trigger inline-flex items-center rounded-lg border px-4 py-2 text-sm font-medium transition <?= (string) $year === (string) $active_year ? 'border-primary bg-primary text-primary-foreground shadow-sm' : 'border-border bg-background text-foreground hover:bg-muted/60' ?>"
                                    data-target-year="<?= html_escape($year) ?>">
                                <?= $year ?>
                            </button>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </div>

                <div class="space-y-4">
                    <?php foreach ($mytime_info as $year => $v_time_info) : ?>
                        <?php if (empty($v_time_info)) { continue; } ?>
                        <?php
                        $year_hours = 0;
                        $year_minutes = 0;
                        if (!empty($year_summaries[$year]['minutes'])) {
                            $year_hours = floor($year_summaries[$year]['minutes'] / 60);
                            $year_minutes = $year_summaries[$year]['minutes'] % 60;
                        }
                        ?>
                        <section class="js-time-year-panel space-y-4 <?= (string) $year === (string) $active_year ? '' : 'hidden' ?>" data-year-panel="<?= html_escape($year) ?>">
                            <div class="grid grid-cols-1 gap-3 lg:grid-cols-4">
                                <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('year') ?></p>
                                    <p class="mt-2 text-lg font-semibold text-foreground"><?= $year ?></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('days') ?></p>
                                    <p class="mt-2 text-lg font-semibold text-foreground"><?= !empty($year_summaries[$year]['days']) ? $year_summaries[$year]['days'] : 0 ?></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('entries') ?></p>
                                    <p class="mt-2 text-lg font-semibold text-foreground"><?= !empty($year_summaries[$year]['entries']) ? $year_summaries[$year]['entries'] : 0 ?></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('working') . ' ' . lang('hours') ?></p>
                                    <p class="mt-2 text-lg font-semibold text-primary"><?= $year_hours . ' : ' . str_pad($year_minutes, 2, '0', STR_PAD_LEFT) . ' m' ?></p>
                                </div>
                            </div>

                            <div class="overflow-x-auto rounded-xl border border-border bg-card">
                                <table class="min-w-full text-sm">
                                    <thead class="border-b border-border text-xs uppercase tracking-wide text-muted-foreground">
                                    <tr>
                                        <th class="px-4 py-3 text-left"><?= lang('date') ?></th>
                                        <th class="px-4 py-3 text-left"><?= lang('clock_in_time') ?></th>
                                        <th class="px-4 py-3 text-left"><?= lang('clock_out_time') ?></th>
                                        <th class="px-4 py-3 text-left"><?= lang('ip_address') ?></th>
                                        <th class="px-4 py-3 text-left"><?= lang('hours') ?></th>
                                        <th class="px-4 py-3 text-left"><?= lang('status') ?></th>
                                        <th class="px-4 py-3 text-left hidden-print"><?= lang('action') ?></th>
                                    </tr>
                                    </thead>
                                    <tbody class="divide-y divide-border">
                                    <?php if (!empty($year_summaries[$year]['rows'])) : ?>
                                        <?php foreach ($year_summaries[$year]['rows'] as $index => $row) : ?>
                                            <tr id="<?= !empty($row['clock_id']) ? 'table_' . $row['clock_id'] : 'history_row_' . $year . '_' . $index ?>">
                                                <td class="px-4 py-3">
                                                    <div class="font-medium text-foreground"><?= $row['date_label'] ?></div>
                                                    <?php if (!empty($row['date_value'])) : ?>
                                                        <div class="text-xs text-muted-foreground"><?= date('D', safe_strtotime($row['date_value'])) ?></div>
                                                    <?php endif; ?>
                                                </td>
                                                <td class="px-4 py-3"><?= $row['clock_in'] ?></td>
                                                <td class="px-4 py-3">
                                                    <?php if ($row['status'] === 'open') : ?>
                                                        <span class="inline-flex items-center rounded-full bg-violet-500/10 px-2.5 py-1 text-xs font-semibold text-violet-600 dark:text-violet-300"><?= lang('currently_clock_in') ?></span>
                                                    <?php else : ?>
                                                        <?= $row['clock_out'] ?>
                                                    <?php endif; ?>
                                                </td>
                                                <td class="px-4 py-3"><?= $row['ip_address'] ?></td>
                                                <td class="px-4 py-3">
                                                    <?php if ($row['duration'] !== '-') : ?>
                                                        <span class="inline-flex items-center rounded-full bg-emerald-500/10 px-2.5 py-1 text-xs font-semibold text-emerald-600 dark:text-emerald-300"><?= $row['duration'] ?></span>
                                                    <?php else : ?>
                                                        <span class="text-muted-foreground"><?= $row['duration'] ?></span>
                                                    <?php endif; ?>
                                                </td>
                                                <td class="px-4 py-3">
                                                    <?php if ($row['status'] === 'present') : ?>
                                                        <span class="inline-flex items-center rounded-full bg-emerald-500/10 px-2.5 py-1 text-xs font-semibold text-emerald-600 dark:text-emerald-300"><?= lang('present') ?></span>
                                                    <?php elseif ($row['status'] === 'open') : ?>
                                                        <span class="inline-flex items-center rounded-full bg-violet-500/10 px-2.5 py-1 text-xs font-semibold text-violet-600 dark:text-violet-300"><?= lang('currently_clock_in') ?></span>
                                                    <?php elseif ($row['status'] === 'leave') : ?>
                                                        <span class="inline-flex items-center rounded-full bg-amber-500/10 px-2.5 py-1 text-xs font-semibold text-amber-600 dark:text-amber-300"><?= lang('on_leave') ?></span>
                                                    <?php elseif ($row['status'] === 'holiday') : ?>
                                                        <span class="inline-flex items-center rounded-full bg-sky-500/10 px-2.5 py-1 text-xs font-semibold text-sky-600 dark:text-sky-300"><?= lang('holiday') ?></span>
                                                    <?php elseif ($row['status'] === 'absent') : ?>
                                                        <span class="inline-flex items-center rounded-full bg-rose-500/10 px-2.5 py-1 text-xs font-semibold text-rose-600 dark:text-rose-300"><?= lang('absent') ?></span>
                                                    <?php else : ?>
                                                        <span class="text-muted-foreground">-</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td class="px-4 py-3 hidden-print">
                                                    <?php if (!empty($row['clock_id'])) : ?>
                                                        <?php if (isset($edited) && !empty($edited)) { echo btn_edit_modal('admin/attendance/edit_mytime/' . $row['clock_id']); } ?>
                                                        <?php if (!empty(admin())) { echo ajax_anchor(base_url('admin/attendance/delete_mytime/' . $row['clock_id']), lang('delete'), array("class" => "", "title" => lang('delete'), "data-fade-out-on-success" => "#" . (!empty($row['clock_id']) ? 'table_' . $row['clock_id'] : 'history_row_' . $year . '_' . $index))); } ?>
                                                    <?php else : ?>
                                                        <span class="text-muted-foreground">-</span>
                                                    <?php endif; ?>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php else : ?>
                                        <tr>
                                            <td colspan="7" class="px-4 py-8 text-center text-sm text-muted-foreground"><?= lang('nothing_to_display') ?></td>
                                        </tr>
                                    <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </section>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php else : ?>
            <div class="px-6 py-10 text-sm text-muted-foreground"><?= lang('nothing_to_display') ?></div>
        <?php endif; ?>
    </section>
</div>

<script type="text/javascript">
    window.timeHistoryPrintHtml = <?= json_encode(isset($time_history_print_html) ? $time_history_print_html : '', JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>;
    function printEmp_report(printableArea) {
        var fallback = document.getElementById(printableArea);
        var printHtml = window.timeHistoryPrintHtml || (fallback ? fallback.outerHTML : '');
        if (!printHtml) return false;

        var printWindow = window.open('', 'PRINT', 'height=900,width=1200');
        if (!printWindow) {
            if (typeof window.erpNativePrint === 'function') {
                window.erpNativePrint();
            } else if (typeof window.print === 'function') {
                window.print();
            }
            return false;
        }

        printWindow.document.open();
        printWindow.document.write(printHtml);
        printWindow.document.close();

        var printed = false;
        var doPrint = function() {
            if (printed || printWindow.closed) return;
            printed = true;
            printWindow.focus();
            if (typeof printWindow.print === 'function') {
                printWindow.print();
            }
            printWindow.close();
        };
        printWindow.onload = function() {
            printWindow.setTimeout(doPrint, 350);
        };
        printWindow.setTimeout(doPrint, 1000);
        return false;
    }

    document.addEventListener('click', function (event) {
        var trigger = event.target.closest('.js-time-year-trigger');
        if (!trigger) {
            return;
        }
        var targetYear = trigger.getAttribute('data-target-year');
        document.querySelectorAll('.js-time-year-trigger').forEach(function (button) {
            button.classList.remove('border-primary', 'bg-primary', 'text-primary-foreground', 'shadow-sm');
            button.classList.add('border-border', 'bg-background', 'text-foreground');
        });
        trigger.classList.remove('border-border', 'bg-background', 'text-foreground');
        trigger.classList.add('border-primary', 'bg-primary', 'text-primary-foreground', 'shadow-sm');

        document.querySelectorAll('.js-time-year-panel').forEach(function (panel) {
            panel.classList.toggle('hidden', panel.getAttribute('data-year-panel') !== targetYear);
        });
    });
</script>
