<?php
/**
 * Enterprise HRM ERP System - Employee List
 * Excel-like table interface
 */

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

$pageTitle = 'Employee Management';
$currentModule = 'employee';

// Data Isolation: Get site filter
$siteId = getCurrentSiteId();
$siteFilter = getSiteFilter();
$accessibleSiteIds = getAccessibleSiteIds();

// For Employee role, show only own data
if (isEmployee()) {
    // Employee can only see their own record
    $where = ["e.email = ?"];
    $params = [$_SESSION['email'] ?? ''];
} elseif (isSuperAdmin()) {
    // Super Admin can see all or selected site
    if ($siteFilter) {
        $where = ["e.site_id = ?"];
        $params = [$siteFilter];
    } else {
        // All sites
        $where = ["1=1"];
        $params = [];
    }
} elseif (isHRAdmin()) {
    // HR Admin - only their created/managed employees
    $where = ["e.created_by = ?"];
    $params = [getCurrentUserId()];
} else {
    // Default: no access
    $where = ["1=0"];
    $params = [];
}

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

// Filters
$search = sanitize($_GET['search'] ?? '');
$departmentId = isset($_GET['department_id']) ? (int)$_GET['department_id'] : 0;
$status = sanitize($_GET['status'] ?? '');

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

if ($departmentId > 0) {
    $where[] = "e.department_id = ?";
    $params[] = $departmentId;
}

if (!empty($status)) {
    $where[] = "e.employment_status = ?";
    $params[] = $status;
}

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

// Get total count
try {
    $db = getDB();
    $countSql = "SELECT COUNT(*) FROM employees e WHERE {$whereClause}";
    $stmt = $db->prepare($countSql);
    $stmt->execute($params);
    $totalRecords = $stmt->fetchColumn();
    $totalPages = ceil($totalRecords / $perPage);
    
    // Get employees with HR info
    $sql = "
        SELECT 
            e.*,
            d.department_name,
            des.designation_name,
            u.full_name as hr_name,
            CONCAT(e.first_name, ' ', COALESCE(e.middle_name, ''), ' ', e.last_name) as full_name
        FROM employees e
        LEFT JOIN departments d ON e.department_id = d.department_id
        LEFT JOIN designations des ON e.designation_id = des.designation_id
        LEFT JOIN users u ON e.created_by = u.user_id
        WHERE {$whereClause}
        ORDER BY e.employee_code ASC
        LIMIT ? OFFSET ?
    ";
    $params[] = $perPage;
    $params[] = $offset;
    
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    $employees = $stmt->fetchAll();
    
    // Get departments for filter (based on accessible sites)
    if (isEmployee()) {
        $departments = []; // Employee doesn't need department filter
    } elseif (isSuperAdmin() && $siteFilter) {
        $stmt = $db->prepare("SELECT department_id, department_name FROM departments WHERE site_id = ? AND department_status = 'active' ORDER BY department_name");
        $stmt->execute([$siteFilter]);
        $departments = $stmt->fetchAll();
    } elseif (!empty($accessibleSiteIds)) {
        $placeholders = implode(',', array_fill(0, count($accessibleSiteIds), '?'));
        $stmt = $db->prepare("SELECT department_id, department_name FROM departments WHERE site_id IN ($placeholders) AND department_status = 'active' ORDER BY department_name");
        $stmt->execute($accessibleSiteIds);
        $departments = $stmt->fetchAll();
    } else {
        $departments = [];
    }
    
} catch (Exception $e) {
    error_log("Employee list error: " . $e->getMessage());
    $employees = [];
    $departments = [];
    $totalRecords = 0;
    $totalPages = 0;
}

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

<div class="table-container">
    <div class="table-header">
        <h2 class="table-title">Employees</h2>
        <div class="table-actions">
            <?php if (hasPermission('EMPLOYEE_CREATE')): ?>
            <a href="<?php echo BASE_URL; ?>/modules/employee/create.php" class="btn btn-primary">Add Employee</a>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- Role & Access Info -->
    <?php if (isHRAdmin()): ?>
    <div style="background: #e8f5e9; border-left: 4px solid #4caf50; padding: 10px 15px; margin: 15px 0; border-radius: 4px;">
        <strong>ℹ️ HR Admin View:</strong> You can only see and manage employees you have created.
    </div>
    <?php elseif (isSuperAdmin()): ?>
    <div style="background: #e3f2fd; border-left: 4px solid #2196f3; padding: 10px 15px; margin: 15px 0; border-radius: 4px;">
        <strong>ℹ️ Admin View:</strong> You can see all employees from all HRs. The "Managed By HR" column shows which HR manages each employee.
    </div>
    <?php endif; ?>
    
    <div class="table-filters">
        <div class="filter-group">
            <label>Search</label>
            <input type="text" name="search" class="form-control" placeholder="Code, Name, Email..." 
                   value="<?php echo htmlspecialchars($search); ?>" 
                   onkeypress="if(event.key==='Enter') filterTable()">
        </div>
        <div class="filter-group">
            <label>Department</label>
            <select name="department_id" class="form-control" onchange="filterTable()">
                <option value="">All Departments</option>
                <?php foreach ($departments as $dept): ?>
                <option value="<?php echo $dept['department_id']; ?>" 
                        <?php echo $departmentId == $dept['department_id'] ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($dept['department_name']); ?>
                </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="filter-group">
            <label>Status</label>
            <select name="status" class="form-control" onchange="filterTable()">
                <option value="">All Status</option>
                <option value="active" <?php echo $status === 'active' ? 'selected' : ''; ?>>Active</option>
                <option value="inactive" <?php echo $status === 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                <option value="terminated" <?php echo $status === 'terminated' ? 'selected' : ''; ?>>Terminated</option>
                <option value="resigned" <?php echo $status === 'resigned' ? 'selected' : ''; ?>>Resigned</option>
            </select>
        </div>
        <div class="filter-group">
            <button type="button" class="btn btn-secondary" onclick="resetFilters()">Reset</button>
        </div>
    </div>
    
    <?php if (count($employees) > 0): ?>
    <div class="table-scroll-wrapper">
        <table class="data-table">
            <thead>
                <tr>
                    <th class="sortable">Code</th>
                    <th class="sortable">Name</th>
                    <?php if (isSuperAdmin()): ?>
                    <th class="sortable">Managed By HR</th>
                    <?php endif; ?>
                    <th class="sortable">Email</th>
                    <th class="sortable">Phone</th>
                    <th class="sortable">Department</th>
                    <th class="sortable">Designation</th>
                    <th class="sortable">Join Date</th>
                    <th class="sortable">Status</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($employees as $emp): ?>
                <tr>
                    <td><?php echo htmlspecialchars($emp['employee_code']); ?></td>
                    <td><?php echo htmlspecialchars($emp['full_name']); ?></td>
                    <?php if (isSuperAdmin()): ?>
                    <td style="font-size: 12px; color: #666;">
                        <?php echo htmlspecialchars($emp['hr_name'] ?? 'Not Assigned'); ?>
                    </td>
                    <?php endif; ?>
                    <td><?php echo htmlspecialchars($emp['email'] ?? '-'); ?></td>
                    <td><?php echo htmlspecialchars($emp['phone'] ?? '-'); ?></td>
                    <td><?php echo htmlspecialchars($emp['department_name'] ?? '-'); ?></td>
                    <td><?php echo htmlspecialchars($emp['designation_name'] ?? '-'); ?></td>
                    <td><?php echo formatDate($emp['date_of_joining']); ?></td>
                    <td>
                        <span class="status-badge status-<?php echo htmlspecialchars($emp['employment_status']); ?>">
                            <?php echo ucfirst($emp['employment_status']); ?>
                        </span>
                    </td>
                    <td class="table-actions-cell">
                        <?php if (hasPermission('EMPLOYEE_VIEW')): ?>
                        <a href="<?php echo BASE_URL; ?>/modules/employee/view.php?id=<?php echo $emp['employee_id']; ?>" 
                           class="btn btn-sm btn-secondary">View</a>
                        <?php endif; ?>
                        <?php if (hasPermission('EMPLOYEE_EDIT')): ?>
                        <a href="<?php echo BASE_URL; ?>/modules/employee/edit.php?id=<?php echo $emp['employee_id']; ?>" 
                           class="btn btn-sm btn-primary">Edit</a>
                        <?php endif; ?>
                        <?php if (hasPermission('EMPLOYEE_EDIT')): ?>
                            <?php if ($emp['employment_status'] === 'active'): ?>
                            <a href="<?php echo BASE_URL; ?>/modules/employee/change_status.php?id=<?php echo $emp['employee_id']; ?>&status=inactive" 
                               class="btn btn-sm btn-warning" 
                               onclick="return confirm('Are you sure you want to set this employee status to Inactive?')"
                               title="Set to Inactive">Deactivate</a>
                            <?php elseif ($emp['employment_status'] === 'inactive'): ?>
                            <a href="<?php echo BASE_URL; ?>/modules/employee/change_status.php?id=<?php echo $emp['employee_id']; ?>&status=active" 
                               class="btn btn-sm btn-success" 
                               onclick="return confirm('Are you sure you want to activate this employee?')"
                               title="Set to Active">Activate</a>
                            <?php endif; ?>
                        <?php endif; ?>
                        <?php if (hasPermission('EMPLOYEE_DELETE')): ?>
                        <a href="<?php echo BASE_URL; ?>/modules/employee/delete.php?id=<?php echo $emp['employee_id']; ?>" 
                           class="btn btn-sm btn-danger" 
                           onclick="return confirm('Are you sure you want to delete this employee? If the employee has related records, you will be given an option to force delete.')">Delete</a>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    
    <div class="table-footer">
        <div class="table-info">
            Showing <?php echo $offset + 1; ?> to <?php echo min($offset + $perPage, $totalRecords); ?> of <?php echo number_format($totalRecords); ?> employees
        </div>
        <div class="pagination">
            <?php if ($page > 1): ?>
            <a href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>&department_id=<?php echo $departmentId; ?>&status=<?php echo urlencode($status); ?>" 
               class="btn btn-sm">Previous</a>
            <?php endif; ?>
            <span class="pagination-info">Page <?php echo $page; ?> of <?php echo $totalPages; ?></span>
            <?php if ($page < $totalPages): ?>
            <a href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>&department_id=<?php echo $departmentId; ?>&status=<?php echo urlencode($status); ?>" 
               class="btn btn-sm">Next</a>
            <?php endif; ?>
        </div>
    </div>
    <?php else: ?>
    <div class="table-empty">
        <div class="table-empty-icon">👥</div>
        <div class="table-empty-message">No employees found</div>
        <div class="table-empty-submessage">
            <?php if (hasPermission('EMPLOYEE_CREATE')): ?>
            <a href="<?php echo BASE_URL; ?>/modules/employee/create.php" class="btn btn-primary">Add First Employee</a>
            <?php endif; ?>
        </div>
    </div>
    <?php endif; ?>
</div>

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

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

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

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

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

/* Table Scroll Wrapper for Horizontal Scrolling */
.table-scroll-wrapper {
    overflow-x: auto;
    overflow-y: visible;
    -webkit-overflow-scrolling: touch;
    position: relative;
    width: 100%;
}

.table-scroll-wrapper::-webkit-scrollbar {
    height: 8px;
}

.table-scroll-wrapper::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
}

.table-scroll-wrapper::-webkit-scrollbar-thumb {
    background: #888;
    border-radius: 4px;
}

.table-scroll-wrapper::-webkit-scrollbar-thumb:hover {
    background: #555;
}

/* Responsive adjustments */
@media (max-width: 1024px) {
    .table-scroll-wrapper {
        overflow-x: auto;
    }
    
    .data-table {
        min-width: 900px;
    }
}

@media (max-width: 768px) {
    .table-scroll-wrapper {
        overflow-x: auto;
        -webkit-overflow-scrolling: touch;
    }
    
    .data-table {
        min-width: 800px;
        font-size: 12px;
    }
    
    .data-table th,
    .data-table td {
        padding: 8px 6px;
        font-size: 12px;
    }
    
    .table-actions-cell {
        width: auto;
        min-width: 150px;
    }
    
    .table-actions-cell .btn {
        padding: 4px 6px;
        font-size: 10px;
        margin: 2px 1px;
    }
}

@media (max-width: 480px) {
    .data-table {
        min-width: 700px;
        font-size: 11px;
    }
    
    .data-table th,
    .data-table td {
        padding: 6px 4px;
        font-size: 11px;
    }
}
</style>

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

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

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

