<?php
/**
 * API Endpoint: Get Employee Details for Transfer
 * Returns employee details for auto-filling transfer form
 */

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

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

$employeeId = isset($_GET['employee_id']) ? (int)$_GET['employee_id'] : 0;

if ($employeeId <= 0) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => 'Invalid employee ID'
    ]);
    exit;
}

try {
    $db = getDB();
    
    $stmt = $db->prepare("
        SELECT 
            e.employee_id,
            e.employee_code,
            e.first_name,
            e.last_name,
            e.middle_name,
            CONCAT(e.first_name, ' ', IFNULL(e.middle_name, ''), ' ', e.last_name) as full_name,
            e.employee_category,
            e.designation_id,
            d.designation_name,
            e.site_id,
            s.site_name
        FROM employees e
        LEFT JOIN designations d ON e.designation_id = d.designation_id
        LEFT JOIN sites s ON e.site_id = s.site_id
        WHERE e.employee_id = ? AND e.employment_status = 'active'
        LIMIT 1
    ");
    $stmt->execute([$employeeId]);
    $employee = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$employee) {
        http_response_code(404);
        echo json_encode([
            'success' => false,
            'error' => 'Employee not found or inactive'
        ]);
        exit;
    }
    
    echo json_encode([
        'success' => true,
        'employee' => $employee
    ]);
    
} catch (Exception $e) {
    error_log("Get employee for transfer API error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}

