<?php
// admin/employees.php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/functions.php';

if (!isAdmin()) {
    header('Location: login.php');
    exit;
}

// Get employees
$stmt = $pdo->query("SELECT e.*, d.name as department_name, des.name as designation_name
                     FROM employees e
                     LEFT JOIN departments d ON e.department = d.name
                     LEFT JOIN designations des ON e.designation = des.name
                     ORDER BY e.id DESC");
$employees = $stmt->fetchAll();

// Get stats
$stmt = $pdo->query("SELECT COUNT(*) as total FROM employees WHERE status = 1");
$total_active = $stmt->fetch()['total'];

$stmt = $pdo->query("SELECT COUNT(*) as total FROM employees");
$total_employees = $stmt->fetch()['total'];

$stmt = $pdo->query("SELECT COUNT(*) as total FROM employees WHERE status = 0");
$total_inactive = $stmt->fetch()['total'];

$success_msg = $_SESSION['success_msg'] ?? '';
$error_msg = $_SESSION['error_msg'] ?? '';
unset($_SESSION['success_msg']);
unset($_SESSION['error_msg']);

include 'header.php';
?>

<style>
.employee-stats {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
    gap: 15px;
    margin-bottom: 25px;
}

.stat-box {
    background: #fff;
    border-radius: 12px;
    padding: 18px 20px;
    text-align: center;
    box-shadow: 0 1px 3px rgba(0,0,0,0.08);
}

.stat-box .stat-number {
    font-size: 28px;
    font-weight: 700;
}

.stat-box .stat-label {
    font-size: 13px;
    color: #64748b;
}

.stat-box .stat-icon {
    font-size: 24px;
    margin-bottom: 5px;
}

.employee-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: #047dc3;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 600;
    font-size: 16px;
    flex-shrink: 0;
}

.employee-avatar img {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    object-fit: cover;
}

.status-badge {
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 500;
}

.status-badge.active {
    background: #86efac;
    color: #166534;
}

.status-badge.inactive {
    background: #fca5a5;
    color: #991b1b;
}

.status-badge.full_time { background: #93c5fd; color: #1e40af; }
.status-badge.part_time { background: #fcd34d; color: #92400e; }
.status-badge.contract { background: #f59e0b; color: #92400e; }
.status-badge.intern { background: #86efac; color: #166534; }

.action-btns {
    display: flex;
    gap: 4px;
    flex-wrap: wrap;
}
</style>

<div class="admin-content">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="fa-solid fa-user-tie me-2"></i> Employees</h2>
        <a href="add-employee.php" class="btn btn-primary">
            <i class="fa-solid fa-plus"></i> Add Employee
        </a>
    </div>

    <!-- Stats -->
    <div class="employee-stats">
        <div class="stat-box">
            <div class="stat-icon text-primary"><i class="fa-solid fa-users"></i></div>
            <div class="stat-number text-primary"><?php echo $total_employees; ?></div>
            <div class="stat-label">Total Employees</div>
        </div>
        <div class="stat-box">
            <div class="stat-icon text-success"><i class="fa-solid fa-user-check"></i></div>
            <div class="stat-number text-success"><?php echo $total_active; ?></div>
            <div class="stat-label">Active</div>
        </div>
        <div class="stat-box">
            <div class="stat-icon text-danger"><i class="fa-solid fa-user-slash"></i></div>
            <div class="stat-number text-danger"><?php echo $total_inactive; ?></div>
            <div class="stat-label">Inactive</div>
        </div>
    </div>

    <?php if ($success_msg): ?>
    <div class="alert alert-success"><?php echo $success_msg; ?></div>
    <?php endif; ?>

    <!-- Employee Table -->
    <div class="admin-card">
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Code</th>
                        <th>Employee</th>
                        <th>Department</th>
                        <th>Designation</th>
                        <th>Phone</th>
                        <th>Type</th>
                        <th>Salary</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($employees)): ?>
                    <tr>
                        <td colspan="9" class="text-center py-4">
                            <i class="fa-regular fa-user-tie fa-2x text-muted d-block mb-2"></i>
                            No employees found. Click "Add Employee" to create one.
                        </td>
                    </tr>
                    <?php else: ?>
                    <?php foreach ($employees as $emp): ?>
                    <tr id="empRow_<?php echo $emp['id']; ?>">
                        <td><code><?php echo $emp['employee_code']; ?></code></td>
                        <td>
                            <div class="d-flex align-items-center gap-2">
                                <div class="employee-avatar">
                                    <?php echo strtoupper(substr($emp['first_name'], 0, 1)); ?>
                                </div>
                                <div>
                                    <strong><?php echo htmlspecialchars($emp['first_name'] . ' ' . $emp['last_name']); ?></strong>
                                    <br><small class="text-muted"><?php echo htmlspecialchars($emp['email'] ?? 'No email'); ?></small>
                                </div>
                            </div>
                        </td>
                        <td><?php echo htmlspecialchars($emp['department_name'] ?? '-'); ?></td>
                        <td><?php echo htmlspecialchars($emp['designation_name'] ?? '-'); ?></td>
                        <td><?php echo htmlspecialchars($emp['phone']); ?></td>
                        <td>
                            <span class="status-badge <?php echo $emp['employee_type']; ?>">
                                <?php echo ucfirst(str_replace('_', ' ', $emp['employee_type'])); ?>
                            </span>
                        </td>
                        <td><?php echo number_format($emp['base_salary']); ?> TK</td>
                        <td>
                            <span class="status-badge <?php echo $emp['status'] ? 'active' : 'inactive'; ?>">
                                <?php echo $emp['status'] ? 'Active' : 'Inactive'; ?>
                            </span>
                        </td>
                        <td>
                            <div class="action-btns">
                                <a href="view-employee.php?id=<?php echo $emp['id']; ?>" class="btn btn-sm btn-primary">
                                    <i class="fa-solid fa-eye"></i>
                                </a>
                                <a href="edit-employee.php?id=<?php echo $emp['id']; ?>" class="btn btn-sm btn-warning">
                                    <i class="fa-solid fa-edit"></i>
                                </a>
                                <a href="employee-attendance.php?emp=<?php echo $emp['id']; ?>" class="btn btn-sm btn-info">
                                    <i class="fa-solid fa-clock"></i>
                                </a>
                                <button onclick="deleteEmployee(<?php echo $emp['id']; ?>)" class="btn btn-sm btn-danger">
                                    <i class="fa-solid fa-trash"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
function deleteEmployee(id) {
    if (!confirm('Are you sure you want to delete this employee?')) return;

    var formData = new FormData();
    formData.append('delete_id', id);

    fetch('delete-employee.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            var row = document.getElementById('empRow_' + id);
            if (row) {
                row.style.transition = 'all 0.5s ease';
                row.style.opacity = '0';
                setTimeout(function() { row.remove(); }, 500);
            }
            showToast('Employee deleted successfully!', 'success');
        } else {
            showToast(data.message || 'Failed to delete', 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showToast('Something went wrong', 'error');
    });
}

function showToast(message, type) {
    var colors = { success: '#22c55e', error: '#ef4444', warning: '#f59e0b', info: '#3b82f6' };
    var toast = document.createElement('div');
    toast.style.cssText = `
        position: fixed; top: 20px; right: 20px; padding: 12px 24px;
        background: ${colors[type] || colors.info}; color: #fff;
        border-radius: 8px; z-index: 9999;
        animation: slideIn 0.3s ease; max-width: 400px; font-size: 14px;
        box-shadow: 0 5px 20px rgba(0,0,0,0.15);
    `;
    toast.textContent = message;
    document.body.appendChild(toast);
    setTimeout(function() { toast.remove(); }, 3000);
}
</script>

<?php include 'footer.php'; ?>