<?php $__env->startSection('content'); ?>
<div class="card shadow-sm border-0">
    <div class="card-header bg-white py-3">
        <div class="row align-items-center">
            <div class="col">
                <h5 class="mb-0 fw-bold"><i class="bi bi-calendar-check-fill text-primary"></i> Mark Attendance</h5>
                <p class="text-muted small mb-0">Process raw attendance data into marked records based on shifts and leaves.</p>
            </div>
        </div>
    </div>

    <div class="card-body">
        <form id="markForm">
            <?php echo csrf_field(); ?>
            <div class="row g-3">
                <div class="col-md-4">
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Branch <span class="text-danger">*</span></label>
                        <select name="branch_id" id="branch_id" class="form-select" required>
                            <option value="">Select Branch</option>
                            <?php $__currentLoopData = $branches; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $branch): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <option value="<?php echo e($branch->id); ?>"><?php echo e($branch->name); ?></option>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </select>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Start Date <span class="text-danger">*</span></label>
                        <input type="date" name="start_date" id="start_date" class="form-control" required 
                               value="<?php echo e(date('Y-m-01')); ?>">
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="mb-3">
                        <label class="form-label fw-semibold">End Date <span class="text-danger">*</span></label>
                        <input type="date" name="end_date" id="end_date" class="form-control" required 
                               value="<?php echo e(date('Y-m-d')); ?>">
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-12">
                    <div class="form-check form-switch p-3 bg-light rounded border">
                        <input class="form-check-input ms-0" type="checkbox" name="use_raw_punches" id="use_raw_punches" value="1">
                        <label class="form-check-label ms-2 fw-semibold text-danger" for="use_raw_punches">
                            <i class="bi bi-exclamation-triangle-fill"></i> Overwrite with Raw Data
                        </label>
                        <p class="text-muted small mb-0 ms-2 mt-1">Check this to pull original device data and overwrite any manual edits in selected date range.</p>
                    </div>
                </div>
            </div>

            <div class="d-flex justify-content-end mt-3">
                <button type="submit" class="btn btn-primary px-4" id="markBtn">
                    <i class="bi bi-play-fill"></i> Start Marking Process
                </button>
            </div>
        </form>

        <!-- Result Section -->
        <div id="resultSection" class="mt-4" style="display: none;">
            <hr>
            <div class="alert" id="resultAlert">
                <h5 id="resultTitle" class="fw-bold"></h5>
                <div id="resultStats" class="mt-2"></div>
                <div id="resultErrors" class="mt-3" style="display: none;">
                    <h6 class="text-danger fw-bold"><i class="bi bi-exclamation-octagon"></i> Processing Errors:</h6>
                    <div class="table-responsive">
                        <table class="table table-sm table-bordered mt-2">
                            <thead class="table-light">
                                <tr>
                                    <th>Emp Code</th>
                                    <th>Date</th>
                                    <th>Error Message</th>
                                </tr>
                            </thead>
                            <tbody id="errorList"></tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('scripts'); ?>
<script>
$(function() {
    $('#use_raw_punches').on('change', function(e) {
        if (this.checked) {
            let checkbox = this;
            checkbox.checked = false;
            
            Swal.fire({
                title: 'Are you sure?',
                text: "Enabling this will overwrite any manual attendance edits with raw device data for the selected period.",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d33',
                confirmButtonText: 'Yes, allow overwrite',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    checkbox.checked = true;
                }
            });
        }
    });

    $('#markForm').on('submit', function(e) {
        e.preventDefault();

        let formData = $(this).serialize();
        
        Swal.fire({
            title: 'Confirm Processing',
            text: 'Are you sure you want to mark attendance for the selected date range? This will overwrite existing (unlocked) attendance records.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, start it'
        }).then((result) => {
            if (result.isConfirmed) {
                processAttendance(formData);
            }
        });
    });

    function processAttendance(formData) {
        $('#markBtn').prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span> Processing...');
        $('#resultSection').hide();

        $.ajax({
            url: "<?php echo e(route('attendance.process.mark')); ?>",
            type: 'POST',
            data: formData,
            success: function(res) {
                showResult(res);
            },
            error: function(xhr) {
                let msg = xhr.responseJSON?.message || 'Processing failed. Please check server logs.';
                showResult({
                    status: false,
                    message: msg,
                    data: xhr.responseJSON?.data || null
                });
            },
            complete: function() {
                $('#markBtn').prop('disabled', false).html('<i class="bi bi-play-fill"></i> Start Marking Process');
            }
        });
    }

    function showResult(res) {
        let alertClass = res.status ? 'alert-success' : 'alert-danger';
        let title = res.status ? 'Process Completed!' : 'Process Failed';

        $('#resultAlert').removeClass('alert-success alert-danger').addClass(alertClass);
        $('#resultTitle').text(title);

        if (res.data) {
            let stats = `
                <div class="row">
                    <div class="col-md-3">
                        <div class="p-3 bg-white rounded border text-center">
                            <h4 class="fw-bold mb-0 text-primary">${res.data.total_employees || 0}</h4>
                            <small class="text-muted">Total Employees</small>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="p-3 bg-white rounded border text-center">
                            <h4 class="fw-bold mb-0 text-info">${res.data.total_days || 0}</h4>
                            <small class="text-muted">Total Days</small>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="p-3 bg-white rounded border text-center">
                            <h4 class="fw-bold mb-0 text-success">${res.data.success_count || 0}</h4>
                            <small class="text-muted">Successfully Processed</small>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="p-3 bg-white rounded border text-center">
                            <h4 class="fw-bold mb-0 text-danger">${res.data.failed_count || 0}</h4>
                            <small class="text-muted">Failures</small>
                        </div>
                    </div>
                </div>
            `;
            $('#resultStats').html(stats);

            // Show errors if any
            if (res.data.errors && res.data.errors.length > 0) {
                let errorHtml = '';
                res.data.errors.forEach(function(err) {
                    errorHtml += `
                        <tr>
                            <td>${err.employee}</td>
                            <td>${err.date}</td>
                            <td class="text-danger">${err.message}</td>
                        </tr>
                    `;
                });
                $('#errorList').html(errorHtml);
                $('#resultErrors').show();
            } else {
                $('#resultErrors').hide();
            }
        } else {
            $('#resultStats').html('<p class="mb-0">' + (res.message || '') + '</p>');
            $('#resultErrors').hide();
        }

        $('#resultSection').fadeIn();
        
        if (res.status) {
            Swal.fire('Success', 'Attendance marking process completed.', 'success');
        }
    }
});
</script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /home/codeproh/demo.laraoffice.com/app/Modules/HR/Attendance/Providers/../Views/process/mark.blade.php ENDPATH**/ ?>