<?php
/**
 * Employee Live Search API
 * Returns JSON data for autocomplete/live search
 */

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

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

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

if (empty($query) || strlen($query) < 2) {
    echo json_encode(['success' => false, 'employees' => []]);
    exit;
}

try {
    $db = getDB();
    
    // Search in both main employees table and employee_master_sheet
    $stmt = $db->prepare("
        SELECT DISTINCT
            e.employee_id,
            e.employee_code as emp_id,
            CONCAT(e.first_name, ' ', IFNULL(e.middle_name, ''), ' ', e.last_name) as employee_name,
            d.department_name as department,
            des.designation_name as designation,
            e.phone as contact_number
        FROM employees e
        LEFT JOIN departments d ON e.department_id = d.department_id
        LEFT JOIN designations des ON e.designation_id = des.designation_id
        WHERE e.site_id = ? 
        AND e.employment_status = 'active'
        AND (
            e.employee_code LIKE ? 
            OR e.first_name LIKE ? 
            OR e.last_name LIKE ? 
            OR e.middle_name LIKE ?
            OR CONCAT(e.first_name, ' ', e.last_name) LIKE ?
        )
        
        UNION
        
        SELECT DISTINCT
            ems.employee_id,
            ems.emp_id,
            ems.employee_name,
            ems.department,
            ems.designation,
            ems.contact_number
        FROM employee_master_sheet ems
        WHERE ems.site_id = ?
        AND (
            ems.emp_id LIKE ?
            OR ems.employee_name LIKE ?
        )
        
        ORDER BY employee_name
        LIMIT 10
    ");
    
    $searchParam = "%{$query}%";
    $stmt->execute([
        $siteId, $searchParam, $searchParam, $searchParam, $searchParam, $searchParam,
        $siteId, $searchParam, $searchParam
    ]);
    
    $employees = $stmt->fetchAll();
    
    echo json_encode([
        'success' => true,
        'employees' => $employees
    ]);
    
} catch (Exception $e) {
    error_log("Employee search error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'error' => 'Search error',
        'employees' => []
    ]);
}

