<?php
/**
 * Employee Search API Endpoint
 * Returns employees matching search query
 */

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

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

$query = $_GET['q'] ?? '';
$siteId = getCurrentSiteId();
$db = getDB();

if (strlen($query) < 2) {
    echo json_encode([]);
    exit;
}

try {
    $stmt = $db->prepare("
        SELECT 
            e.employee_id,
            CONCAT(e.first_name, ' ', IFNULL(e.middle_name, ''), ' ', e.last_name) as full_name,
            d.designation_name as designation,
            e.employment_status,
            ems.category
        FROM employees e
        LEFT JOIN designations d ON e.designation_id = d.designation_id
        LEFT JOIN employee_master_sheet ems ON e.employee_id = ems.employee_id
        WHERE e.site_id = ? 
          AND e.employment_status = 'active'
          AND (
              e.first_name LIKE ? OR 
              e.last_name LIKE ? OR 
              e.middle_name LIKE ? OR
              e.employee_code LIKE ?
          )
        ORDER BY e.first_name
        LIMIT 10
    ");
    
    $searchTerm = '%' . $query . '%';
    $stmt->execute([$siteId, $searchTerm, $searchTerm, $searchTerm, $searchTerm]);
    
    $employees = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($employees);
    
} catch (Exception $e) {
    echo json_encode(['error' => $e->getMessage()]);
}
