<?php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';
$user  = requireRole([1, 5]);
$db    = getDB();
$empId = (int)post('employee_id', 0);
if (!$empId) apiError('Employee ID required.', 422);

$userId = post('user_id', '');
$userId = ($userId !== '' && $userId !== null) ? (int)$userId : null;

try {
    // If linking, check user isn't already linked to another employee
    if ($userId) {
        $chk = $db->prepare("SELECT id FROM employees WHERE user_id=? AND id!=?");
        $chk->execute([$userId, $empId]);
        if ($chk->fetch()) apiError('This user is already linked to another employee.', 409);
    }
    $db->prepare("UPDATE employees SET user_id=? WHERE id=?")->execute([$userId, $empId]);
    apiSuccess([], $userId ? 'User linked.' : 'User unlinked.');
} catch (PDOException $e) {
    apiError('Database error: ' . $e->getMessage(), 500);
}
