<?php
/**
 * API Endpoint: Get Employee Transfers
 * Returns transfer data for real-time updates
 */

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

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

try {
    $siteId = getCurrentSiteId();
    $db = getDB();
    
    // Get all active employees
    $stmt = $db->prepare("
        SELECT 
            e.employee_id,
            e.employee_code,
            e.first_name,
            e.last_name,
            e.middle_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.employment_status = 'active'
        ORDER BY e.employee_code
    ");
    $stmt->execute();
    $employees = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get all sites
    $stmt = $db->query("SELECT site_id, site_name FROM sites ORDER BY site_name");
    $sites = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get existing transfers (if needed for editing)
    // Check if table exists first
    try {
        $tableCheck = $db->query("SHOW TABLES LIKE 'employee_transfers'");
        if ($tableCheck->rowCount() > 0) {
            $stmt = $db->prepare("
                SELECT 
                    t.*,
                    e.employee_code,
                    e.first_name,
                    e.last_name,
                    e.middle_name,
                    d.designation_name,
                    fs.site_name as from_site_name,
                    ts.site_name as to_site_name
                FROM employee_transfers t
                INNER JOIN employees e ON t.employee_id = e.employee_id
                LEFT JOIN designations d ON e.designation_id = d.designation_id
                LEFT JOIN sites fs ON t.from_site_id = fs.site_id
                LEFT JOIN sites ts ON t.to_site_id = ts.site_id
                WHERE t.transfer_status != 'cancelled'
                ORDER BY t.transfer_date DESC, t.created_at DESC
                LIMIT 50
            ");
            $stmt->execute();
            $transfers = $stmt->fetchAll(PDO::FETCH_ASSOC);
        } else {
            $transfers = [];
        }
    } catch (Exception $e) {
        // Table doesn't exist, return empty array
        $transfers = [];
    }
    
    echo json_encode([
        'success' => true,
        'employees' => $employees,
        'sites' => $sites,
        'transfers' => $transfers,
        'count' => count($employees)
    ]);
    
} catch (Exception $e) {
    error_log("Get transfers API error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

