<?php
// ============= ATTENDANCE SYSTEM =============
// IMPORTANT: Output buffering must be at the VERY beginning
ob_start();

// Set timezone to Sri Lanka
date_default_timezone_set('Asia/Colombo');

// Define base path
$base_dir = dirname(dirname(dirname(__FILE__)));

// Include session file with correct path
require_once $base_dir . '/config/session.php';

// Check login
if (!isLoggedIn()) {
    header("Location: ../../login.php");
    exit();
}

// Check if user is employee (for clock in/out functions)
$user_role = $_SESSION['role'] ?? 'employee';
$is_employee = ($user_role === 'employee');

if ($is_employee) {
    // Ensure employee_id is set in session
    if (!isset($_SESSION['employee_id'])) {
        // Load database configuration
        $db_file = $base_dir . '/config/database.php';
        if (!file_exists($db_file)) {
            header("Location: ../../login.php?error=db_config");
            exit();
        }
        require_once $db_file;
        
        try {
            $stmt = $pdo->prepare("SELECT id FROM employees WHERE user_id = ?");
            $stmt->execute([$_SESSION['user_id']]);
            $employee = $stmt->fetch();
            
            if ($employee) {
                $_SESSION['employee_id'] = $employee['id'];
            } else {
                session_destroy();
                header("Location: ../../login.php");
                exit();
            }
        } catch (Exception $e) {
            session_destroy();
            header("Location: ../../login.php?error=employee_not_found");
            exit();
        }
    }
    $employee_id = $_SESSION['employee_id'];
} else {
    // For admin/manager, we'll load all employee data
    $db_file = $base_dir . '/config/database.php';
    if (!file_exists($db_file)) {
        header("Location: ../../login.php?error=db_config");
        exit();
    }
    require_once $db_file;
}

$today = date('Y-m-d');
$current_time = date('H:i:s');
$ip_address = $_SERVER['REMOTE_ADDR'] ?? 'Unknown';
$user_agent = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown';

// Initialize variables
$message = '';
$error = '';
$success = false;

// ============= PROCESS FORM SUBMISSIONS (EMPLOYEES ONLY) =============
if ($_SERVER['REQUEST_METHOD'] == 'POST' && $is_employee) {
    try {
        if (isset($_POST['action']) && $_POST['action'] == 'clock_in') {
            // Check if work_type is selected
            if (!isset($_POST['work_type']) || !in_array($_POST['work_type'], ['office', 'wfh'])) {
                $_SESSION['attendance_error'] = "Please select work type (WFH or Office)";
                ob_end_clean();
                header("Location: " . $_SERVER['PHP_SELF']);
                exit();
            }
            
            $work_type = $_POST['work_type'];
            
            // Get today's attendance
            $stmt = $pdo->prepare("SELECT * FROM attendance WHERE employee_id = ? AND attendance_date = ?");
            $stmt->execute([$employee_id, $today]);
            $attendance = $stmt->fetch();
            
            if (!$attendance) {
                // Calculate late minutes (office start: 9:00 AM)
                $late_minutes = 0;
                $clock_in_time = new DateTime($current_time);
                $office_start = new DateTime('09:00:00');
                
                if ($clock_in_time > $office_start) {
                    $interval = $office_start->diff($clock_in_time);
                    $late_minutes = ($interval->h * 60) + $interval->i;
                }
                
                // Set status based on work type
                $status = ($work_type == 'wfh') ? 'wfh' : 'present';
                
                $stmt = $pdo->prepare("INSERT INTO attendance 
                                      (employee_id, attendance_date, status, work_type,
                                       clock_in, clock_in_ip, late_minutes, 
                                       check_in_ip, notes, updated_at) 
                                      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");
                $success = $stmt->execute([
                    $employee_id, 
                    $today, 
                    $status,
                    $work_type,
                    $current_time, 
                    $ip_address,
                    $late_minutes,
                    $ip_address,
                    "Clocked in via web - $user_agent | Work Type: " . strtoupper($work_type)
                ]);
                
                if ($success) {
                    $message = "✅ Clocked in successfully at " . date('h:i A', strtotime($current_time));
                    $message .= " (Work Type: " . strtoupper($work_type) . ")";
                    
                    if ($late_minutes > 0 && $work_type == 'office') {
                        $hours = floor($late_minutes / 60);
                        $minutes = $late_minutes % 60;
                        $late_str = "";
                        if ($hours > 0) $late_str .= "$hours hour" . ($hours > 1 ? 's' : '');
                        if ($minutes > 0) {
                            if ($hours > 0) $late_str .= " ";
                            $late_str .= "$minutes minute" . ($minutes > 1 ? 's' : '');
                        }
                        $message .= " (You are $late_str late)";
                    }
                } else {
                    $error = "❌ Failed to clock in. Please try again.";
                }
            } else {
                $error = "⚠️ Already clocked in today!";
            }
        } elseif (isset($_POST['action']) && $is_employee) {
            $action = $_POST['action'];
            
            // Get today's attendance
            $stmt = $pdo->prepare("SELECT * FROM attendance WHERE employee_id = ? AND attendance_date = ?");
            $stmt->execute([$employee_id, $today]);
            $attendance = $stmt->fetch();
            
            switch ($action) {
                case 'lunch_start':
                    if ($attendance && !empty($attendance['clock_in']) && empty($attendance['clock_out']) && empty($attendance['lunch_start'])) {
                        $stmt = $pdo->prepare("UPDATE attendance SET lunch_start = ?, updated_at = NOW() WHERE id = ?");
                        $success = $stmt->execute([$current_time, $attendance['id']]);
                        
                        if ($success) {
                            $message = "🍽️ Lunch started at " . date('h:i A', strtotime($current_time));
                        } else {
                            $error = "❌ Failed to start lunch. Please try again.";
                        }
                    } else {
                        $error = "Cannot start lunch. Either you haven't clocked in, already clocked out, or lunch already started.";
                    }
                    break;
                    
                case 'lunch_end':
                    if ($attendance && !empty($attendance['lunch_start']) && empty($attendance['lunch_end']) && empty($attendance['clock_out'])) {
                        $stmt = $pdo->prepare("UPDATE attendance SET lunch_end = ?, updated_at = NOW() WHERE id = ?");
                        $success = $stmt->execute([$current_time, $attendance['id']]);
                        
                        if ($success) {
                            $message = "✅ Lunch ended at " . date('h:i A', strtotime($current_time));
                        } else {
                            $error = "❌ Failed to end lunch. Please try again.";
                        }
                    } else {
                        $error = "Cannot end lunch. Either lunch hasn't started, already ended, or you've already clocked out.";
                    }
                    break;
                    
                case 'clock_out':
                    if ($attendance && !empty($attendance['clock_in']) && empty($attendance['clock_out'])) {
                        // Calculate working hours
                        $clock_in = new DateTime($attendance['clock_in']);
                        $clock_out = new DateTime($current_time);
                        
                        $total_seconds = $clock_out->getTimestamp() - $clock_in->getTimestamp();
                        $total_hours = round($total_seconds / 3600, 2);
                        
                        // Deduct lunch break if exists
                        if (!empty($attendance['lunch_start']) && !empty($attendance['lunch_end'])) {
                            $lunch_start = new DateTime($attendance['lunch_start']);
                            $lunch_end = new DateTime($attendance['lunch_end']);
                            $lunch_seconds = $lunch_end->getTimestamp() - $lunch_start->getTimestamp();
                            $total_hours -= round($lunch_seconds / 3600, 2);
                        }
                        
                        // Calculate early leave (office end: 5:00 PM)
                        $early_leave_minutes = 0;
                        $office_end = new DateTime('17:00:00');
                        if ($clock_out < $office_end) {
                            $interval = $clock_out->diff($office_end);
                            $early_leave_minutes = ($interval->h * 60) + $interval->i;
                        }
                        
                        // Update attendance
                        $stmt = $pdo->prepare("UPDATE attendance 
                                              SET clock_out = ?, 
                                                  clock_out_ip = ?,
                                                  check_out_ip = ?,
                                                  total_hours = ?,
                                                  early_leave_minutes = ?,
                                                  updated_at = NOW(),
                                                  notes = CONCAT(COALESCE(notes, ''), '\nClocked out at $current_time')
                                              WHERE id = ?");
                        $success = $stmt->execute([
                            $current_time,
                            $ip_address,
                            $ip_address,
                            max(0, $total_hours),
                            $early_leave_minutes,
                            $attendance['id']
                        ]);
                        
                        if ($success) {
                            $message = "👋 Clocked out successfully at " . date('h:i A', strtotime($current_time));
                            if ($early_leave_minutes > 0 && $attendance['work_type'] == 'office') {
                                $hours = floor($early_leave_minutes / 60);
                                $minutes = $early_leave_minutes % 60;
                                $early_str = "";
                                if ($hours > 0) $early_str .= "$hours hour" . ($hours > 1 ? 's' : '');
                                if ($minutes > 0) {
                                    if ($hours > 0) $early_str .= " ";
                                    $early_str .= "$minutes minute" . ($minutes > 1 ? 's' : '');
                                }
                                $message .= " (You left $early_str early)";
                            }
                        } else {
                            $error = "❌ Failed to clock out. Please try again.";
                        }
                    } else {
                        $error = "Cannot clock out. Either you haven't clocked in or already clocked out.";
                    }
                    break;
                    
                default:
                    $error = "Invalid action";
            }
        }
        
        // Store messages in session for display after redirect
        if (!empty($message)) {
            $_SESSION['attendance_success'] = $message;
        }
        if (!empty($error)) {
            $_SESSION['attendance_error'] = $error;
        }
        
       
        
    } catch (Exception $e) {
        $_SESSION['attendance_error'] = "❌ Database Error: " . $e->getMessage();
        ob_end_clean();
        header("Location: " . $_SERVER['PHP_SELF']);
        exit();
    }
}

// ============= LOAD DATA FOR DISPLAY =============

// Check for session messages
if (isset($_SESSION['attendance_success'])) {
    $message = $_SESSION['attendance_success'];
    $success = true;
    unset($_SESSION['attendance_success']);
}

if (isset($_SESSION['attendance_error'])) {
    $error = $_SESSION['attendance_error'];
    unset($_SESSION['attendance_error']);
}

// Get user details
try {
    if ($is_employee) {
        $stmt = $pdo->prepare("SELECT e.*, d.department_name, u.username 
                               FROM employees e 
                               LEFT JOIN departments d ON e.department_id = d.id 
                               LEFT JOIN users u ON e.user_id = u.id
                               WHERE e.id = ?");
        $stmt->execute([$employee_id]);
        $user_data = $stmt->fetch();
        
        if (!$user_data) {
            throw new Exception("Employee record not found!");
        }
    } else {
        // For admin/manager, get basic user info
        $stmt = $pdo->prepare("SELECT username, email FROM users WHERE id = ?");
        $stmt->execute([$_SESSION['user_id']]);
        $user_data = $stmt->fetch();
        $user_data['full_name'] = $_SESSION['full_name'] ?? $_SESSION['username'] ?? 'User';
        $user_data['department_name'] = ucfirst($user_role);
    }
} catch (Exception $e) {
    $error = "Error loading user data: " . $e->getMessage();
    $user_data = ['full_name' => 'User', 'department_name' => ucfirst($user_role)];
}

// ============= LOAD ATTENDANCE DATA =============
if ($is_employee) {
    // Get today's attendance for employee
    try {
        $stmt = $pdo->prepare("SELECT * FROM attendance 
                               WHERE employee_id = ? AND attendance_date = ?");
        $stmt->execute([$employee_id, $today]);
        $attendance = $stmt->fetch();
    } catch (Exception $e) {
        $error .= " Error loading attendance data: " . $e->getMessage();
    }

    // Get attendance statistics for current month
    try {
        $month_start = date('Y-m-01');
        $month_end = date('Y-m-t');
        
        $stmt = $pdo->prepare("SELECT 
            COUNT(*) as total_days,
            SUM(CASE WHEN status = 'present' THEN 1 ELSE 0 END) as present_days,
            SUM(CASE WHEN status = 'absent' THEN 1 ELSE 0 END) as absent_days,
            SUM(CASE WHEN status = 'half-day' THEN 1 ELSE 0 END) as half_days,
            SUM(CASE WHEN status = 'wfh' THEN 1 ELSE 0 END) as wfh_days,
            SUM(CASE WHEN status = 'leave' THEN 1 ELSE 0 END) as leave_days,
            SUM(CASE WHEN work_type = 'office' THEN 1 ELSE 0 END) as office_days,
            SUM(CASE WHEN work_type = 'wfh' THEN 1 ELSE 0 END) as wfh_type_days,
            COALESCE(AVG(total_hours), 0) as avg_hours,
            SUM(late_minutes) as total_late_minutes,
            SUM(early_leave_minutes) as total_early_minutes
            FROM attendance 
            WHERE employee_id = ? 
            AND attendance_date BETWEEN ? AND ?");
        $stmt->execute([$employee_id, $month_start, $month_end]);
        $stats = $stmt->fetch() ?: [];
    } catch (Exception $e) {
        $stats = [];
        $error .= " Statistics error: " . $e->getMessage();
    }

    // Get recent attendance records
    try {
        $stmt = $pdo->prepare("SELECT * FROM attendance 
                               WHERE employee_id = ? 
                               ORDER BY attendance_date DESC 
                               LIMIT 15");
        $stmt->execute([$employee_id]);
        $recent_attendance = $stmt->fetchAll() ?: [];
    } catch (Exception $e) {
        $recent_attendance = [];
        $error .= " Recent records error: " . $e->getMessage();
    }
} else {
    // Admin/Manager: Get all employees attendance for today
    try {
        $stmt = $pdo->prepare("SELECT a.*, e.full_name, d.department_name 
                               FROM attendance a
                               JOIN employees e ON a.employee_id = e.id
                               LEFT JOIN departments d ON e.department_id = d.id
                               WHERE a.attendance_date = ?
                               ORDER BY e.full_name");
        $stmt->execute([$today]);
        $todays_attendance = $stmt->fetchAll() ?: [];
    } catch (Exception $e) {
        $todays_attendance = [];
        $error .= " Today's attendance error: " . $e->getMessage();
    }

    // Get monthly statistics for all employees
    try {
        $month_start = date('Y-m-01');
        $month_end = date('Y-m-t');
        
        $stmt = $pdo->prepare("SELECT 
            e.full_name,
            d.department_name,
            COUNT(*) as total_days,
            SUM(CASE WHEN a.status = 'present' THEN 1 ELSE 0 END) as present_days,
            SUM(CASE WHEN a.status = 'absent' THEN 1 ELSE 0 END) as absent_days,
            SUM(CASE WHEN a.status = 'half-day' THEN 1 ELSE 0 END) as half_days,
            SUM(CASE WHEN a.status = 'wfh' THEN 1 ELSE 0 END) as wfh_days,
            SUM(CASE WHEN a.status = 'leave' THEN 1 ELSE 0 END) as leave_days,
            SUM(CASE WHEN a.work_type = 'office' THEN 1 ELSE 0 END) as office_days,
            SUM(CASE WHEN a.work_type = 'wfh' THEN 1 ELSE 0 END) as wfh_type_days,
            COALESCE(AVG(a.total_hours), 0) as avg_hours,
            SUM(a.late_minutes) as total_late_minutes,
            SUM(a.early_leave_minutes) as total_early_minutes
            FROM attendance a
            JOIN employees e ON a.employee_id = e.id
            LEFT JOIN departments d ON e.department_id = d.id
            WHERE a.attendance_date BETWEEN ? AND ?
            GROUP BY e.id, e.full_name, d.department_name
            ORDER BY e.full_name");
        $stmt->execute([$month_start, $month_end]);
        $monthly_stats = $stmt->fetchAll() ?: [];
    } catch (Exception $e) {
        $monthly_stats = [];
        $error .= " Monthly stats error: " . $e->getMessage();
    }
}

// Now start the HTML output
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $is_employee ? 'Smart Attendance System' : 'Attendance Management'; ?></title>
    
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <style>
        :root {
            --primary: #4361ee;
            --secondary: #3a0ca3;
            --success: #4cc9f0;
            --warning: #f72585;
            --light: #f8f9fa;
            --dark: #212529;
        }
        
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        .main-container {
            background: rgba(255, 255, 255, 0.98);
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            margin-top: 20px;
            margin-bottom: 20px;
            overflow: hidden;
        }
        
        .header-gradient {
            background: linear-gradient(90deg, var(--primary), var(--secondary));
            color: white;
            padding: 25px;
        }
        
        .time-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 20px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
        }
        
        .action-card {
            background: white;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 20px;
            border: none;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            transition: transform 0.3s, box-shadow 0.3s;
        }
        
        .action-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 30px rgba(0,0,0,0.15);
        }
        
        .btn-action {
            padding: 15px 25px;
            font-size: 1.1rem;
            font-weight: 600;
            border-radius: 12px;
            border: none;
            transition: all 0.3s;
            margin: 8px;
            min-width: 180px;
        }
        
        .btn-clock-in {
            background: linear-gradient(135deg, #00b09b, #96c93d);
            color: white;
        }
        
        .btn-clock-out {
            background: linear-gradient(135deg, #ff416c, #ff4b2b);
            color: white;
        }
        
        .btn-lunch {
            background: linear-gradient(135deg, #f7971e, #ffd200);
            color: white;
        }
        
        .btn-action:hover:not(:disabled) {
            transform: scale(1.05);
            box-shadow: 0 10px 20px rgba(0,0,0,0.2);
        }
        
        .btn-action:disabled {
            opacity: 0.5;
            cursor: not-allowed;
            transform: none !important;
            box-shadow: none !important;
        }
        
        .status-badge {
            padding: 8px 20px;
            border-radius: 50px;
            font-weight: 600;
        }
        
        .badge-present { background: #28a745; color: white; }
        .badge-absent { background: #dc3545; color: white; }
        .badge-late { background: #fd7e14; color: white; }
        .badge-wfh { background: #17a2b8; color: white; }
        .badge-leave { background: #6c757d; color: white; }
        .badge-half-day { background: #ffc107; color: #212529; }
        .badge-office { background: #4361ee; color: white; }
        
        .work-type-badge {
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 600;
        }
        
        .badge-work-wfh { background: #9d4edd; color: white; }
        .badge-work-office { background: #4361ee; color: white; }
        
        .time-log-display {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 15px;
            margin: 10px 0;
        }
        
        .time-item {
            display: flex;
            justify-content: space-between;
            padding: 10px;
            border-bottom: 1px solid #dee2e6;
        }
        
        .time-item:last-child {
            border-bottom: none;
        }
        
        .stat-card {
            text-align: center;
            padding: 15px;
            border-radius: 10px;
            background: white;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
        }
        
        .stat-number {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 10px;
        }
        
        .real-time-clock {
            font-size: 3rem;
            font-weight: 800;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
            font-family: 'Courier New', monospace;
        }
        
        @media (max-width: 768px) {
            .real-time-clock {
                font-size: 2rem;
            }
            .btn-action {
                min-width: 100%;
                margin: 5px 0;
            }
        }
        
        .attendance-table {
            width: 130%;
            background: white;
        }
        
        .attendance-table th {
            background: var(--primary);
            color: white;
        }
        
        .office-hours-indicator {
            font-size: 0.9rem;
            padding: 5px 15px;
            border-radius: 20px;
            margin-top: 10px;
            display: inline-block;
        }
        
        .office-open {
            background: rgba(40, 167, 69, 0.2);
            color: #28a745;
            border: 1px solid #28a745;
        }
        
        .office-closed {
            background: rgba(220, 53, 69, 0.2);
            color: #dc3545;
            border: 1px solid #dc3545;
        }
        
        .confirmation-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 9999;
        }
        
        .confirmation-box {
            background: white;
            border-radius: 15px;
            padding: 25px;
            max-width: 500px;
            width: 90%;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
        }
        
        .work-type-selection {
            margin: 20px 0;
        }
        
        .work-type-option {
            padding: 15px;
            border: 2px solid #dee2e6;
            border-radius: 10px;
            margin: 10px 0;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .work-type-option:hover {
            border-color: #4361ee;
            background: #f8f9fa;
        }
        
        .work-type-option.selected {
            border-color: #4361ee;
            background: rgba(67, 97, 238, 0.1);
        }
        
        .work-type-icon {
            font-size: 1.5rem;
            margin-right: 10px;
        }
        
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(255,255,255,0.8);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 9999;
        }
        
        .spinner-custom {
            width: 60px;
            height: 60px;
            border: 6px solid #f3f3f3;
            border-top: 6px solid var(--primary);
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .nav-tabs .nav-link {
            border: none;
            color: #6c757d;
            font-weight: 500;
        }
        
        .nav-tabs .nav-link.active {
            color: var(--primary);
            border-bottom: 3px solid var(--primary);
            background: transparent;
        }
        
        .late-indicator {
            font-size: 0.8rem;
            padding: 3px 10px;
            border-radius: 10px;
            background: rgba(253, 126, 20, 0.2);
            color: #fd7e14;
            border: 1px solid #fd7e14;
        }
        
        .early-indicator {
            font-size: 0.8rem;
            padding: 3px 10px;
            border-radius: 10px;
            background: rgba(23, 162, 184, 0.2);
            color: #17a2b8;
            border: 1px solid #17a2b8;
        }
    </style>
</head>
<body>
    <!-- Loading Overlay -->
    <div id="loadingOverlay" class="loading-overlay" style="display: none;">
        <div class="spinner-custom"></div>
        <div class="mt-3" id="loadingText">Processing...</div>
    </div>

    <!-- Work Type Selection Modal -->
    <div id="workTypeModal" class="confirmation-modal" style="display: none;">
        <div class="confirmation-box">
            <h4><i class="bi bi-laptop"></i> Select Work Type</h4>
            <p>Please select where you will be working today:</p>
            
            <div class="work-type-selection">
                <div class="work-type-option" onclick="selectWorkType('office')" id="officeOption">
                    <div class="d-flex align-items-center">
                        <i class="bi bi-building work-type-icon"></i>
                        <div>
                            <h5 class="mb-1">Office (On-site)</h5>
                            <p class="mb-0 text-muted">Working from the office location</p>
                        </div>
                    </div>
                </div>
                
                <div class="work-type-option" onclick="selectWorkType('wfh')" id="wfhOption">
                    <div class="d-flex align-items-center">
                        <i class="bi bi-house work-type-icon"></i>
                        <div>
                            <h5 class="mb-1">Work From Home</h5>
                            <p class="mb-0 text-muted">Working remotely from home</p>
                        </div>
                    </div>
                </div>
            </div>
            
            <input type="hidden" id="selectedWorkType" value="">
            
            <div class="d-flex justify-content-between mt-4">
                <button type="button" class="btn btn-secondary" onclick="cancelWorkType()">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="confirmWorkType()" id="confirmWorkTypeBtn" disabled>Confirm Clock In</button>
            </div>
        </div>
    </div>

    <!-- Confirmation Modal for other actions -->
    <div id="confirmationModal" class="confirmation-modal" style="display: none;">
        <div class="confirmation-box">
            <h4 id="confirmTitle"></h4>
            <p id="confirmMessage"></p>
            <div class="d-flex justify-content-between mt-4">
                <button type="button" class="btn btn-secondary" onclick="cancelAction()">Cancel</button>
                <button type="button" class="btn btn-primary" id="confirmBtn">Confirm</button>
            </div>
        </div>
    </div>

    <div class="container py-4">
        <div class="main-container">
            <!-- Header -->
            <div class="header-gradient">
                <div class="row align-items-center">
                    <div class="col-md-8">
                        <h4><i class="bi bi-clock-history"></i> 
                            <?php echo $is_employee ? 'Smart Attendance System' : 'Attendance Management'; ?>
                        </h4>
                        <p class="mb-0">
                            Welcome, <strong><?php echo htmlspecialchars($user_data['full_name'] ?? 'User'); ?></strong> 
                            
                            | <span class="badge bg-light text-dark"><?php echo ucfirst($user_role); ?></span>
                        </p>
                        
                    </div>
                    <div class="col-md-4 text-end">
                       <a href="dashboard.php" class="btn btn-sm btn-light mt-2">
                            <i class="bi bi-arrow-left"></i> Back to Dashboard
                        </a>
                    </div>
                </div>
            </div>

            <!-- Messages -->
            <?php if ($success && !empty($message)): ?>
            <div class="alert alert-success alert-dismissible fade show m-3" role="alert">
                <i class="bi bi-check-circle"></i> <?php echo htmlspecialchars($message); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
            <?php endif; ?>
            
            <?php if (!empty($error)): ?>
            <div class="alert alert-danger alert-dismissible fade show m-3" role="alert">
                <i class="bi bi-exclamation-triangle"></i> <?php echo htmlspecialchars($error); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
            <?php endif; ?>

            <!-- Real Time Clock -->
            <div class="container mt-4">
                <div class="time-card text-center">
                    <div class="real-time-clock" id="current-time">
                        <?php echo date('H:i:s'); ?>
                    </div>
                    <h5 id="current-date"><?php echo date('l, F j, Y'); ?></h5>
                    <div id="office-hours-indicator" class="office-hours-indicator office-open">
                        <i class="bi bi-building"></i> Office Hours: 9:00 AM - 5:00 PM
                    </div>
                    <?php if ($is_employee && isset($attendance) && $attendance && $attendance['clock_in']): ?>
                    <div class="mt-3">
                        <?php 
                        $status_class = '';
                        switch($attendance['status']) {
                            case 'present': $status_class = 'badge-present'; break;
                            case 'absent': $status_class = 'badge-absent'; break;
                            case 'half-day': $status_class = 'badge-half-day'; break;
                            case 'wfh': $status_class = 'badge-wfh'; break;
                            case 'leave': $status_class = 'badge-leave'; break;
                            default: $status_class = 'badge-light';
                        }
                        ?>
                        <span class="status-badge <?php echo $status_class; ?>" id="attendance-status">
                            <?php echo strtoupper($attendance['status']); ?>
                        </span>
                        
                        <?php if (isset($attendance['work_type'])): ?>
                        <span class="work-type-badge badge-work-<?php echo $attendance['work_type']; ?> ms-2">
                            <i class="bi bi-<?php echo $attendance['work_type'] == 'office' ? 'building' : 'house'; ?>"></i>
                            <?php echo strtoupper($attendance['work_type']); ?>
                        </span>
                        <?php endif; ?>
                        
                        <?php if ($attendance['late_minutes'] > 0 && $attendance['work_type'] == 'office'): 
                            $hours = floor($attendance['late_minutes'] / 60);
                            $minutes = $attendance['late_minutes'] % 60;
                            $late_str = "";
                            if ($hours > 0) $late_str .= "$hours hour" . ($hours > 1 ? 's' : '');
                            if ($minutes > 0) {
                                if ($hours > 0) $late_str .= " ";
                                $late_str .= "$minutes minute" . ($minutes > 1 ? 's' : '');
                            }
                        ?>
                        <span class="late-indicator ms-2">
                            <i class="bi bi-alarm"></i> Late: <?php echo $late_str; ?>
                        </span>
                        <?php endif; ?>
                    </div>
                    <?php elseif ($is_employee): ?>
                    <div class="mt-3">
                        <span class="status-badge badge-absent" id="attendance-status">
                            ABSENT
                        </span>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

            <?php if ($is_employee): ?>
            <!-- EMPLOYEE VIEW -->
            <!-- Action Buttons -->
            <div class="container mt-4">
                <div class="action-card">
                    <h5 class="mb-4"><i class="bi bi-play-circle"></i> Attendance Actions</h5>
                    <form method="POST" action="" id="attendanceForm">
                        <input type="hidden" name="action" id="actionInput">
                        <input type="hidden" name="work_type" id="workTypeInput">
                        
                        <div class="row justify-content-center text-center">
                            <!-- Clock In Button -->
                            <div class="col-md-3 mb-3">
                                <button type="button" class="btn btn-clock-in btn-action w-100"
                                        onclick="showWorkTypeSelection()"
                                        <?php echo (isset($attendance) && $attendance && $attendance['clock_in']) ? 'disabled' : ''; ?>
                                        id="btn-clock-in">
                                    <i class="bi bi-play-fill"></i><br>
                                    <span id="clock-in-text">
                                        <?php echo (isset($attendance) && $attendance && $attendance['clock_in']) ? 'CLOCKED IN' : 'CLOCK IN'; ?>
                                    </span>
                                    <br>
                                    <small id="clock-in-time">
                                        <?php echo (isset($attendance) && $attendance && $attendance['clock_in']) ? date('h:i A', strtotime($attendance['clock_in'])) : '--:--'; ?>
                                    </small>
                                </button>
                            </div>
                            
                            <!-- Lunch Start Button -->
                            <div class="col-md-3 mb-3">
                                <button type="button" class="btn btn-lunch btn-action w-100"
                                        onclick="showConfirmation('lunch_start', 'Are you sure you want to start lunch?')"
                                        <?php echo !isset($attendance) || !$attendance || !$attendance['clock_in'] || $attendance['lunch_start'] || $attendance['clock_out'] ? 'disabled' : ''; ?>
                                        id="btn-lunch-start">
                                    <i class="bi bi-egg-fried"></i><br>
                                    <span id="lunch-start-text">
                                        <?php echo (isset($attendance) && $attendance && $attendance['lunch_start']) ? 'LUNCH STARTED' : 'START LUNCH'; ?>
                                    </span>
                                    <br>
                                    <small id="lunch-start-time">
                                        <?php echo (isset($attendance) && $attendance && $attendance['lunch_start']) ? date('h:i A', strtotime($attendance['lunch_start'])) : '--:--'; ?>
                                    </small>
                                </button>
                            </div>
                            
                            <!-- Lunch End Button -->
                            <div class="col-md-3 mb-3">
                                <button type="button" class="btn btn-lunch btn-action w-100"
                                        onclick="showConfirmation('lunch_end', 'Are you sure you want to end lunch?')"
                                        <?php echo !isset($attendance) || !$attendance || !$attendance['lunch_start'] || $attendance['lunch_end'] || $attendance['clock_out'] ? 'disabled' : ''; ?>
                                        id="btn-lunch-end">
                                    <i class="bi bi-egg"></i><br>
                                    <span id="lunch-end-text">
                                        <?php echo (isset($attendance) && $attendance && $attendance['lunch_end']) ? 'LUNCH ENDED' : 'END LUNCH'; ?>
                                    </span>
                                    <br>
                                    <small id="lunch-end-time">
                                        <?php echo (isset($attendance) && $attendance && $attendance['lunch_end']) ? date('h:i A', strtotime($attendance['lunch_end'])) : '--:--'; ?>
                                    </small>
                                </button>
                            </div>
                            
                            <!-- Clock Out Button -->
                            <div class="col-md-3 mb-3">
                                <button type="button" class="btn btn-clock-out btn-action w-100"
                                        onclick="showConfirmation('clock_out', 'Are you sure you want to clock out?')"
                                        <?php echo !isset($attendance) || !$attendance || !$attendance['clock_in'] || $attendance['clock_out'] ? 'disabled' : ''; ?>
                                        id="btn-clock-out">
                                    <i class="bi bi-stop-fill"></i><br>
                                    <span id="clock-out-text">
                                        <?php echo (isset($attendance) && $attendance && $attendance['clock_out']) ? 'CLOCKED OUT' : 'CLOCK OUT'; ?>
                                    </span>
                                    <br>
                                    <small id="clock-out-time">
                                        <?php echo (isset($attendance) && $attendance && $attendance['clock_out']) ? date('h:i A', strtotime($attendance['clock_out'])) : '--:--'; ?>
                                    </small>
                                </button>
                            </div>
                        </div>
                    </form>
                    
                    <!-- Today's Summary -->
                    <?php if (isset($attendance) && $attendance): ?>
                    <div class="mt-4 p-3" style="background: #e8f4fd; border-radius: 10px;">
                        <h6><i class="bi bi-graph-up"></i> Today's Summary</h6>
                        <div class="row">
                            <div class="col-md-2">
                                <div class="time-item">
                                    <span>Work Type:</span>
                                    <strong>
                                        <span class="badge badge-work-<?php echo $attendance['work_type'] ?? 'office'; ?>">
                                            <?php echo isset($attendance['work_type']) ? strtoupper($attendance['work_type']) : 'OFFICE'; ?>
                                        </span>
                                    </strong>
                                </div>
                            </div>
                            <div class="col-md-2">
                                <div class="time-item">
                                    <span>Clock In:</span>
                                    <strong id="summary-clock-in"><?php echo $attendance['clock_in'] ? date('h:i A', strtotime($attendance['clock_in'])) : '--:--'; ?></strong>
                                </div>
                            </div>
                            <div class="col-md-2">
                                <div class="time-item">
                                    <span>Lunch:</span>
                                    <strong id="summary-lunch">
                                        <?php 
                                        if ($attendance['lunch_start'] && $attendance['lunch_end']) {
                                            echo date('h:i', strtotime($attendance['lunch_start'])) . ' - ' . date('h:i', strtotime($attendance['lunch_end']));
                                        } elseif ($attendance['lunch_start']) {
                                            echo date('h:i A', strtotime($attendance['lunch_start'])) . ' - --:--';
                                        } else {
                                            echo '--:--';
                                        }
                                        ?>
                                    </strong>
                                </div>
                            </div>
                            <div class="col-md-2">
                                <div class="time-item">
                                    <span>Clock Out:</span>
                                    <strong id="summary-clock-out"><?php echo $attendance['clock_out'] ? date('h:i A', strtotime($attendance['clock_out'])) : '--:--'; ?></strong>
                                </div>
                            </div>
                            <div class="col-md-2">
                                <div class="time-item">
                                    <span>Total Hours:</span>
                                    <strong id="summary-total-hours"><?php echo $attendance['total_hours'] > 0 ? number_format($attendance['total_hours'], 1) . ' hrs' : '--:--'; ?></strong>
                                </div>
                            </div>
                            <div class="col-md-2">
                                <div class="time-item">
                                    <span>Status:</span>
                                    <strong>
                                        <span class="badge <?php echo $status_class; ?>">
                                            <?php echo strtoupper($attendance['status']); ?>
                                        </span>
                                    </strong>
                                </div>
                            </div>
                        </div>
                        <?php if ($attendance['clock_out'] && $attendance['work_type'] == 'office'): ?>
                        <div class="row mt-2">
                            <div class="col-md-6">
                                <div class="alert <?php echo $attendance['late_minutes'] > 0 ? 'alert-warning' : 'alert-success'; ?> p-2">
                                    <i class="bi bi-alarm"></i> Late: 
                                    <?php 
                                    if ($attendance['late_minutes'] > 0) {
                                        $hours = floor($attendance['late_minutes'] / 60);
                                        $minutes = $attendance['late_minutes'] % 60;
                                        $late_str = "";
                                        if ($hours > 0) $late_str .= "$hours hour" . ($hours > 1 ? 's' : '');
                                        if ($minutes > 0) {
                                            if ($hours > 0) $late_str .= " ";
                                            $late_str .= "$minutes minute" . ($minutes > 1 ? 's' : '');
                                        }
                                        echo $late_str;
                                    } else {
                                        echo "On time";
                                    }
                                    ?>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="alert <?php echo $attendance['early_leave_minutes'] > 0 ? 'alert-warning' : 'alert-success'; ?> p-2">
                                    <i class="bi bi-hourglass-split"></i> Early Leave: 
                                    <?php 
                                    if ($attendance['early_leave_minutes'] > 0) {
                                        $hours = floor($attendance['early_leave_minutes'] / 60);
                                        $minutes = $attendance['early_leave_minutes'] % 60;
                                        $early_str = "";
                                        if ($hours > 0) $early_str .= "$hours hour" . ($hours > 1 ? 's' : '');
                                        if ($minutes > 0) {
                                            if ($hours > 0) $early_str .= " ";
                                            $early_str .= "$minutes minute" . ($minutes > 1 ? 's' : '');
                                        }
                                        echo $early_str;
                                    } else {
                                        echo "Left on time";
                                    }
                                    ?>
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Employee Statistics -->
            <?php if (isset($stats)): ?>
            <div class="container mt-4">
                <div class="action-card">
                    <h5 class="mb-4"><i class="bi bi-bar-chart"></i> Monthly Statistics (<?php echo date('F Y'); ?>)</h5>
                    <div class="row text-center">
                        <div class="col-md-2 col-6 mb-3">
                            <div class="stat-card">
                                <div class="stat-number text-primary"><?php echo $stats['present_days'] ?? 0; ?></div>
                                <div>Present Days</div>
                            </div>
                        </div>
                        <div class="col-md-2 col-6 mb-3">
                            <div class="stat-card">
                                <div class="stat-number text-warning"><?php echo $stats['absent_days'] ?? 0; ?></div>
                                <div>Absent Days</div>
                            </div>
                        </div>
                        
                        <div class="col-md-2 col-6 mb-3">
                            <div class="stat-card">
                                <div class="stat-number text-secondary"><?php echo round($stats['avg_hours'] ?? 0, 1); ?></div>
                                <div>Avg Hours/Day</div>
                            </div>
                        </div>
                        <div class="col-md-2 col-6 mb-3">
                            <div class="stat-card">
                                <div class="stat-number text-success"><?php echo $stats['office_days'] ?? 0; ?></div>
                                <div>Office Days</div>
                            </div>
                        </div>
                        <div class="col-md-2 col-6 mb-3">
                            <div class="stat-card">
                                <div class="stat-number text-purple"><?php echo $stats['wfh_type_days'] ?? 0; ?></div>
                                <div>WFH Days</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <!-- Recent Attendance -->
<?php if (isset($recent_attendance)): ?>
<div class="container mt-4 mb-4">
    <div class="action-card">
        <h5 class="mb-4"><i class="bi bi-calendar-week"></i> Recent Attendance (Last 15 Days)</h5>
        <div class="table-responsive">
            <table class="table table-hover attendance-table" id="attendanceTable">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Day</th>
                        <th>Clock In</th>
                        <th>Clock Out</th>
                        <th>Work Type</th>
                        <th>Total Hours</th>
                        <th>Remarks</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($recent_attendance)): ?>
                    <tr>
                        <td colspan="7" class="text-center">No attendance records found.</td>
                    </tr>
                    <?php else: ?>
                    <?php foreach ($recent_attendance as $record): ?>
                    <tr>
                        <td><?php echo date('Y-m-d', strtotime($record['attendance_date'])); ?></td>
                        <td><?php echo date('D', strtotime($record['attendance_date'])); ?></td>
                        <td><?php echo $record['clock_in'] ? date('h:i A', strtotime($record['clock_in'])) : '--:--'; ?></td>
                        <td><?php echo $record['clock_out'] ? date('h:i A', strtotime($record['clock_out'])) : '--:--'; ?></td>
                        <td>
                            <?php if (isset($record['work_type'])): ?>
                            <span class="badge badge-work-<?php echo $record['work_type']; ?>">
                                <i class="bi bi-<?php echo $record['work_type'] == 'office' ? 'building' : 'house'; ?>"></i>
                                <?php echo strtoupper($record['work_type']); ?>
                            </span>
                            <?php else: ?>
                            <span class="badge badge-work-office">OFFICE</span>
                            <?php endif; ?>
                        </td>
                        <td><?php echo $record['total_hours'] > 0 ? number_format($record['total_hours'], 1) . ' hrs' : '--'; ?></td>
                        <td>
                            <?php 
                            $remarks = [];
                            if ($record['late_minutes'] > 0 && $record['work_type'] == 'office') {
                                $hours = floor($record['late_minutes'] / 60);
                                $minutes = $record['late_minutes'] % 60;
                                $late_str = "";
                                if ($hours > 0) $late_str .= "$hours hour" . ($hours > 1 ? 's' : '');
                                if ($minutes > 0) {
                                    if ($hours > 0) $late_str .= " ";
                                    $late_str .= "$minutes minute" . ($minutes > 1 ? 's' : '');
                                }
                                $remarks[] = "Late $late_str";
                            }
                            if ($record['early_leave_minutes'] > 0 && $record['work_type'] == 'office') {
                                $hours = floor($record['early_leave_minutes'] / 60);
                                $minutes = $record['early_leave_minutes'] % 60;
                                $early_str = "";
                                if ($hours > 0) $early_str .= "$hours hour" . ($hours > 1 ? 's' : '');
                                if ($minutes > 0) {
                                    if ($hours > 0) $early_str .= " ";
                                    $early_str .= "$minutes minute" . ($minutes > 1 ? 's' : '');
                                }
                                $remarks[] = "Left $early_str early";
                            }
                            echo !empty($remarks) ? implode(', ', $remarks) : '--';
                            ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<?php endif; ?>

            <?php else: ?>
            <!-- ADMIN/MANAGER VIEW -->
            <div class="container mt-4">
                <ul class="nav nav-tabs" id="attendanceTabs" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="nav-link active" id="today-tab" data-bs-toggle="tab" data-bs-target="#today" type="button" role="tab">
                            <i class="bi bi-calendar-day"></i> Today's Attendance
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="monthly-tab" data-bs-toggle="tab" data-bs-target="#monthly" type="button" role="tab">
                            <i class="bi bi-calendar-month"></i> Monthly Report
                        </button>
                    </li>
                </ul>
                
                <div class="tab-content mt-3">
                    <!-- Today's Attendance Tab -->
                    <div class="tab-pane fade show active" id="today" role="tabpanel">
                        <div class="action-card">
                            <h5><i class="bi bi-calendar-day"></i> Today's Attendance (<?php echo date('F j, Y'); ?>)</h5>
                            <p class="text-muted">Attendance records for all employees today.</p>
                            
                            <div class="table-responsive">
                                <table class="table table-hover attendance-table" id="todayTable">
                                    <thead>
                                        <tr>
                                            <th>Employee</th>
                                            <th>Department</th>
                                            <th>Clock In</th>
                                            <th>Clock Out</th>
                                            <th>Work Type</th>
                                            <th>Total Hours</th>
                                            
                                            <th>Remarks</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php if (empty($todays_attendance)): ?>
                                        <tr>
                                            <td colspan="8" class="text-center">No attendance records for today.</td>
                                        </tr>
                                        <?php else: ?>
                                        <?php foreach ($todays_attendance as $record): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($record['full_name']); ?></td>
                                            <td><?php echo htmlspecialchars($record['department_name'] ?? 'N/A'); ?></td>
                                            <td><?php echo $record['clock_in'] ? date('h:i A', strtotime($record['clock_in'])) : '--:--'; ?></td>
                                            <td><?php echo $record['clock_out'] ? date('h:i A', strtotime($record['clock_out'])) : '--:--'; ?></td>
                                            <td>
                                                <?php if (isset($record['work_type'])): ?>
                                                <span class="badge badge-work-<?php echo $record['work_type']; ?>">
                                                    <i class="bi bi-<?php echo $record['work_type'] == 'office' ? 'building' : 'house'; ?>"></i>
                                                    <?php echo strtoupper($record['work_type']); ?>
                                                </span>
                                                <?php else: ?>
                                                <span class="badge badge-work-office">OFFICE</span>
                                                <?php endif; ?>
                                            </td>
                                            <td><?php echo $record['total_hours'] > 0 ? number_format($record['total_hours'], 1) . ' hrs' : '--'; ?></td>
                                           
                                            <td>
                                                <?php 
                                                $remarks = [];
                                                if ($record['late_minutes'] > 0 && isset($record['work_type']) && $record['work_type'] == 'office') {
                                                    $hours = floor($record['late_minutes'] / 60);
                                                    $minutes = $record['late_minutes'] % 60;
                                                    $late_str = "";
                                                    if ($hours > 0) $late_str .= "$hours hour" . ($hours > 1 ? 's' : '');
                                                    if ($minutes > 0) {
                                                        if ($hours > 0) $late_str .= " ";
                                                        $late_str .= "$minutes minute" . ($minutes > 1 ? 's' : '');
                                                    }
                                                    $remarks[] = "Late $late_str";
                                                }
                                                if ($record['early_leave_minutes'] > 0 && isset($record['work_type']) && $record['work_type'] == 'office') {
                                                    $hours = floor($record['early_leave_minutes'] / 60);
                                                    $minutes = $record['early_leave_minutes'] % 60;
                                                    $early_str = "";
                                                    if ($hours > 0) $early_str .= "$hours hour" . ($hours > 1 ? 's' : '');
                                                    if ($minutes > 0) {
                                                        if ($hours > 0) $early_str .= " ";
                                                        $early_str .= "$minutes minute" . ($minutes > 1 ? 's' : '');
                                                    }
                                                    $remarks[] = "Left $early_str early";
                                                }
                                                if (isset($record['work_type']) && $record['work_type'] == 'wfh') {
                                                    $remarks[] = "Work From Home";
                                                }
                                                echo !empty($remarks) ? implode(', ', $remarks) : '--';
                                                ?>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                            
                            <!-- Today's Summary Stats -->
                            <div class="row mt-4">
                                <div class="col-md-3">
                                    <div class="stat-card">
                                        <div class="stat-number text-primary"><?php echo count($todays_attendance); ?></div>
                                        <div>Employees Present</div>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <?php 
                                    $office_count = 0;
                                    $wfh_count = 0;
                                    foreach ($todays_attendance as $record) {
                                        if (isset($record['work_type'])) {
                                            if ($record['work_type'] == 'office') {
                                                $office_count++;
                                            } elseif ($record['work_type'] == 'wfh') {
                                                $wfh_count++;
                                            }
                                        } else {
                                            $office_count++;
                                        }
                                    }
                                    ?>
                                    <div class="stat-card">
                                        <div class="stat-number text-success"><?php echo $office_count; ?></div>
                                        <div>Office Workers</div>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="stat-card">
                                        <div class="stat-number text-purple"><?php echo $wfh_count; ?></div>
                                        <div>WFH Workers</div>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <?php 
                                    $absent_count = 0;
                                    try {
                                        $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM employees");
                                        $stmt->execute();
                                        $total_employees = $stmt->fetch()['total'];
                                        $absent_count = $total_employees - count($todays_attendance);
                                    } catch (Exception $e) {
                                        $absent_count = 0;
                                    }
                                    ?>
                                    <div class="stat-card">
                                        <div class="stat-number text-warning"><?php echo $absent_count; ?></div>
                                        <div>Employees Absent</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Monthly Report Tab -->
                    <div class="tab-pane fade" id="monthly" role="tabpanel">
                        <div class="action-card">
                            <h5><i class="bi bi-calendar-month"></i> Monthly Attendance Report (<?php echo date('F Y'); ?>)</h5>
                            <p class="text-muted">Attendance statistics for all employees this month.</p>
                            
                            <div class="table-responsive">
                                <table class="table table-hover attendance-table" id="monthlyTable">
                                    <thead>
                                        <tr>
                                            <th>Employee</th>
                                            <th>Department</th>
                                            <th>Present</th>
                                            <th>WFH</th>
                                            <th>Office</th>
                                            <th>Leave</th>
                                            <th>Avg Hours</th>
                                            <th>Work Type</th>
                                            <th>Late Time</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php if (empty($monthly_stats)): ?>
                                        <tr>
                                            <td colspan="9" class="text-center">No attendance records for this month.</td>
                                        </tr>
                                        <?php else: ?>
                                        <?php foreach ($monthly_stats as $stat): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($stat['full_name']); ?></td>
                                            <td><?php echo htmlspecialchars($stat['department_name'] ?? 'N/A'); ?></td>
                                            <td><span class="badge bg-success"><?php echo $stat['present_days']; ?></span></td>
                                            <td><span class="badge bg-info"><?php echo $stat['wfh_days']; ?></span></td>
                                            <td><span class="badge bg-primary"><?php echo $stat['office_days']; ?></span></td>
                                            <td><span class="badge bg-secondary"><?php echo $stat['leave_days']; ?></span></td>
                                            <td><?php echo number_format($stat['avg_hours'], 1); ?> hrs</td>
                                            <td>
                                                <?php 
                                                $total_days = $stat['total_days'];
                                                $office_percent = $total_days > 0 ? round(($stat['office_days'] / $total_days) * 100, 0) : 0;
                                                $wfh_percent = $total_days > 0 ? round(($stat['wfh_type_days'] / $total_days) * 100, 0) : 0;
                                                ?>
                                                <div class="progress" style="height: 20px;">
                                                    <div class="progress-bar bg-primary" style="width: <?php echo $office_percent; ?>%" 
                                                         title="Office: <?php echo $office_percent; ?>%">
                                                        <?php echo $office_percent >= 20 ? $office_percent . '%' : ''; ?>
                                                    </div>
                                                    <div class="progress-bar bg-purple" style="width: <?php echo $wfh_percent; ?>%"
                                                         title="WFH: <?php echo $wfh_percent; ?>%">
                                                        <?php echo $wfh_percent >= 20 ? $wfh_percent . '%' : ''; ?>
                                                    </div>
                                                </div>
                                                <small class="text-muted">
                                                    Office: <?php echo $stat['office_days']; ?> | WFH: <?php echo $stat['wfh_type_days']; ?>
                                                </small>
                                            </td>
                                            <td>
                                                <?php if ($stat['total_late_minutes'] > 0): 
                                                    $hours = floor($stat['total_late_minutes'] / 60);
                                                    $minutes = $stat['total_late_minutes'] % 60;
                                                    $late_str = "";
                                                    if ($hours > 0) $late_str .= "$hours hour" . ($hours > 1 ? 's' : '');
                                                    if ($minutes > 0) {
                                                        if ($hours > 0) $late_str .= " ";
                                                        $late_str .= "$minutes minute" . ($minutes > 1 ? 's' : '');
                                                    }
                                                ?>
                                                <span class="late-indicator"><?php echo $late_str; ?></span>
                                                <?php else: ?>
                                                <span class="text-success">On Time</span>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                            
                            <!-- Monthly Summary Stats -->
                            <?php if (!empty($monthly_stats)): ?>
                            <div class="row mt-4">
                                <div class="col-md-3">
                                    <div class="stat-card">
                                        <div class="stat-number text-primary"><?php echo count($monthly_stats); ?></div>
                                        <div>Total Employees</div>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <?php 
                                    $total_office = array_sum(array_column($monthly_stats, 'office_days'));
                                    $total_wfh = array_sum(array_column($monthly_stats, 'wfh_type_days'));
                                    ?>
                                    <div class="stat-card">
                                        <div class="stat-number text-success"><?php echo $total_office; ?></div>
                                        <div>Total Office Days</div>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="stat-card">
                                        <div class="stat-number text-purple"><?php echo $total_wfh; ?></div>
                                        <div>Total WFH Days</div>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <?php 
                                    $avg_hours = !empty($monthly_stats) ? 
                                        array_sum(array_column($monthly_stats, 'avg_hours')) / count($monthly_stats) : 0;
                                    ?>
                                    <div class="stat-card">
                                        <div class="stat-number text-secondary"><?php echo number_format($avg_hours, 1); ?></div>
                                        <div>Avg Hours/Employee</div>
                                    </div>
                                </div>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>

    
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
    <script>
        // Initialize DataTables
        $(document).ready(function() {
            $('#attendanceTable').DataTable({
                "order": [[0, "desc"]],
                "pageLength": 10,
                "language": {
                    "emptyTable": "No attendance records found."
                }
            });
            
            <?php if (!$is_employee): ?>
            $('#todayTable').DataTable({
                "pageLength": 10,
                "language": {
                    "emptyTable": "No attendance records for today."
                }
            });
            
            $('#monthlyTable').DataTable({
                "pageLength": 10,
                "language": {
                    "emptyTable": "No monthly records found."
                }
            });
            <?php endif; ?>
        });

        // Real-time clock update with Sri Lanka time
        function updateClock() {
            const now = new Date();
            
            // Format time in 24-hour format
            const hours = String(now.getHours()).padStart(2, '0');
            const minutes = String(now.getMinutes()).padStart(2, '0');
            const seconds = String(now.getSeconds()).padStart(2, '0');
            const timeString = `${hours}:${minutes}:${seconds}`;
            
            // Format date
            const options = { 
                weekday: 'long', 
                year: 'numeric', 
                month: 'long', 
                day: 'numeric'
            };
            const dateString = now.toLocaleDateString('en-US', options);
            
            document.getElementById('current-time').textContent = timeString;
            document.getElementById('current-date').textContent = dateString;
            
            // Check if office hours (9:00 AM to 5:00 PM)
            const currentHour = now.getHours();
            const currentMinute = now.getMinutes();
            
            // Office hours: 9:00 to 17:00
            const isOfficeHours = (currentHour > 9 || (currentHour === 9 && currentMinute >= 0)) && 
                                 (currentHour < 17 || (currentHour === 17 && currentMinute === 0));
            
            // Update office hours indicator
            const indicator = document.getElementById('office-hours-indicator');
            if (isOfficeHours) {
                indicator.className = 'office-hours-indicator office-open';
                indicator.innerHTML = '<i class="bi bi-building"></i> Office Hours: 9:00 AM - 5:00 PM (Open)';
            } else {
                indicator.className = 'office-hours-indicator office-closed';
                indicator.innerHTML = '<i class="bi bi-building"></i> Office Hours: 9:00 AM - 5:00 PM (Closed)';
            }
        }

        // Update clock every second
        setInterval(updateClock, 1000);
        updateClock(); // Initial call

        // Work type selection functions
        function showWorkTypeSelection() {
            document.getElementById('workTypeModal').style.display = 'flex';
            resetWorkTypeSelection();
        }
        
        function selectWorkType(type) {
            // Remove selected class from all options
            document.getElementById('officeOption').classList.remove('selected');
            document.getElementById('wfhOption').classList.remove('selected');
            
            // Add selected class to clicked option
            document.getElementById(type + 'Option').classList.add('selected');
            
            // Set selected value
            document.getElementById('selectedWorkType').value = type;
            
            // Enable confirm button
            document.getElementById('confirmWorkTypeBtn').disabled = false;
        }
        
        function resetWorkTypeSelection() {
            document.getElementById('officeOption').classList.remove('selected');
            document.getElementById('wfhOption').classList.remove('selected');
            document.getElementById('selectedWorkType').value = '';
            document.getElementById('confirmWorkTypeBtn').disabled = true;
        }
        
        function cancelWorkType() {
            document.getElementById('workTypeModal').style.display = 'none';
            resetWorkTypeSelection();
        }
        
        function confirmWorkType() {
            const workType = document.getElementById('selectedWorkType').value;
            if (!workType) {
                alert('Please select work type');
                return;
            }
            
            // Hide work type modal
            document.getElementById('workTypeModal').style.display = 'none';
            
            // Show confirmation modal
            const workTypeText = workType === 'office' ? 'Office (On-site)' : 'Work From Home';
            showConfirmation('clock_in', `Are you sure you want to clock in as ${workTypeText}?`, workType);
        }
        
        // Confirmation and form submission
        let pendingAction = '';
        let pendingWorkType = '';
        
        function showConfirmation(action, message, workType = '') {
            pendingAction = action;
            pendingWorkType = workType;
            
            // Set modal content based on action
            const titleMap = {
                'clock_in': 'Clock In Confirmation',
                'lunch_start': 'Start Lunch Confirmation',
                'lunch_end': 'End Lunch Confirmation',
                'clock_out': 'Clock Out Confirmation'
            };
            
            const buttonTextMap = {
                'clock_in': 'Clock In',
                'lunch_start': 'Start Lunch',
                'lunch_end': 'End Lunch',
                'clock_out': 'Clock Out'
            };
            
            document.getElementById('confirmTitle').textContent = titleMap[action] || 'Confirmation';
            document.getElementById('confirmMessage').textContent = message;
            document.getElementById('confirmBtn').textContent = buttonTextMap[action] || 'Confirm';
            
            // Show modal
            document.getElementById('confirmationModal').style.display = 'flex';
        }
        
        function confirmAction() {
            if (!pendingAction) return;
            
            // Show loading
            showLoading('Processing your request...');
            
            // Set the action in hidden input
            document.getElementById('actionInput').value = pendingAction;
            
            // Set work type if it's clock in action
            if (pendingAction === 'clock_in' && pendingWorkType) {
                document.getElementById('workTypeInput').value = pendingWorkType;
            }
            
            // Submit form
            document.getElementById('attendanceForm').submit();
        }
        
        function cancelAction() {
            pendingAction = '';
            pendingWorkType = '';
            document.getElementById('confirmationModal').style.display = 'none';
        }
        
        // Set up confirm button
        document.getElementById('confirmBtn').addEventListener('click', confirmAction);
        
        // Show loading overlay
        function showLoading(message) {
            document.getElementById('loadingText').textContent = message || 'Processing...';
            document.getElementById('loadingOverlay').style.display = 'flex';
        }
        
        // Hide loading overlay
        function hideLoading() {
            document.getElementById('loadingOverlay').style.display = 'none';
        }
        
        // Keyboard shortcuts for quick actions (employees only)
        <?php if ($is_employee): ?>
        document.addEventListener('keydown', function(e) {
            // Only trigger if not typing in an input field
            if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA' || e.target.isContentEditable) {
                return;
            }
            
            // Ctrl+Shift+I for Clock In
            if (e.ctrlKey && e.shiftKey && (e.key === 'I' || e.key === 'i')) {
                e.preventDefault();
                const btn = document.getElementById('btn-clock-in');
                if (btn && !btn.disabled) {
                    showWorkTypeSelection();
                }
            }
            // Ctrl+Shift+O for Clock Out
            else if (e.ctrlKey && e.shiftKey && (e.key === 'O' || e.key === 'o')) {
                e.preventDefault();
                const btn = document.getElementById('btn-clock-out');
                if (btn && !btn.disabled) {
                    showConfirmation('clock_out', 'Are you sure you want to clock out?');
                }
            }
            // Ctrl+Shift+L for Lunch Start
            else if (e.ctrlKey && e.shiftKey && (e.key === 'L' || e.key === 'l')) {
                e.preventDefault();
                const btn = document.getElementById('btn-lunch-start');
                if (btn && !btn.disabled) {
                    showConfirmation('lunch_start', 'Are you sure you want to start lunch?');
                }
            }
            // Escape to close confirmation modal
            else if (e.key === 'Escape') {
                if (document.getElementById('workTypeModal').style.display === 'flex') {
                    cancelWorkType();
                } else if (document.getElementById('confirmationModal').style.display === 'flex') {
                    cancelAction();
                }
            }
        });
        <?php endif; ?>
        
        // Auto-refresh page every 5 minutes to keep data fresh
        setTimeout(() => {
            window.location.reload();
        }, 5 * 60 * 1000);
    </script>
</body>
</html>
<?php
// End output buffering and flush
ob_end_flush();
?>