<?php
/**
 * Employee Search API for Autocomplete
 * Returns employees matching the search query
 */

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

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

$query = $_GET['q'] ?? '';

if (strlen($query) < 2) {
    echo json_encode(['success' => false, 'message' => 'Query too short', 'employees' => []]);
    exit;
}

$db = getDB();

try {
    $searchTerm = '%' . $query . '%';
    
    // Data isolation: Get accessible site IDs
    require_once __DIR__ . '/../includes/data_isolation.php';
    $accessibleSiteIds = getAccessibleSiteIds();
    
    if (empty($accessibleSiteIds)) {
        echo json_encode(['success' => true, 'employees' => []]);
        exit;
    }
    
    $placeholders = implode(',', array_fill(0, count($accessibleSiteIds), '?'));
    
    // For HR Admin, only show employees they created
    if (isHRAdmin()) {
        $whereClause = "e.site_id IN ($placeholders) AND e.created_by = ? AND e.employment_status = 'active'";
        $params = array_merge($accessibleSiteIds, [getCurrentUserId(), $searchTerm, $searchTerm, $searchTerm, $searchTerm]);
    } else {
        $whereClause = "e.site_id IN ($placeholders) AND e.employment_status = 'active'";
        $params = array_merge($accessibleSiteIds, [$searchTerm, $searchTerm, $searchTerm, $searchTerm]);
    }
    
    $stmt = $db->prepare("
        SELECT 
            e.employee_id,
            e.employee_code,
            CONCAT(e.first_name, ' ', IFNULL(e.middle_name, ''), ' ', e.last_name) as full_name,
            e.employment_status,
            d.designation_name,
            dept.department_name,
            e.phone,
            e.email,
            u.full_name as reporting_manager
        FROM employees e
        LEFT JOIN designations d ON e.designation_id = d.designation_id
        LEFT JOIN departments dept ON e.department_id = dept.department_id
        LEFT JOIN users u ON e.created_by = u.user_id
        WHERE {$whereClause}
        AND (
            e.employee_code LIKE ? 
            OR e.first_name LIKE ? 
            OR e.last_name LIKE ?
            OR CONCAT(e.first_name, ' ', e.last_name) LIKE ?
        )
        ORDER BY e.employee_code
        LIMIT 20
    ");
    
    $stmt->execute($params);
    $employees = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'employees' => $employees,
        'count' => count($employees)
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage(),
        'employees' => []
    ]);
}
