<?php
// Get statistics based on user role
$total_employees = 0;
$today_present = 0;
$pending_leaves = 0;
$total_interns = 0;
$pending_approvals = 0;

// Get total employees
if (hasPermission('view_employees')) {
    $stmt = $pdo->query("SELECT COUNT(*) as total FROM employees");
    $total_employees = $stmt->fetch()['total'];
}

// Get today's present count
if (hasPermission('view_attendance')) {
    // If manager, only show their department's attendance
    if (isManager() && isset($_SESSION['department'])) {
        $stmt = $pdo->prepare("
            SELECT COUNT(DISTINCT a.employee_id) as active 
            FROM attendance a
            JOIN employees e ON a.employee_id = e.id
            WHERE a.attendance_date = CURDATE() 
            AND a.status IN ('present', 'wfh', 'half-day')
            AND e.department = ?
        ");
        $stmt->execute([$_SESSION['department']]);
    } else {
        $stmt = $pdo->query("
            SELECT COUNT(DISTINCT employee_id) as active 
            FROM attendance 
            WHERE attendance_date = CURDATE() 
            AND status IN ('present', 'wfh', 'half-day')
        ");
    }
    $today_present = $stmt->fetch()['active'];
}

// Get pending leaves count
if (hasPermission('manage_leaves') || hasPermission('apply_leaves')) {
    // If manager, only show leaves from their department
    if (isManager() && isset($_SESSION['department'])) {
        $stmt = $pdo->prepare("
            SELECT COUNT(*) as pending 
            FROM leaves l
            JOIN employees e ON l.employee_id = e.id
            WHERE l.status = 'pending'
            AND e.department = ?
        ");
        $stmt->execute([$_SESSION['department']]);
    } else {
        $stmt = $pdo->query("SELECT COUNT(*) as pending FROM leaves WHERE status = 'pending'");
    }
    $pending_leaves = $stmt->fetch()['pending'];
}

// Get interns count
if (hasPermission('manage_interns')) {
    $stmt = $pdo->query("SELECT COUNT(*) as interns FROM employees WHERE employment_type = 'intern'");
    $total_interns = $stmt->fetch()['interns'];
}

// Get pending approvals count (for admin only)
if (isAdmin()) {
    $stmt = $pdo->query("SELECT COUNT(*) as pending FROM users WHERE is_active = 0 AND role = 'employee'");
    $pending_approvals = $stmt->fetch()['pending'];
}

// Get recent activities
$recent_activities = [];
try {
    $query = "SELECT 'attendance' as type, e.full_name, a.attendance_date as date, 
              CONCAT('Checked in at ', TIME_FORMAT(a.clock_in, '%h:%i %p')) as description
              FROM attendance a
              JOIN employees e ON a.employee_id = e.id
              WHERE a.attendance_date = CURDATE()
              AND a.clock_in IS NOT NULL
              ORDER BY a.clock_in DESC
              LIMIT 5";
    $stmt = $pdo->query($query);
    $recent_activities = $stmt->fetchAll();
} catch (Exception $e) {
    // Silently fail
}
?>

<div class="row mb-4">
    <?php if(hasPermission('view_employees')): ?>
    <div class="col-md-3 mb-3">
        <div class="card border-primary border-2">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h6 class="card-title text-muted">Total Employees</h6>
                        <h2 class="text-primary mb-0"><?php echo $total_employees; ?></h2>
                    </div>
                    <div class="rounded-circle bg-primary bg-opacity-10 p-3">
                        <i class="bi bi-people fs-3 text-primary"></i>
                    </div>
                </div>
                <p class="card-text mt-2"><small class="text-muted">All departments</small></p>
            </div>
            <div class="card-footer bg-transparent border-top-0">
                <a href="dashboard.php?page=employees" class="btn btn-sm btn-outline-primary w-100">View All</a>
            </div>
        </div>
    </div>
    <?php endif; ?>
    
    <?php if(hasPermission('view_attendance')): ?>
    <div class="col-md-3 mb-3">
        <div class="card border-success border-2">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h6 class="card-title text-muted">Today Present</h6>
                        <h2 class="text-success mb-0"><?php echo $today_present; ?></h2>
                    </div>
                    <div class="rounded-circle bg-success bg-opacity-10 p-3">
                        <i class="bi bi-calendar-check fs-3 text-success"></i>
                    </div>
                </div>
                <p class="card-text mt-2"><small class="text-muted"><?php echo date('l, F j'); ?></small></p>
            </div>
            <div class="card-footer bg-transparent border-top-0">
                <a href="dashboard.php?page=attendance" class="btn btn-sm btn-outline-success w-100">View Attendance</a>
            </div>
        </div>
    </div>
    <?php endif; ?>
    
    <?php if(hasPermission('apply_leaves')): ?>
    <div class="col-md-3 mb-3">
        <div class="card border-warning border-2">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h6 class="card-title text-muted">Pending Leaves</h6>
                        <h2 class="text-warning mb-0"><?php echo $pending_leaves; ?></h2>
                    </div>
                    <div class="rounded-circle bg-warning bg-opacity-10 p-3">
                        <i class="bi bi-calendar-event fs-3 text-warning"></i>
                    </div>
                </div>
                <p class="card-text mt-2"><small class="text-muted">Awaiting approval</small></p>
            </div>
            <div class="card-footer bg-transparent border-top-0">
                <a href="dashboard.php?page=leave" class="btn btn-sm btn-outline-warning w-100">Manage Leaves</a>
            </div>
        </div>
    </div>
    <?php endif; ?>
    
    <?php if(isAdmin()): ?>
    <div class="col-md-3 mb-3">
        <div class="card border-danger border-2">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h6 class="card-title text-muted">Pending Approvals</h6>
                        <h2 class="text-danger mb-0"><?php echo $pending_approvals; ?></h2>
                    </div>
                    <div class="rounded-circle bg-danger bg-opacity-10 p-3">
                        <i class="bi bi-person-plus fs-3 text-danger"></i>
                    </div>
                </div>
                <p class="card-text mt-2"><small class="text-muted">New registrations</small></p>
            </div>
            <div class="card-footer bg-transparent border-top-0">
                <?php if($pending_approvals > 0): ?>
                <a href="dashboard.php?page=pending_approvals" class="btn btn-sm btn-danger w-100">Review Now</a>
                <?php else: ?>
                <a href="dashboard.php?page=users" class="btn btn-sm btn-outline-danger w-100">View Users</a>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <?php elseif(hasPermission('manage_interns')): ?>
    <div class="col-md-3 mb-3">
        <div class="card border-info border-2">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h6 class="card-title text-muted">Active Interns</h6>
                        <h2 class="text-info mb-0"><?php echo $total_interns; ?></h2>
                    </div>
                    <div class="rounded-circle bg-info bg-opacity-10 p-3">
                        <i class="bi bi-person-badge fs-3 text-info"></i>
                    </div>
                </div>
                <p class="card-text mt-2"><small class="text-muted">Training interns</small></p>
            </div>
            <div class="card-footer bg-transparent border-top-0">
                <a href="dashboard.php?page=interns" class="btn btn-sm btn-outline-info w-100">Manage Interns</a>
            </div>
        </div>
    </div>
    <?php endif; ?>
</div>

<!-- Quick Actions -->
<div class="row mb-4">
    <div class="col-md-8">
        <div class="card">
            <div class="card-header bg-white border-bottom">
                <h5 class="mb-0"><i class="bi bi-lightning-charge text-warning me-2"></i>Quick Actions</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <?php if(hasPermission('manage_employees')): ?>
                    <div class="col-md-3 mb-3">
                        <a href="dashboard.php?page=employees" class="btn btn-outline-primary w-100 py-3 d-flex flex-column align-items-center">
                            <i class="bi bi-person-plus fs-1 mb-2"></i>
                            <span>Add Employee</span>
                        </a>
                    </div>
                    <?php endif; ?>
                    
                    <?php if(hasPermission('view_attendance')): ?>
                    <div class="col-md-3 mb-3">
                        <a href="dashboard.php?page=attendance" class="btn btn-outline-success w-100 py-3 d-flex flex-column align-items-center">
                            <i class="bi bi-clock-history fs-1 mb-2"></i>
                            <span>Mark Attendance</span>
                        </a>
                    </div>
                    <?php endif; ?>
                    
                    <?php if(hasPermission('apply_leaves')): ?>
                    <div class="col-md-3 mb-3">
                        <a href="dashboard.php?page=leave" class="btn btn-outline-warning w-100 py-3 d-flex flex-column align-items-center">
                            <i class="bi bi-calendar-plus fs-1 mb-2"></i>
                            <span>Apply Leave</span>
                        </a>
                    </div>
                    <?php endif; ?>
                    
                    <?php if(hasPermission('manage_interns')): ?>
                    <div class="col-md-3 mb-3">
                        <a href="dashboard.php?page=interns" class="btn btn-outline-info w-100 py-3 d-flex flex-column align-items-center">
                            <i class="bi bi-person-badge fs-1 mb-2"></i>
                            <span>Manage Interns</span>
                        </a>
                    </div>
                    <?php endif; ?>
                    
                    <?php if(hasPermission('view_reports')): ?>
                    <div class="col-md-3 mb-3">
                        <a href="dashboard.php?page=reports" class="btn btn-outline-secondary w-100 py-3 d-flex flex-column align-items-center">
                            <i class="bi bi-file-earmark-text fs-1 mb-2"></i>
                            <span>Generate Reports</span>
                        </a>
                    </div>
                    <?php endif; ?>
                    
                    <div class="col-md-3 mb-3">
                        <a href="dashboard.php?page=profile" class="btn btn-outline-dark w-100 py-3 d-flex flex-column align-items-center">
                            <i class="bi bi-person-circle fs-1 mb-2"></i>
                            <span>My Profile</span>
                        </a>
                    </div>
                    
                    <?php if(isAdmin() && $pending_approvals > 0): ?>
                    <div class="col-md-3 mb-3">
                        <a href="dashboard.php?page=pending_approvals" class="btn btn-danger w-100 py-3 d-flex flex-column align-items-center">
                            <i class="bi bi-person-check fs-1 mb-2"></i>
                            <span>Pending Approvals</span>
                            <span class="badge bg-white text-danger mt-1"><?php echo $pending_approvals; ?></span>
                        </a>
                    </div>
                    <?php endif; ?>
                    
                    <?php if($_SESSION['role'] !== 'admin'): ?>
                    <div class="col-md-3 mb-3">
                        <a href="register.php" class="btn btn-outline-info w-100 py-3 d-flex flex-column align-items-center">
                            <i class="bi bi-person-plus fs-1 mb-2"></i>
                            <span>Register New</span>
                        </a>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-4">
        <div class="card">
            <div class="card-header bg-white border-bottom">
                <h5 class="mb-0"><i class="bi bi-info-circle text-primary me-2"></i>System Information</h5>
            </div>
            <div class="card-body">
                <ul class="list-group list-group-flush">
                    <li class="list-group-item d-flex justify-content-between align-items-center">
                        <span>Your Role:</span>
                        <span class="badge 
                            <?php 
                            echo $_SESSION['role'] == 'admin' ? 'bg-danger' : 
                                 ($_SESSION['role'] == 'manager' ? 'bg-warning' : 'bg-success'); 
                            ?>">
                            <?php echo ucfirst($_SESSION['role']); ?>
                        </span>
                    </li>
                    <li class="list-group-item d-flex justify-content-between align-items-center">
                        <span>Login Time:</span>
                        <span><?php echo date('h:i A', $_SESSION['login_time'] ?? time()); ?></span>
                    </li>
                    <li class="list-group-item d-flex justify-content-between align-items-center">
                        <span>Current Date:</span>
                        <span><?php echo date('Y-m-d'); ?></span>
                    </li>
                    <?php if(isset($_SESSION['department']) && !empty($_SESSION['department'])): ?>
                    <li class="list-group-item d-flex justify-content-between align-items-center">
                        <span>Department:</span>
                        <span><?php echo htmlspecialchars($_SESSION['department']); ?></span>
                    </li>
                    <?php endif; ?>
                    <?php if(isset($_SESSION['employee_id'])): ?>
                    <li class="list-group-item d-flex justify-content-between align-items-center">
                        <span>Employee ID:</span>
                        <span>EMP<?php echo str_pad($_SESSION['employee_id'], 4, '0', STR_PAD_LEFT); ?></span>
                    </li>
                    <?php endif; ?>
                </ul>
            </div>
        </div>
    </div>
</div>

<!-- Recent Activities -->
<?php if(!empty($recent_activities)): ?>
<div class="row">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header bg-white border-bottom">
                <h5 class="mb-0"><i class="bi bi-activity text-success me-2"></i>Recent Activities</h5>
            </div>
            <div class="card-body">
                <div class="list-group">
                    <?php foreach($recent_activities as $activity): ?>
                    <div class="list-group-item list-group-item-action border-0">
                        <div class="d-flex w-100 justify-content-between">
                            <div>
                                <i class="bi bi-clock-history text-primary me-2"></i>
                                <strong><?php echo htmlspecialchars($activity['full_name']); ?></strong>
                                <span class="text-muted"><?php echo $activity['description']; ?></span>
                            </div>
                            <small class="text-muted"><?php echo date('h:i A', strtotime($activity['date'])); ?></small>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- Welcome Message for New Users -->
<?php if(isset($_GET['welcome']) && $_GET['welcome'] == '1'): ?>
<div class="row mt-4">
    <div class="col-md-12">
        <div class="alert alert-success alert-dismissible fade show">
            <h4><i class="bi bi-emoji-smile"></i> Welcome to HR System!</h4>
            <p>Your account has been successfully activated. You can now access all features of the system.</p>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    </div>
</div>
<?php endif; ?>