<?php
$staff_count = !empty($users) ? count($users) : 0;
$currently_clocked = 0;
$completed_logs = 0;
$off_day_count = 0;
if (!empty($attendace_info)) {
    foreach ($attendace_info as $entries) {
        $has_completed = false;
        $has_open = false;
        $has_off = false;
        if (!empty($entries)) {
            foreach ($entries as $entry) {
                if (!is_object($entry)) {
                    continue;
                }
                if (!empty($entry->attendance_status) && ($entry->attendance_status === 'H' || $entry->attendance_status == 3 || $entry->attendance_status == 0)) {
                    $has_off = true;
                }
                if (!empty($entry->clockout_time)) {
                    $has_completed = true;
                }
                if (!empty($entry->attendance_status) && $entry->attendance_status == 1 && empty($entry->clockout_time)) {
                    $has_open = true;
                }
            }
        }
        if ($has_open) {
            $currently_clocked++;
        }
        if ($has_completed) {
            $completed_logs++;
        }
        if ($has_off) {
            $off_day_count++;
        }
    }
}
?>

<script type="text/javascript">
    $(document).ready(function () {
        $('#select_all').change(function () {
            var checked = this.checked;
            $(':checkbox[data-attendance-check]').prop('checked', checked);
        });
        $('#select_all_clock_in').change(function () {
            $('.clock_in').prop('checked', this.checked);
        });
        $('#select_all_clock_out').change(function () {
            $('.clock_out').prop('checked', this.checked);
        });
        $('#Transation_DataTables').dataTable({
            paging: false,
            "bSort": false
        });
    });
</script>

<div 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-end xl:justify-between">
                <div class="space-y-1">
                    <h2 class="text-xl font-semibold tracking-tight text-foreground"><?= lang('mark_attendance') ?></h2>
                    <p class="max-w-3xl text-sm text-muted-foreground">Daily attendance board for bulk clock actions and direct staff updates.</p>
                </div>
                <form action="<?= base_url('admin/mark_attendance') ?>" method="get" class="flex w-full flex-col gap-3 sm:w-auto sm:flex-row sm:items-end">
                    <div class="w-full sm:w-64">
                        <?= form_datepicker('date', lang('date'), $selected_date, false, array('data-auto-close' => 'true')); ?>
                    </div>
                    <button type="submit" class="inline-flex h-9 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>
                </form>
            </div>
        </div>

        <div class="grid grid-cols-2 gap-3 border-b border-border px-5 py-4 lg: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"><?= $staff_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('currently_clock_in') ?></p>
                <p class="mt-1 text-lg font-semibold text-emerald-600 dark:text-emerald-300"><?= $currently_clocked ?></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('clock_out') ?></p>
                <p class="mt-1 text-lg font-semibold text-sky-600 dark:text-sky-300"><?= $completed_logs ?></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('holiday') ?>/<?= lang('on_leave') ?></p>
                <p class="mt-1 text-lg font-semibold text-amber-600 dark:text-amber-300"><?= $off_day_count ?></p>
            </div>
        </div>

        <form action="<?= base_url() ?>admin/attendance/update_clock" method="post" class="space-y-6">
            <input type="hidden" name="selected_date" value="<?= html_escape($selected_date) ?>">

            <div class="flex flex-col gap-3 border-b border-border px-5 py-4 xl:flex-row xl:items-center xl:justify-between">
                <div>
                    <h3 class="text-base font-semibold text-foreground"><?= date('F d, Y', safe_strtotime($selected_date)) ?></h3>
                    <p class="text-sm text-muted-foreground">Select staff for bulk clock updates or use the direct action per row.</p>
                </div>
                <div class="flex flex-wrap items-center gap-4 text-sm">
                    <label class="inline-flex items-center gap-2 rounded-lg border border-border bg-background px-3 py-2 text-foreground">
                        <input id="select_all_clock_in" type="checkbox" class="h-4 w-4 rounded border-input text-primary focus:ring-primary/20">
                        <span><?= lang('mark_as_clock_in') ?></span>
                    </label>
                    <label class="inline-flex items-center gap-2 rounded-lg border border-border bg-background px-3 py-2 text-foreground">
                        <input id="select_all_clock_out" type="checkbox" class="h-4 w-4 rounded border-input text-primary focus:ring-primary/20">
                        <span><?= lang('mark_as_clock_out') ?></span>
                    </label>
                    <label class="inline-flex items-center gap-2 rounded-lg border border-border bg-background px-3 py-2 text-foreground">
                        <input id="select_all" type="checkbox" class="h-4 w-4 rounded border-input text-primary focus:ring-primary/20">
                        <span><?= lang('mark_all') ?></span>
                    </label>
                    <button type="submit" 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="save" class="h-4 w-4"></i>
                        <?= lang('update') ?>
                    </button>
                </div>
            </div>

            <div class="p-5 pt-0">
                <div class="overflow-x-auto rounded-xl border border-border bg-card">
                    <table class="min-w-full text-sm" id="Transation_DataTables">
                        <thead class="border-b border-border text-xs uppercase tracking-wide text-muted-foreground">
                        <tr>
                            <th class="px-4 py-3 text-left"><?= lang('select') ?></th>
                            <th class="px-4 py-3 text-left"><?= lang('emp_id') ?></th>
                            <th class="px-4 py-3 text-left"><?= lang('name') ?></th>
                            <th class="px-4 py-3 text-left"><?= lang('clocking_hours') ?></th>
                        </tr>
                        </thead>
                        <tbody class="divide-y divide-border">
                        <?php
                        $clock_button_loc = '';
                        $allow_geo_clock_in = config_item('allow_geo_clock_in');
                        if (!empty($allow_geo_clock_in) && $allow_geo_clock_in == 'TRUE') {
                            $clock_button_loc = 'clock_button_loc';
                        }

                        if ((!empty($date)) && !empty($attendace_info)) {
                            foreach ($attendace_info as $nkey => $v_attendace_info) {
                                $already_clock = null;
                                $currently_clock_in = null;
                                $clock_id = null;
                                $holiday = null;
                                $name = 'clock_in';
                                $total_hh = 0;
                                $total_mm = 0;
                                if (!empty($v_attendace_info)) {
                                    foreach ($v_attendace_info as $v_mytime) {
                                        if (!is_object($v_mytime)) {
                                            continue;
                                        }
                                        if ($v_mytime->attendance_status == 1) {
                                            if (!empty($v_mytime->clockout_time)) {
                                                $startdatetime = safe_strtotime($v_mytime->date_in . " " . $v_mytime->clockin_time);
                                                $enddatetime = safe_strtotime($v_mytime->date_out . " " . $v_mytime->clockout_time);
                                                $difference = $enddatetime - $startdatetime;
                                                $days = abs(floor($difference / 86400));
                                                $hours = abs(floor(($difference - ($days * 86400)) / 3600));
                                                $mins = abs(floor(($difference - ($days * 86400) - ($hours * 3600)) / 60));
                                                $total_mm += $mins;
                                                $total_hh += $hours;
                                                $already_clock = true;
                                            } else {
                                                $currently_clock_in = '<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>';
                                                $clock_id = $v_mytime->clock_id;
                                                $name = 'clock_out';
                                            }
                                        } elseif ($v_mytime->attendance_status == 'H') {
                                            $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>';
                                        } elseif ($v_mytime->attendance_status == '3') {
                                            $holiday = '<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>';
                                        } elseif ($v_mytime->attendance_status == '0') {
                                            $holiday = '<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>';
                                        }
                                    }
                                }
                                ?>
                                <tr>
                                    <td class="px-4 py-3">
                                        <label class="inline-flex items-center">
                                            <input type="checkbox" data-attendance-check class="<?= $name ?> h-4 w-4 rounded border-input text-primary focus:ring-primary/20" name="<?= $name; ?>[]" value="<?= $users[$nkey]->user_id; ?>">
                                        </label>
                                        <input type="hidden" name="<?= $users[$nkey]->user_id; ?>" value="<?= $clock_id; ?>">
                                    </td>
                                    <td class="px-4 py-3 font-medium text-foreground"><?= $users[$nkey]->employment_id; ?></td>
                                    <td class="px-4 py-3">
                                        <div class="font-medium text-foreground"><?= $users[$nkey]->fullname; ?></div>
                                        <div class="text-xs text-muted-foreground"><?= !empty($users[$nkey]->designations) ? $users[$nkey]->designations : lang('employee') ?></div>
                                    </td>
                                    <td class="px-4 py-3">
                                        <div class="flex flex-wrap items-center gap-2">
                                            <?php
                                            if (!empty($already_clock)) {
                                                if ($total_mm > 59) {
                                                    $total_hh += intval($total_mm / 60);
                                                    $total_mm = intval($total_mm % 60);
                                                }
                                                echo '<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">' . $total_hh . ' : ' . $total_mm . ' m</span>';
                                            }
                                            if (!empty($currently_clock_in)) {
                                                echo $currently_clock_in . ' <a class="inline-flex items-center rounded-full bg-rose-500 px-3 py-1 text-xs font-semibold text-white transition hover:bg-rose-600 ' . $clock_button_loc . '" href="' . base_url() . 'admin/attendance/set_clocking/' . $clock_id . '/' . $users[$nkey]->user_id . '?date=' . $selected_date . '">' . lang('clock_out') . '</a>';
                                            } else {
                                                echo $holiday . ' <a class="inline-flex items-center rounded-full bg-emerald-500 px-3 py-1 text-xs font-semibold text-white transition hover:bg-emerald-600 ' . $clock_button_loc . '" href="' . base_url() . 'admin/attendance/set_clocking/0/' . $users[$nkey]->user_id . '/1?date=' . $selected_date . '">' . lang('clock_in') . '</a>';
                                            }
                                            ?>
                                        </div>
                                    </td>
                                </tr>
                                <?php
                            }
                        }
                        ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </form>
    </section>
</div>
