<?php
/**
 * Enterprise HRM ERP System - Lateness & Early Leaving Management
 * Role-based lateness tracking and calculation
 * 
 * Features:
 * - Calculate lateness based on expected check-in time
 * - Calculate early leaving based on expected check-out time
 * - Role-based filtering
 * - Monthly/Yearly reports
 */

require_once __DIR__ . '/../../includes/init.php';
requireLogin();
requirePermission('ATTENDANCE_VIEW');

require_once __DIR__ . '/../../includes/attendance_isolation.php';

$pageTitle = 'Lateness & Early Leaving';
$currentModule = 'attendance';

$siteId = getCurrentSiteId();
if (!$siteId) {
    redirect(BASE_URL . '/dashboard.php', 'Please select a site first.', 'error');
}

// Get filter parameters
$filterMonth = isset($_GET['month']) ? (int)$_GET['month'] : date('m');
$filterYear = isset($_GET['year']) ? (int)$_GET['year'] : date('Y');
$filterEmployeeId = isset($_GET['employee_id']) ? (int)$_GET['employee_id'] : 0;

// Expected times (can be from settings)
$expectedCheckIn = getSetting('EXPECTED_CHECK_IN_TIME', '09:00:00');
$expectedCheckOut = getSetting('EXPECTED_CHECK_OUT_TIME', '18:00:00');

// Get accessible employees
$accessibleEmployeeIds = getAccessibleEmployeeIds();
$employeeFilterSQL = getEmployeeAccessFilterSQL('a.employee_id');

$startDate = date('Y-m-01', strtotime("$filterYear-$filterMonth-01"));
$endDate = date('Y-m-t', strtotime($startDate));

try {
    $db = getDB();
    
    // Get employees for filter
    $employeeSQL = "
        SELECT e.employee_id, e.employee_code, 
               CONCAT(e.first_name, ' ', COALESCE(e.middle_name, ''), ' ', e.last_name) as name
        FROM employees e
        WHERE e.site_id = ? AND e.employment_status = 'active'
        AND " . str_replace('a.employee_id', 'e.employee_id', $employeeFilterSQL) . "
        ORDER BY e.employee_code
    ";
    $stmt = $db->prepare($employeeSQL);
    $stmt->execute([$siteId]);
    $employees = $stmt->fetchAll();
    
    // Build query for lateness records
    $where = [
        "a.site_id = ?",
        "a.attendance_date >= ?",
        "a.attendance_date <= ?",
        "a.check_in_time IS NOT NULL",
        $employeeFilterSQL
    ];
    $params = [$siteId, $startDate, $endDate];
    
    // Employee filter
    if ($filterEmployeeId > 0 && canViewEmployeeAttendance($filterEmployeeId)) {
        $where[] = "a.employee_id = ?";
        $params[] = $filterEmployeeId;
    }
    
    $whereClause = implode(' AND ', $where);
    
    $sql = "
        SELECT 
            a.attendance_id,
            a.attendance_date,
            a.check_in_time,
            a.check_out_time,
            e.employee_id,
            e.employee_code,
            e.first_name,
            e.middle_name,
            e.last_name,
            d.department_name,
            des.designation_name
        FROM attendance a
        INNER JOIN employees e ON a.employee_id = e.employee_id
        LEFT JOIN departments d ON e.department_id = d.department_id
        LEFT JOIN designations des ON e.designation_id = des.designation_id
        WHERE {$whereClause}
        ORDER BY a.attendance_date DESC, e.employee_code
    ";
    
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    $attendanceRecords = $stmt->fetchAll();
    
    // Calculate lateness and early leaving for each record
    foreach ($attendanceRecords as &$record) {
        $checkInTime = $record['check_in_time'];
        $checkOutTime = $record['check_out_time'];
        
        // Calculate lateness
        $record['lateness_minutes'] = calculateLateness($checkInTime, $expectedCheckIn);
        $record['is_late'] = $record['lateness_minutes'] > 0;
        
        // Calculate early leaving
        if ($checkOutTime) {
            $record['early_leaving_minutes'] = calculateEarlyLeaving($checkOutTime, $expectedCheckOut);
            $record['is_early'] = $record['early_leaving_minutes'] > 0;
        } else {
            $record['early_leaving_minutes'] = 0;
            $record['is_early'] = false;
        }
    }
    
    // Filter to show only late or early records
    $lateRecords = array_filter($attendanceRecords, function($r) {
        return $r['is_late'] || $r['is_early'];
    });
    
} catch (Exception $e) {
    error_log("Error loading lateness records: " . $e->getMessage());
    $attendanceRecords = [];
    $lateRecords = [];
    $employees = [];
}

include __DIR__ . '/../../includes/header.php';
?>

<style>
.lateness-page {
    padding: 0;
}

.filter-card {
    background: white;
    border-radius: 12px;
    padding: 24px;
    margin-bottom: 24px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.lateness-table-card {
    background: white;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    overflow: hidden;
}

.lateness-table {
    width: 100%;
    border-collapse: separate;
    border-spacing: 0;
}

.lateness-table thead {
    background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
    color: white;
}

.lateness-table th {
    padding: 16px;
    text-align: left;
    font-weight: 600;
    font-size: 14px;
    white-space: nowrap;
}

.lateness-table td {
    padding: 16px;
    border-bottom: 1px solid #f1f5f9;
}

.lateness-table tbody tr:hover {
    background-color: #fffbeb;
}

.late-badge {
    display: inline-block;
    padding: 4px 12px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 600;
    background: #fee2e2;
    color: #991b1b;
}

.early-badge {
    display: inline-block;
    padding: 4px 12px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 600;
    background: #fef3c7;
    color: #92400e;
}

.time-late {
    color: #dc2626;
    font-weight: 700;
    font-family: 'Courier New', monospace;
}

.time-early {
    color: #d97706;
    font-weight: 700;
    font-family: 'Courier New', monospace;
}
</style>

<div class="lateness-page">
    <div class="card">
        <div class="card-header">
            <h2 class="card-title">⏱️ Lateness & Early Leaving</h2>
            <div style="display: flex; gap: 10px;">
                <a href="<?php echo BASE_URL; ?>/modules/attendance/index.php" class="btn btn-secondary">All Features</a>
                <a href="<?php echo BASE_URL; ?>/modules/attendance/list.php" class="btn btn-secondary">Back to List</a>
            </div>
        </div>
        
        <!-- Filters -->
        <div class="filter-card">
            <form method="GET" class="filter-form">
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; align-items: end;">
                    <div class="form-group">
                        <label class="form-label">Month</label>
                        <select name="month" class="form-control" required onchange="this.form.submit()">
                            <?php 
                            $months = ['January', 'February', 'March', 'April', 'May', 'June', 
                                      'July', 'August', 'September', 'October', 'November', 'December'];
                            for ($m = 1; $m <= 12; $m++): 
                            ?>
                            <option value="<?php echo $m; ?>" <?php echo $filterMonth == $m ? 'selected' : ''; ?>>
                                <?php echo $months[$m - 1]; ?>
                            </option>
                            <?php endfor; ?>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Year</label>
                        <select name="year" class="form-control" required onchange="this.form.submit()">
                            <?php for ($y = date('Y'); $y >= date('Y') - 2; $y--): ?>
                            <option value="<?php echo $y; ?>" <?php echo $filterYear == $y ? 'selected' : ''; ?>>
                                <?php echo $y; ?>
                            </option>
                            <?php endfor; ?>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Employee</label>
                        <select name="employee_id" class="form-control" onchange="this.form.submit()">
                            <option value="0">All Employees</option>
                            <?php foreach ($employees as $emp): ?>
                            <option value="<?php echo $emp['employee_id']; ?>" <?php echo $filterEmployeeId == $emp['employee_id'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($emp['employee_code'] . ' - ' . $emp['name']); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
            </form>
            
            <div style="margin-top: 16px; padding: 12px; background: #fffbeb; border-radius: 8px; border-left: 4px solid #f59e0b;">
                <strong>Expected Times:</strong> Check In: <?php echo date('h:i A', strtotime($expectedCheckIn)); ?> | 
                Check Out: <?php echo date('h:i A', strtotime($expectedCheckOut)); ?>
            </div>
        </div>
        
        <!-- Lateness Table -->
        <div class="lateness-table-card">
            <div style="padding: 20px; background: #fffbeb; border-bottom: 2px solid #f59e0b;">
                <h3 style="margin: 0; color: #92400e; font-size: 18px;">
                    Late Arrivals & Early Departures - <?php echo date('F Y', strtotime($startDate)); ?>
                    <span style="color: #d97706; font-weight: 700;">(<?php echo count($lateRecords); ?> records)</span>
                </h3>
            </div>
            
            <?php if (!empty($lateRecords)): ?>
            <div style="overflow-x: auto;">
                <table class="lateness-table">
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Employee Code</th>
                            <th>Employee Name</th>
                            <th>Department</th>
                            <th>Check In</th>
                            <th>Check Out</th>
                            <th>Lateness</th>
                            <th>Early Leaving</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($lateRecords as $record): 
                            $empName = trim($record['first_name'] . ' ' . ($record['middle_name'] ?? '') . ' ' . $record['last_name']);
                            $checkIn = $record['check_in_time'] ? date('H:i:s', strtotime($record['check_in_time'])) : '-';
                            $checkOut = $record['check_out_time'] ? date('H:i:s', strtotime($record['check_out_time'])) : '-';
                        ?>
                        <tr>
                            <td><?php echo date('d M Y', strtotime($record['attendance_date'])); ?></td>
                            <td><strong><?php echo htmlspecialchars($record['employee_code']); ?></strong></td>
                            <td><?php echo htmlspecialchars($empName); ?></td>
                            <td><?php echo htmlspecialchars($record['department_name'] ?? '-'); ?></td>
                            <td class="time-cell"><?php echo $checkIn; ?></td>
                            <td class="time-cell"><?php echo $checkOut; ?></td>
                            <td>
                                <?php if ($record['is_late']): ?>
                                <span class="late-badge">
                                    <?php echo $record['lateness_minutes']; ?> min late
                                </span>
                                <?php else: ?>
                                <span style="color: #059669;">On Time</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if ($record['is_early']): ?>
                                <span class="early-badge">
                                    <?php echo $record['early_leaving_minutes']; ?> min early
                                </span>
                                <?php else: ?>
                                <span style="color: #059669;"><?php echo $checkOut ? 'Normal' : '-'; ?></span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if ($record['is_late'] && $record['is_early']): ?>
                                <span class="late-badge">Late & Early</span>
                                <?php elseif ($record['is_late']): ?>
                                <span class="late-badge">Late</span>
                                <?php elseif ($record['is_early']): ?>
                                <span class="early-badge">Early</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <?php else: ?>
            <div style="text-align: center; padding: 60px 20px; color: #64748b;">
                <div style="font-size: 64px; margin-bottom: 16px; opacity: 0.5;">✅</div>
                <div style="font-size: 18px; font-weight: 600; color: #059669; margin-bottom: 8px;">
                    Perfect Attendance!
                </div>
                <div>No late arrivals or early departures for <?php echo date('F Y', strtotime($startDate)); ?></div>
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<?php include __DIR__ . '/../../includes/footer.php'; ?>

