<?php
/**
 * Enterprise HRM ERP System - Missing Attendance Management
 * Role-based missing attendance view and management
 * 
 * Features:
 * - Show employees with missing attendance for selected date
 * - Role-based filtering (HR sees only their team)
 * - Bulk mark attendance
 * - Direct link to mark attendance
 */

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

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

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

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

// Get filter parameters
$filterDate = isset($_GET['date']) ? sanitize($_GET['date']) : date('Y-m-d');
$filterDepartmentId = isset($_GET['department_id']) ? (int)$_GET['department_id'] : 0;

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

if (empty($accessibleEmployeeIds)) {
    $missingEmployees = [];
} else {
    try {
        $db = getDB();
        
        // Get departments for filter
        $stmt = $db->prepare("SELECT department_id, department_name FROM departments WHERE site_id = ? ORDER BY department_name");
        $stmt->execute([$siteId]);
        $departments = $stmt->fetchAll();
        
        // Build query to find employees without attendance for the date
        $where = [
            "e.site_id = ?",
            "e.employment_status = 'active'",
            $employeeFilterSQL,
            "NOT EXISTS (
                SELECT 1 FROM attendance a 
                WHERE a.employee_id = e.employee_id 
                AND a.attendance_date = ? 
                AND a.site_id = ?
                AND a.check_in_time IS NOT NULL
            )"
        ];
        $params = [$siteId, $filterDate, $siteId];
        
        // Department filter
        if ($filterDepartmentId > 0) {
            $where[] = "e.department_id = ?";
            $params[] = $filterDepartmentId;
        }
        
        $whereClause = implode(' AND ', $where);
        
        $sql = "
            SELECT 
                e.employee_id,
                e.employee_code,
                e.first_name,
                e.middle_name,
                e.last_name,
                d.department_name,
                des.designation_name
            FROM employees e
            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 e.employee_code
        ";
        
        $stmt = $db->prepare($sql);
        $stmt->execute($params);
        $missingEmployees = $stmt->fetchAll();
        
    } catch (Exception $e) {
        error_log("Error loading missing attendance: " . $e->getMessage());
        $missingEmployees = [];
        $departments = [];
    }
}

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

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

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

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

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

.missing-table thead {
    background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
    color: white;
}

.missing-table th {
    padding: 16px;
    text-align: left;
    font-weight: 600;
    font-size: 14px;
}

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

.missing-table tbody tr:hover {
    background-color: #fef2f2;
}

.btn-mark-attendance {
    padding: 8px 16px;
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    color: white;
    border: none;
    border-radius: 6px;
    font-size: 13px;
    font-weight: 500;
    cursor: pointer;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    transition: all 0.2s;
}

.btn-mark-attendance:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
}

.empty-state {
    text-align: center;
    padding: 60px 20px;
    color: #64748b;
}

.empty-state-icon {
    font-size: 64px;
    margin-bottom: 16px;
    opacity: 0.5;
}
</style>

<div class="missing-attendance-page">
    <div class="card">
        <div class="card-header">
            <h2 class="card-title">⚠️ Missing Attendance</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-section">
            <form method="GET" class="filter-form">
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 16px; align-items: end;">
                    <div class="form-group">
                        <label class="form-label">Date</label>
                        <input type="date" name="date" class="form-control" value="<?php echo htmlspecialchars($filterDate); ?>" required onchange="this.form.submit()">
                    </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>
            </form>
        </div>
        
        <!-- Missing Employees List -->
        <div class="missing-list-card">
            <div style="padding: 20px; background: #fef2f2; border-bottom: 2px solid #ef4444;">
                <h3 style="margin: 0; color: #991b1b; font-size: 18px;">
                    Employees without attendance for <?php echo date('d M Y', strtotime($filterDate)); ?>
                    <span style="color: #ef4444; font-weight: 700;">(<?php echo count($missingEmployees); ?>)</span>
                </h3>
            </div>
            
            <?php if (!empty($missingEmployees)): ?>
            <table class="missing-table">
                <thead>
                    <tr>
                        <th>SL No.</th>
                        <th>Employee Code</th>
                        <th>Employee Name</th>
                        <th>Department</th>
                        <th>Designation</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($missingEmployees as $index => $emp): 
                        $empName = trim($emp['first_name'] . ' ' . ($emp['middle_name'] ?? '') . ' ' . $emp['last_name']);
                    ?>
                    <tr>
                        <td><?php echo $index + 1; ?></td>
                        <td><strong><?php echo htmlspecialchars($emp['employee_code']); ?></strong></td>
                        <td><?php echo htmlspecialchars($empName); ?></td>
                        <td><?php echo htmlspecialchars($emp['department_name'] ?? '-'); ?></td>
                        <td><?php echo htmlspecialchars($emp['designation_name'] ?? '-'); ?></td>
                        <td>
                            <?php if (canViewEmployeeAttendance($emp['employee_id']) && hasPermission('ATTENDANCE_CREATE')): ?>
                            <a href="<?php echo BASE_URL; ?>/modules/attendance/form.php?employee_id=<?php echo $emp['employee_id']; ?>&date=<?php echo $filterDate; ?>&mode=check_in" 
                               class="btn-mark-attendance">
                                ✅ Mark Attendance
                            </a>
                            <?php else: ?>
                            <span style="color: #94a3b8;">No permission</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
            <?php else: ?>
            <div class="empty-state">
                <div class="empty-state-icon">✅</div>
                <div style="font-size: 18px; font-weight: 600; color: #059669; margin-bottom: 8px;">
                    All Good!
                </div>
                <div>No missing attendance for <?php echo date('d M Y', strtotime($filterDate)); ?></div>
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>

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

