<?php $__env->startSection('title'); ?>
    Hrm - <?php echo e($title); ?>

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

<?php $__env->startSection('styles'); ?>
    <style>
        .bootstrap-switch-large {
            width: 200px;
        }
    </style>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('navbar-content'); ?>
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="m-0">
                        HRM </h1>
                </div>
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="<?php echo e(route('home')); ?>">Dashboard</a></li>
                        <?php if(helper::roleAccess('inventorySetup.adjust.index')): ?>
                            <li class="breadcrumb-item"><a href="<?php echo e(route('hrm.attendance.index')); ?>">Hrm</a>
                            </li>
                        <?php endif; ?>
                        <li class="breadcrumb-item active"><span><?php echo e($title); ?></span></li>
                    </ol>
                </div><!-- /.col -->
            </div><!-- /.row -->
        </div><!-- /.container-fluid -->
    </div>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('admin-content'); ?>
    <div class="row">
        <div class="col-md-12">
            <div class="card card-default">
                <div class="card-header">
                    <h3 class="card-title">Attendance Log</h3>
                    <div class="card-tools">
                        <span id="buttons"></span>
                        <a class="btn btn-tool btn-default" data-card-widget="collapse">
                            <i class="fas fa-minus"></i>
                        </a>
                        <a class="btn btn-tool btn-default" data-card-widget="remove">
                            <i class="fas fa-times"></i>
                        </a>
                    </div>
                </div>
                <!-- /.card-header -->
                <div class="card-body">
                    <form action="<?php echo e(route('hrm.attendancelog.index')); ?>" method="POST">
                        <?php echo csrf_field(); ?>
                        <div class="form-group row">
                            <label for="employe" class="mt-2">Employee:</label>
                            <div class="col-md-3">
                                <select name="employee_id" class="form-control select2" id="employe">
                                    <option value="all">All</option>
                                    <?php $__currentLoopData = $employees; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $employee): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <option <?php echo e($request->employee_id == $employee->id ? 'selected' : ''); ?>

                                            value="<?php echo e($employee->id); ?>"><?php echo e($employee->name); ?></option>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                            </div>
                            <label for="From" class="mt-2">From:</label>
                            <div class="col-md-3">
                                <input type="date" id="From" value="<?php echo e($request->from ?? date('Y-m-d')); ?>"
                                    class="form-control" name="from">
                            </div>
                            <label for="To" class="mt-2">To:</label>
                            <div class="col-md-3">
                                <input type="date" id="To" value="<?php echo e($request->to ?? date('Y-m-d')); ?>"
                                    class="form-control" name="to">
                            </div>
                            <div class="col-md-1">
                                <button class="btn btn-success">Search</button>
                            </div>
                        </div>
                    </form>
                </div>
                <!-- /.card-body -->
            </div>
        </div>
        <!-- /.col-->
    </div>

    <div class="row" id="testDiv">
        <div class="col-md-12">
            <div class="card card-default">
                <div class="card-body">
                    <button class="btn btn-primary mb-3" onclick="printDiv('attendanceDiv')">Print</button>
                    <button onclick="downloadAttendancePDF()" class="btn btn-primary mb-3">Download PDF</button>
                    <div id="loadingIcon" style="display: none; text-align: center;">
                        <img src="https://cdn-icons-gif.flaticon.com/17905/17905715.gif" alt="Loading..." width="50">
                        <p>Generating PDF...</p>
                    </div>
                    <div id="attendanceDiv">
                        <?php if(isset($dayes)): ?>
                            <?php $__currentLoopData = $dayes; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $dayKey => $daye): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <h5 class="text-center mt-3">Attendance History of <?php echo e($daye->date); ?></h5>
                                <table class="table table-bordered">
                                    <thead>
                                        <tr>
                                            <th scope="col">SL</th>
                                            <th scope="col">Employee Name</th>
                                            <th scope="col"> In Time</th>
                                            <th scope="col"> Office In Time</th>
                                            <th scope="col"> Last Out Time</th>
                                            <th scope="col"> Worked Hours</th>
                                            <th scope="col"> OverTime Houre</th>
                                            <th scope="col"> Late</th>
                                            <th scope="col"> Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
   <?php 
$in = null; 
$lastin = null; 
$diff = null; 
$sld = 1; 
?> 

<?php $__currentLoopData = $attendances; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $attendance): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?> 
    <?php if($attendance->date == $daye->date): ?> 
        <?php
        // Format display times
        $signIn = date('h:i A', strtotime($attendance->sign_in));
        $last_in_time = date('h:i A', strtotime($attendance->employe->last_in_time));
        $signOut = $attendance->sign_out ? date('h:i A', strtotime($attendance->sign_out)) : '--';
        
        // Reference times using Carbon for consistency
        $officeStart = \Carbon\Carbon::parse($attendance->date)->setTime(8, 0); // 8:00 AM
        $officeEnd = \Carbon\Carbon::parse($attendance->date)->setTime(17, 0); // 5:00 PM
        $actualIn = \Carbon\Carbon::parse($attendance->date . ' ' . $attendance->sign_in);
        
        // Handle sign out - use actual time or current time if still working
        $actualOut = $attendance->sign_out ? 
            \Carbon\Carbon::parse($attendance->date . ' ' . $attendance->sign_out) : 
            \Carbon\Carbon::now();
        
        // Calculate total worked duration for display
        $workedDuration = $actualIn->diff($actualOut);
        
        // OVERTIME CALCULATION
        // Rule: Only time worked after 5:00 PM counts as overtime
        $overtimeMinutes = 0;
        
        // Step 1: Calculate time worked after 5:00 PM
        if ($actualOut->gt($officeEnd)) {
            $overtimeMinutes = $actualOut->diffInMinutes($officeEnd);
        }
        
        // Step 2: If clocked in late (after 8:00 AM), subtract late minutes from overtime
        if ($actualIn->gt($officeStart)) {
            $lateMinutes = $actualIn->diffInMinutes($officeStart);
            $overtimeMinutes = max($overtimeMinutes - $lateMinutes, 0);
        }
        
        // Step 3: Early clock-ins (before 8:00 AM) are completely ignored
        // Early arrival time is NOT added to overtime - only time after 5:00 PM counts
        
        // Format overtime display
        $overtimeHours = floor($overtimeMinutes / 60);
        $overtimeMins = $overtimeMinutes % 60;
        
        // Optional: Add debug info (remove in production)
        $debugInfo = [
            'actualIn' => $actualIn->format('H:i'),
            'actualOut' => $actualOut->format('H:i'),
            'timeAfter5PM' => $actualOut->gt($officeEnd) ? $actualOut->diffInMinutes($officeEnd) : 0,
            'lateMinutes' => $actualIn->gt($officeStart) ? $actualIn->diffInMinutes($officeStart) : 0,
            'finalOvertime' => $overtimeMinutes,
            'isEarlyArrival' => $actualIn->lt($officeStart),
            'isLateArrival' => $actualIn->gt($officeStart)
        ];
        ?>
        
        <tr>
            <td><?php echo e($attendance->employe->id_card); ?></td>
            <td><?php echo e($attendance->employe->name); ?></td>
            <td><?php echo e($signIn); ?></td>
            <td><?php echo e($last_in_time); ?></td>
            <td><?php echo e($signOut); ?></td>
            <td>
                <?php echo e($workedDuration->h); ?> : <?php echo e(str_pad($workedDuration->i, 2, '0', STR_PAD_LEFT)); ?> 
                <?php echo e(!$attendance->sign_out ? '(Running)' : ''); ?>

            </td>
            <td>
                <?php echo e($overtimeHours); ?> : <?php echo e(str_pad($overtimeMins, 2, '0', STR_PAD_LEFT)); ?>

               
            </td>
            <td>
                <?php echo e(CUSTOM_LATE_DAYS($attendance->employe, date('m', strtotime($daye->date)), date('d', strtotime($attendance->date))) == 1 ? 'Late' : 'N/A'); ?>

            </td>
            <td>
                <a href="<?php echo e(route('hrm.attendance.edit', $attendance->id)); ?>">
                    <i class="fa fa-edit" aria-hidden="true"></i>
                </a>
            </td>
        </tr>
        
        
        <!-- <tr class="debug-row" style="background-color: #f8f9fa; font-size: 12px;">
            <td colspan="9">
                Debug: In=<?php echo e($debugInfo['actualIn']); ?>, Out=<?php echo e($debugInfo['actualOut']); ?>, 
                After5PM=<?php echo e($debugInfo['timeAfter5PM']); ?>min, Late=<?php echo e($debugInfo['lateMinutes']); ?>min, 
                Final=<?php echo e($debugInfo['finalOvertime']); ?>min, Early=<?php echo e($debugInfo['isEarlyArrival'] ? 'YES' : 'NO'); ?>

            </td>
        </tr> -->
    <?php endif; ?> 
<?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>


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

    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/2.4.3/purify.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>

    <script>
        function printDiv(divId) {
            const content = document.getElementById(divId).innerHTML;

            // Create a new window
            const printWindow = window.open('', '_blank', 'height=600,width=800');

            // Write the content into the new window
            printWindow.document.open();
            printWindow.document.write(`
                                   <html>
                                   <head>
                                       <title>Print</title>
                                       <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
                                       <style>
                                           body {
                                               margin: 20px;
                                           }
                                           table {
                                               width: 100%;
                                               border-collapse: collapse;
                                           }
                                           table, th, td {
                                               border: 1px solid black;
                                           }
                                       </style>
                                   </head>
                                   <body>
                                       ${content}
                                   </body>
                                   </html>
                     `);
            printWindow.document.close();

            // Wait for the content to load, then print
            printWindow.onload = function() {
                printWindow.focus();
                printWindow.print();
                printWindow.close();
            };
        }

        function downloadAttendancePDF() {
            const {
                jsPDF
            } = window.jspdf;
            let doc = new jsPDF('p', 'mm', 'a4');

            let element = document.getElementById("attendanceDiv");
            let loadingIcon = document.getElementById("loadingIcon");

            // Show loading icon
            loadingIcon.style.display = "block";

            html2canvas(element, {
                scale: 2
            }).then(canvas => {
                let imgData = canvas.toDataURL("image/png");
                let imgWidth = 190;
                let pageHeight = 297;
                let imgHeight = (canvas.height * imgWidth) / canvas.width;
                let heightLeft = imgHeight;
                let position = 10;

                doc.addImage(imgData, 'PNG', 10, position, imgWidth, imgHeight);
                heightLeft -= pageHeight;

                while (heightLeft > 0) {
                    position -= pageHeight;
                    doc.addPage();
                    doc.addImage(imgData, 'PNG', 10, position, imgWidth, imgHeight);
                    heightLeft -= pageHeight;
                }

                doc.save("Attendance_Report.pdf");

                // Hide loading icon after download
                loadingIcon.style.display = "none";
            });
        }
    </script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('backend.layouts.master', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH F:\XAMPP\htdocs\jubayer\resources\views/backend/pages/hrm/attendance/attendance-log/index.blade.php ENDPATH**/ ?>