<?php
/**
 * AJAX Endpoint: Search Employees
 * Returns JSON list of employees matching search query
 */

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

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

$siteId = getCurrentSiteId();
$query = isset($_GET['q']) ? trim($_GET['q']) : '';
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 50;

try {
    $db = getDB();
    
    // Build search query
    $whereConditions = ["e.site_id = ?", "e.employment_status = 'active'"];
    $params = [$siteId];
    
    // Apply HR-level filtering
    if (isHRAdmin()) {
        $whereConditions[] = "e.created_by = ?";
        $params[] = getCurrentUserId();
    }
    
    // Add search term
    if (!empty($query)) {
        $whereConditions[] = "(e.employee_code LIKE ? OR e.first_name LIKE ? OR e.last_name LIKE ? OR CONCAT(e.first_name, ' ', IFNULL(e.middle_name, ''), ' ', e.last_name) LIKE ?)";
        $searchTerm = "%{$query}%";
        $params = array_merge($params, [$searchTerm, $searchTerm, $searchTerm, $searchTerm]);
    }
    
    $whereClause = implode(' AND ', $whereConditions);
    
    // Fetch employees
    $stmt = $db->prepare("
        SELECT 
            e.employee_id,
            e.employee_code,
            CONCAT(e.first_name, ' ', IFNULL(e.middle_name, ''), ' ', e.last_name) as full_name,
            d.designation_name,
            e.first_name,
            e.last_name
        FROM employees e
        LEFT JOIN designations d ON e.designation_id = d.designation_id
        WHERE {$whereClause}
        ORDER BY e.employee_code ASC
        LIMIT ?
    ");
    $params[] = $limit;
    $stmt->execute($params);
    $employees = $stmt->fetchAll();
    
    // Format response
    $results = [];
    foreach ($employees as $emp) {
        $results[] = [
            'id' => $emp['employee_id'],
            'code' => $emp['employee_code'],
            'name' => $emp['full_name'],
            'designation' => $emp['designation_name'] ?? '',
            'display' => $emp['employee_code'] . ' - ' . $emp['full_name'] . ($emp['designation_name'] ? ' (' . $emp['designation_name'] . ')' : '')
        ];
    }
    
    echo json_encode([
        'success' => true,
        'results' => $results,
        'count' => count($results)
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
