<?php
/**
 * Enterprise HRM ERP System - Get Employees by Site (AJAX)
 */

require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/check_admin_access.php';

header('Content-Type: application/json');

$siteId = isset($_GET['site_id']) ? (int)$_GET['site_id'] : 0;

if ($siteId <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid site ID']);
    exit;
}

try {
    $db = getDB();
    $stmt = $db->prepare("
        SELECT e.employee_id, e.employee_code, e.first_name, e.last_name, e.middle_name, e.site_id,
               CONCAT(COALESCE(e.first_name, ''), ' ', COALESCE(e.middle_name, ''), ' ', COALESCE(e.last_name, '')) as full_name,
               (SELECT user_id FROM users WHERE employee_id = e.employee_id LIMIT 1) as linked_user_id
        FROM employees e
        WHERE e.site_id = ? AND e.employment_status = 'active'
        ORDER BY e.first_name, e.last_name
    ");
    $stmt->execute([$siteId]);
    $employees = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Filter out employees already linked to users
    $availableEmployees = [];
    foreach ($employees as $emp) {
        if (empty($emp['linked_user_id'])) {
            $availableEmployees[] = [
                'employee_id' => $emp['employee_id'],
                'employee_code' => $emp['employee_code'],
                'full_name' => trim($emp['full_name']),
                'site_id' => $emp['site_id']
            ];
        }
    }
    
    echo json_encode([
        'success' => true,
        'employees' => $availableEmployees
    ]);
    
} catch (Exception $e) {
    error_log("Error loading employees: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Error loading employees'
    ]);
}

