<?php
/**
 * Enterprise HRM ERP System - Advanced Attendance List
 * Role-based attendance view with comprehensive filtering
 * 
 * Features:
 * - Role-based data access (Admin/HR/Employee)
 * - Filter by HR, Employee, Department, Date, Month
 * - Daily attendance table with status
 * - Edit, approve, reject, bulk check-in, export
 */

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

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

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

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

// Get filter parameters
$filterEmployeeId = isset($_GET['employee_id']) ? (int)$_GET['employee_id'] : 0;
$filterHRId = isset($_GET['hr_id']) ? (int)$_GET['hr_id'] : 0;
$filterDepartmentId = isset($_GET['department_id']) ? (int)$_GET['department_id'] : 0;
$filterDate = isset($_GET['date']) ? sanitize($_GET['date']) : date('Y-m-d');
$filterMonth = isset($_GET['month']) ? (int)$_GET['month'] : date('m');
$filterYear = isset($_GET['year']) ? (int)$_GET['year'] : date('Y');

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

// Build query with role-based filtering
try {
    $db = getDB();
    
    // Get departments for filter (only accessible ones)
    $deptSQL = "SELECT department_id, department_name FROM departments WHERE site_id = ? ORDER BY department_name";
    $stmt = $db->prepare($deptSQL);
    $stmt->execute([$siteId]);
    $departments = $stmt->fetchAll();
    
    // Get HR Admins for filter (Super Admin only)
    $hrAdmins = [];
    if (isSuperAdmin()) {
        $stmt = $db->prepare("
            SELECT DISTINCT e.employee_id, e.employee_code, 
                   CONCAT(e.first_name, ' ', COALESCE(e.middle_name, ''), ' ', e.last_name) as name
            FROM employees e
            INNER JOIN users u ON e.email = u.email
            INNER JOIN roles r ON u.role_id = r.role_id
            WHERE e.site_id = ? AND e.employment_status = 'active' 
            AND r.role_code = 'hr_admin' AND e.manager_id IS NULL
            ORDER BY e.employee_code
        ");
        $stmt->execute([$siteId]);
        $hrAdmins = $stmt->fetchAll();
    }
    
    // Build attendance query with filters
    $where = ["a.site_id = ?", $employeeFilterSQL];
    $params = [$siteId];
    
    // Date filter
    if (!empty($filterDate)) {
        $where[] = "a.attendance_date = ?";
        $params[] = $filterDate;
    } else {
        // Month/Year filter
        $startDate = date('Y-m-01', strtotime("$filterYear-$filterMonth-01"));
        $endDate = date('Y-m-t', strtotime($startDate));
        $where[] = "a.attendance_date >= ? AND a.attendance_date <= ?";
        $params[] = $startDate;
        $params[] = $endDate;
    }
    
    // Employee filter
    if ($filterEmployeeId > 0 && canViewEmployeeAttendance($filterEmployeeId)) {
        $where[] = "a.employee_id = ?";
        $params[] = $filterEmployeeId;
    }
    
    // HR filter (show employees under this HR)
    if ($filterHRId > 0 && isSuperAdmin()) {
        $where[] = "e.manager_id = ?";
        $params[] = $filterHRId;
    }
    
    // Department filter
    if ($filterDepartmentId > 0) {
        $where[] = "e.department_id = ?";
        $params[] = $filterDepartmentId;
    }
    
    $whereClause = implode(' AND ', $where);
    
    $sql = "
        SELECT 
            a.*,
            e.employee_id,
            e.employee_code,
            e.first_name,
            e.middle_name,
            e.last_name,
            e.manager_id,
            d.department_name,
            des.designation_name,
            CASE 
                WHEN a.check_in_time IS NULL THEN 'Absent'
                WHEN a.check_out_time IS NULL THEN 'Present'
                WHEN a.attendance_status = 'late' THEN 'Late'
                WHEN a.attendance_status = 'half_day' THEN 'Half Day'
                ELSE 'Present'
            END as display_status
        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();
    
    // Get employees for filter dropdown
    $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();
    
} catch (Exception $e) {
    error_log("Error loading attendance list: " . $e->getMessage());
    $attendanceRecords = [];
    $departments = [];
    $hrAdmins = [];
    $employees = [];
}

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

<style>
.attendance-list-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);
    border: 1px solid #e5e7eb;
}

.filter-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 16px;
    align-items: end;
}

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

.table-responsive {
    overflow-x: auto;
    width: 100%;
}

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

.attendance-table thead {
    background: linear-gradient(135deg, #1e3a8a 0%, #1e40af 100%);
    color: white;
    position: sticky;
    top: 0;
    z-index: 10;
}

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

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

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

.status-badge {
    display: inline-block;
    padding: 4px 12px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 600;
    text-transform: uppercase;
}

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

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

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

.status-half-day {
    background: #fef3c7;
    color: #92400e;
}

.action-buttons {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
}

.btn-action {
    padding: 6px 12px;
    border: none;
    border-radius: 6px;
    font-size: 12px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 4px;
}

.btn-edit {
    background: #3b82f6;
    color: white;
}

.btn-edit:hover {
    background: #1e293b;
}

.btn-approve {
    background: #10b981;
    color: white;
}

.btn-reject {
    background: #ef4444;
    color: white;
}

.time-cell {
    font-family: 'Courier New', monospace;
    font-weight: 600;
    color: #475569;
}

@media (max-width: 768px) {
    .filter-grid {
        grid-template-columns: 1fr;
    }
    
    .action-buttons {
        flex-direction: column;
    }
    
    .btn-action {
        width: 100%;
        justify-content: center;
    }
}
</style>

<div class="attendance-list-page">
    <div class="card">
        <div class="card-header">
            <h2 class="card-title">📊 Attendance List</h2>
            <div style="display: flex; gap: 10px; flex-wrap: wrap;">
                <?php if (hasPermission('ATTENDANCE_CREATE')): ?>
                <a href="<?php echo BASE_URL; ?>/modules/attendance/bulk_checkin.php" class="btn btn-primary">
                    ⏰ Bulk Check In
                </a>
                <?php endif; ?>
                <?php if (hasPermission('ATTENDANCE_EXPORT')): ?>
                <a href="<?php echo BASE_URL; ?>/modules/attendance/export.php" 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 class="filter-grid">
                    <?php if (isSuperAdmin() && !empty($hrAdmins)): ?>
                    <div class="form-group">
                        <label class="form-label">HR Admin</label>
                        <select name="hr_id" class="form-control" onchange="this.form.submit()">
                            <option value="0">All HRs</option>
                            <?php foreach ($hrAdmins as $hr): ?>
                            <option value="<?php echo $hr['employee_id']; ?>" <?php echo $filterHRId == $hr['employee_id'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($hr['employee_code'] . ' - ' . $hr['name']); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <?php endif; ?>
                    
                    <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>
                    
                    <?php if (!empty($departments)): ?>
                    <div class="form-group">
                        <label class="form-label">Department</label>
                        <select name="department_id" class="form-control" onchange="this.form.submit()">
                            <option value="0">All Departments</option>
                            <?php foreach ($departments as $dept): ?>
                            <option value="<?php echo $dept['department_id']; ?>" <?php echo $filterDepartmentId == $dept['department_id'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($dept['department_name']); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <?php endif; ?>
                    
                    <div class="form-group">
                        <label class="form-label">Date</label>
                        <input type="date" name="date" class="form-control" value="<?php echo htmlspecialchars($filterDate); ?>" onchange="this.form.submit()">
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Month</label>
                        <select name="month" class="form-control" 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" 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>
            </form>
        </div>
        
        <!-- Attendance Table -->
        <div class="attendance-table-card">
            <div class="table-responsive">
                <table class="attendance-table">
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Employee Code</th>
                            <th>Employee Name</th>
                            <th>Department</th>
                            <th>Designation</th>
                            <th>Check In</th>
                            <th>Check Out</th>
                            <th>Hours</th>
                            <th>Status</th>
                            <?php if (hasPermission('ATTENDANCE_EDIT')): ?>
                            <th>Actions</th>
                            <?php endif; ?>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($attendanceRecords)): ?>
                            <?php foreach ($attendanceRecords 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'])) : '-';
                                $status = strtolower($record['display_status'] ?? $record['attendance_status'] ?? 'absent');
                            ?>
                            <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><?php echo htmlspecialchars($record['designation_name'] ?? '-'); ?></td>
                                <td class="time-cell"><?php echo $checkIn; ?></td>
                                <td class="time-cell"><?php echo $checkOut; ?></td>
                                <td><?php echo $record['total_hours'] ? number_format($record['total_hours'], 2) . ' hrs' : '-'; ?></td>
                                <td>
                                    <span class="status-badge status-<?php echo $status; ?>">
                                        <?php echo ucfirst($status); ?>
                                    </span>
                                </td>
                                <?php if (hasPermission('ATTENDANCE_EDIT') && canViewEmployeeAttendance($record['employee_id'])): ?>
                                <td>
                                    <div class="action-buttons">
                                        <a href="<?php echo BASE_URL; ?>/modules/attendance/form.php?employee_id=<?php echo $record['employee_id']; ?>&date=<?php echo $record['attendance_date']; ?>" 
                                           class="btn-action btn-edit">✏️ Edit</a>
                                    </div>
                                </td>
                                <?php endif; ?>
                            </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="10" style="text-align: center; padding: 40px; color: #64748b;">
                                    No attendance records found.
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

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

