<?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();
$search = isset($_GET['q']) ? trim($_GET['q']) : '';
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 20;

try {
    $db = getDB();
    
    $whereConditions = ["e.site_id = ?", "e.employment_status = 'active'"];
    $params = [$siteId];
    
    // Apply search filter
    if (!empty($search)) {
        $whereConditions[] = "(e.employee_code LIKE ? OR e.first_name LIKE ? OR e.last_name LIKE ? OR e.middle_name LIKE ? OR CONCAT(e.first_name, ' ', IFNULL(e.middle_name, ''), ' ', e.last_name) LIKE ?)";
        $searchParam = "%{$search}%";
        $params = array_merge($params, [$searchParam, $searchParam, $searchParam, $searchParam, $searchParam]);
    }
    
    // HR Admin: Only see employees they created/manage
    if (isHRAdmin()) {
        $whereConditions[] = "e.created_by = ?";
        $params[] = getCurrentUserId();
    }
    
    $whereClause = implode(' AND ', $whereConditions);
    
    $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
        FROM employees e
        LEFT JOIN designations d ON e.designation_id = d.designation_id
        WHERE {$whereClause}
        ORDER BY e.employee_code
        LIMIT ?
    ");
    
    $params[] = $limit;
    $stmt->execute($params);
    $employees = $stmt->fetchAll();
    
    $results = [];
    foreach ($employees as $emp) {
        $results[] = [
            'id' => $emp['employee_id'],
            'code' => $emp['employee_code'],
            'name' => $emp['full_name'],
            'designation' => $emp['designation_name'] ?? '',
            'text' => $emp['employee_code'] . ' - ' . $emp['full_name'] . ($emp['designation_name'] ? ' (' . $emp['designation_name'] . ')' : '')
        ];
    }
    
    echo json_encode([
        'success' => true,
        'results' => $results
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
