<?php
/**
 * Enterprise HRM ERP System - Attendance List
 */

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

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

$siteId = getCurrentSiteId();
$page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$perPage = 20;
$offset = ($page - 1) * $perPage;

// Filters
$search = sanitize($_GET['search'] ?? '');
$dateFrom = $_GET['date_from'] ?? date('Y-m-01');
$dateTo = $_GET['date_to'] ?? date('Y-m-d');

// Build query
$where = ["a.site_id = ?"];
$params = [$siteId];

if (!empty($search)) {
    $where[] = "(e.employee_code LIKE ? OR e.first_name LIKE ? OR e.last_name LIKE ?)";
    $searchParam = "%{$search}%";
    $params = array_merge($params, [$searchParam, $searchParam, $searchParam]);
}

if (!empty($dateFrom)) {
    $where[] = "a.attendance_date >= ?";
    $params[] = $dateFrom;
}

if (!empty($dateTo)) {
    $where[] = "a.attendance_date <= ?";
    $params[] = $dateTo;
}

$whereClause = implode(' AND ', $where);

try {
    $db = getDB();
    
    // Get total count
    $countSql = "
        SELECT COUNT(*) 
        FROM attendance a
        INNER JOIN employees e ON a.employee_id = e.employee_id
        WHERE {$whereClause}
    ";
    $stmt = $db->prepare($countSql);
    $stmt->execute($params);
    $totalRecords = $stmt->fetchColumn();
    $totalPages = ceil($totalRecords / $perPage);
    
    // Get attendance records
    $sql = "
        SELECT 
            a.*,
            e.employee_code,
            CONCAT(e.first_name, ' ', COALESCE(e.middle_name, ''), ' ', e.last_name) as employee_name
        FROM attendance a
        INNER JOIN employees e ON a.employee_id = e.employee_id
        WHERE {$whereClause}
        ORDER BY a.attendance_date DESC, e.employee_code ASC
        LIMIT ? OFFSET ?
    ";
    $params[] = $perPage;
    $params[] = $offset;
    
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    $attendance = $stmt->fetchAll();
    
} catch (Exception $e) {
    error_log("Attendance list error: " . $e->getMessage());
    $attendance = [];
    $totalRecords = 0;
    $totalPages = 0;
}

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

<div class="table-container">
    <div class="table-header">
        <h2 class="table-title">Attendance Records</h2>
        <div class="table-actions">
            <a href="<?php echo BASE_URL; ?>/modules/attendance/create.php" class="btn btn-primary">Mark Attendance</a>
        </div>
    </div>
    
    <div class="table-filters">
        <div class="filter-group">
            <label>Search Employee</label>
            <input type="text" name="search" class="form-control" placeholder="Employee Code or Name..." 
                   value="<?php echo htmlspecialchars($search); ?>" 
                   onkeypress="if(event.key==='Enter') filterTable()">
        </div>
        <div class="filter-group">
            <label>From Date</label>
            <input type="date" name="date_from" class="form-control" 
                   value="<?php echo htmlspecialchars($dateFrom); ?>" 
                   onchange="filterTable()">
        </div>
        <div class="filter-group">
            <label>To Date</label>
            <input type="date" name="date_to" class="form-control" 
                   value="<?php echo htmlspecialchars($dateTo); ?>" 
                   onchange="filterTable()">
        </div>
        <div class="filter-group">
            <button type="button" class="btn btn-secondary" onclick="resetFilters()">Reset</button>
        </div>
    </div>
    
    <?php if (count($attendance) > 0): ?>
    <table class="data-table">
        <thead>
            <tr>
                <th class="sortable">Date</th>
                <th class="sortable">Employee Code</th>
                <th class="sortable">Employee Name</th>
                <th class="sortable">Check In</th>
                <th class="sortable">Check Out</th>
                <th class="sortable">Total Hours</th>
                <th class="sortable">Overtime</th>
                <th class="sortable">Status</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($attendance as $record): ?>
            <tr>
                <td><?php echo formatDate($record['attendance_date']); ?></td>
                <td><?php echo htmlspecialchars($record['employee_code']); ?></td>
                <td><?php echo htmlspecialchars($record['employee_name']); ?></td>
                <td><?php echo formatDateTime($record['check_in_time']); ?></td>
                <td><?php echo formatDateTime($record['check_out_time']); ?></td>
                <td><?php echo number_format($record['total_hours'], 2); ?> hrs</td>
                <td><?php echo number_format($record['overtime_hours'], 2); ?> hrs</td>
                <td>
                    <span class="status-badge status-<?php echo htmlspecialchars($record['attendance_status']); ?>">
                        <?php echo ucfirst(str_replace('_', ' ', $record['attendance_status'])); ?>
                    </span>
                </td>
                <td class="table-actions-cell">
                    <a href="<?php echo BASE_URL; ?>/modules/attendance/edit.php?id=<?php echo $record['attendance_id']; ?>" 
                       class="btn btn-sm btn-primary">Edit</a>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    
    <div class="table-footer">
        <div class="table-info">
            Showing <?php echo $offset + 1; ?> to <?php echo min($offset + $perPage, $totalRecords); ?> of <?php echo number_format($totalRecords); ?> records
        </div>
        <div class="pagination">
            <?php if ($page > 1): ?>
            <a href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>&date_from=<?php echo urlencode($dateFrom); ?>&date_to=<?php echo urlencode($dateTo); ?>" 
               class="btn btn-sm">Previous</a>
            <?php endif; ?>
            <span class="pagination-info">Page <?php echo $page; ?> of <?php echo $totalPages; ?></span>
            <?php if ($page < $totalPages): ?>
            <a href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>&date_from=<?php echo urlencode($dateFrom); ?>&date_to=<?php echo urlencode($dateTo); ?>" 
               class="btn btn-sm">Next</a>
            <?php endif; ?>
        </div>
    </div>
    <?php else: ?>
    <div class="table-empty">
        <div class="table-empty-icon">⏰</div>
        <div class="table-empty-message">No attendance records found</div>
        <div class="table-empty-submessage">
            <a href="<?php echo BASE_URL; ?>/modules/attendance/create.php" class="btn btn-primary">Mark First Attendance</a>
        </div>
    </div>
    <?php endif; ?>
</div>

<style>
.status-badge {
    display: inline-block;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 11px;
    font-weight: 500;
    text-transform: uppercase;
}

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

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

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

.status-on_leave {
    background-color: #e0e7ff;
    color: #3730a3;
}

.status-half_day {
    background-color: #fce7f3;
    color: #831843;
}
</style>

<script>
function filterTable() {
    const search = document.querySelector('[name="search"]').value;
    const dateFrom = document.querySelector('[name="date_from"]').value;
    const dateTo = document.querySelector('[name="date_to"]').value;
    
    const params = new URLSearchParams();
    if (search) params.append('search', search);
    if (dateFrom) params.append('date_from', dateFrom);
    if (dateTo) params.append('date_to', dateTo);
    
    window.location.href = '?' + params.toString();
}

function resetFilters() {
    window.location.href = '<?php echo BASE_URL; ?>/modules/attendance/list.php';
}
</script>

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

