<?php
/**
 * Enterprise HRM ERP System - Attendance Logs (Non-Deletable)
 * Complete attendance history with role-based access
 * 
 * Features:
 * - Complete attendance logs (non-deletable)
 * - Role-based filtering
 * - Date range filtering
 * - Export functionality
 */

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

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

$pageTitle = 'Attendance Logs';
$currentModule = 'attendance';

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

// Get filter parameters
$filterDateFrom = isset($_GET['date_from']) ? sanitize($_GET['date_from']) : date('Y-m-01');
$filterDateTo = isset($_GET['date_to']) ? sanitize($_GET['date_to']) : date('Y-m-d');
$filterEmployeeId = isset($_GET['employee_id']) ? (int)$_GET['employee_id'] : 0;

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

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 attendance logs
    $where = [
        "a.site_id = ?",
        "a.attendance_date >= ?",
        "a.attendance_date <= ?",
        $employeeFilterSQL
    ];
    $params = [$siteId, $filterDateFrom, $filterDateTo];
    
    // Employee filter
    if ($filterEmployeeId > 0 && canViewEmployeeAttendance($filterEmployeeId)) {
        $where[] = "a.employee_id = ?";
        $params[] = $filterEmployeeId;
    }
    
    $whereClause = implode(' AND ', $where);
    
    $sql = "
        SELECT 
            a.*,
            e.employee_id,
            e.employee_code,
            e.first_name,
            e.middle_name,
            e.last_name,
            d.department_name,
            des.designation_name,
            u1.username as created_by_name,
            u2.username as updated_by_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
        LEFT JOIN users u1 ON a.created_by = u1.user_id
        LEFT JOIN users u2 ON a.updated_by = u2.user_id
        WHERE {$whereClause}
        ORDER BY a.attendance_date DESC, a.check_in_time DESC, e.employee_code
    ";
    
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    $logs = $stmt->fetchAll();
    
} catch (Exception $e) {
    error_log("Error loading attendance logs: " . $e->getMessage());
    $logs = [];
    $employees = [];
}

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

<style>
.logs-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);
}

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

.logs-table {
    width: 100%;
    border-collapse: separate;
    border-spacing: 0;
    font-size: 13px;
}

.logs-table thead {
    background: linear-gradient(135deg, #6366f1 0%, #4f46e5 100%);
    color: white;
    position: sticky;
    top: 0;
    z-index: 10;
}

.logs-table th {
    padding: 12px;
    text-align: left;
    font-weight: 600;
    font-size: 12px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    white-space: nowrap;
}

.logs-table td {
    padding: 12px;
    border-bottom: 1px solid #f1f5f9;
    vertical-align: middle;
}

.logs-table tbody tr:hover {
    background-color: #f8fafc;
}

.log-badge {
    display: inline-block;
    padding: 4px 8px;
    border-radius: 6px;
    font-size: 11px;
    font-weight: 600;
    text-transform: uppercase;
}

.log-present {
    background: #d1fae5;
    color: #065f46;
}

.log-absent {
    background: #fee2e2;
    color: #991b1b;
}

.log-late {
    background: #fed7aa;
    color: #9a3412;
}

.log-half-day {
    background: #fef3c7;
    color: #92400e;
}
</style>

<div class="logs-page">
    <div class="card">
        <div class="card-header">
            <h2 class="card-title">📋 Attendance Logs (Complete History)</h2>
            <div style="display: flex; gap: 10px;">
                <?php if (hasPermission('ATTENDANCE_EXPORT')): ?>
                <a href="<?php echo BASE_URL; ?>/modules/attendance/export_logs.php?date_from=<?php echo $filterDateFrom; ?>&date_to=<?php echo $filterDateTo; ?>&employee_id=<?php echo $filterEmployeeId; ?>" 
                   class="btn btn-secondary">📥 Export</a>
                <?php endif; ?>
                <a href="<?php echo BASE_URL; ?>/modules/attendance/index.php" class="btn btn-secondary">All Features</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">Date From</label>
                        <input type="date" name="date_from" class="form-control" value="<?php echo htmlspecialchars($filterDateFrom); ?>" required>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Date To</label>
                        <input type="date" name="date_to" class="form-control" value="<?php echo htmlspecialchars($filterDateTo); ?>" required>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Employee</label>
                        <select name="employee_id" class="form-control">
                            <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 class="form-group">
                        <button type="submit" class="btn btn-primary" style="width: 100%;">🔍 Filter</button>
                    </div>
                </div>
            </form>
        </div>
        
        <!-- Logs Table -->
        <div class="logs-table-card">
            <div style="padding: 20px; background: #eef2ff; border-bottom: 2px solid #6366f1;">
                <h3 style="margin: 0; color: #4338ca; font-size: 18px;">
                    Complete Attendance History
                    <span style="color: #6366f1; font-weight: 700;">(<?php echo count($logs); ?> records)</span>
                </h3>
                <p style="margin: 8px 0 0 0; color: #64748b; font-size: 13px;">
                    All attendance records are logged and cannot be deleted (audit trail)
                </p>
            </div>
            
            <?php if (!empty($logs)): ?>
            <div style="overflow-x: auto; max-height: 600px; overflow-y: auto;">
                <table class="logs-table">
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Employee</th>
                            <th>Department</th>
                            <th>Check In</th>
                            <th>Check Out</th>
                            <th>Hours</th>
                            <th>Status</th>
                            <th>Created</th>
                            <th>Updated</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($logs as $log): 
                            $empName = trim($log['first_name'] . ' ' . ($log['middle_name'] ?? '') . ' ' . $log['last_name']);
                            $checkIn = $log['check_in_time'] ? date('H:i:s', strtotime($log['check_in_time'])) : '-';
                            $checkOut = $log['check_out_time'] ? date('H:i:s', strtotime($log['check_out_time'])) : '-';
                            $status = strtolower($log['attendance_status'] ?? 'absent');
                        ?>
                        <tr>
                            <td><?php echo date('d M Y', strtotime($log['attendance_date'])); ?></td>
                            <td>
                                <strong><?php echo htmlspecialchars($log['employee_code']); ?></strong><br>
                                <small style="color: #64748b;"><?php echo htmlspecialchars($empName); ?></small>
                            </td>
                            <td><?php echo htmlspecialchars($log['department_name'] ?? '-'); ?></td>
                            <td style="font-family: 'Courier New', monospace; font-weight: 600;"><?php echo $checkIn; ?></td>
                            <td style="font-family: 'Courier New', monospace; font-weight: 600;"><?php echo $checkOut; ?></td>
                            <td><?php echo $log['total_hours'] ? number_format($log['total_hours'], 2) . 'h' : '-'; ?></td>
                            <td>
                                <span class="log-badge log-<?php echo $status; ?>">
                                    <?php echo ucfirst(str_replace('_', ' ', $status)); ?>
                                </span>
                            </td>
                            <td>
                                <small>
                                    <?php echo $log['created_at'] ? date('d M Y H:i', strtotime($log['created_at'])) : '-'; ?><br>
                                    <?php if ($log['created_by_name']): ?>
                                    <span style="color: #64748b;">by <?php echo htmlspecialchars($log['created_by_name']); ?></span>
                                    <?php endif; ?>
                                </small>
                            </td>
                            <td>
                                <small>
                                    <?php echo $log['updated_at'] ? date('d M Y H:i', strtotime($log['updated_at'])) : '-'; ?><br>
                                    <?php if ($log['updated_by_name']): ?>
                                    <span style="color: #64748b;">by <?php echo htmlspecialchars($log['updated_by_name']); ?></span>
                                    <?php endif; ?>
                                </small>
                            </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; margin-bottom: 8px;">
                    No Records Found
                </div>
                <div>No attendance logs found for the selected criteria</div>
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>

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

