<?php
require_once __DIR__ . '/../../inc/auth.php';
$session = auth_require('owner');

$pdo = getDB();
$message = '';

// Assign
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $objectId = (int)($_POST['object_id'] ?? 0);
    $userId   = (int)($_POST['user_id'] ?? 0);
    $csrf     = $_POST['csrf_token'] ?? '';

    if (!auth_csrf_verify($csrf)) {
        $message = 'Ошибка безопасности.';
    } elseif ($objectId && $userId) {
        // Роль берётся из профиля сотрудника автоматически
        $stmt = $pdo->prepare("SELECT role FROM users WHERE id=?");
        $stmt->execute([$userId]);
        $userRole = $stmt->fetchColumn();
        if ($userRole) {
            $stmt = $pdo->prepare("INSERT INTO object_assignments (object_id, user_id, role) VALUES (?,?,?)");
            $stmt->execute([$objectId, $userId, $userRole]);
            $message = 'Назначение добавлено.';
            auth_log($session['user_id'], 'assignment_create', "Object: $objectId, User: $userId");
        } else {
            $message = 'Сотрудник не найден.';
        }
    }
}

// Unassign
if (isset($_GET['remove'])) {
    $id = (int)$_GET['remove'];
    if (auth_csrf_verify($_GET['csrf'] ?? '')) {
        $pdo->prepare("UPDATE object_assignments SET unassigned_at=NOW() WHERE id=?")->execute([$id]);
        $message = 'Назначение завершено.';
    }
}

$objects = $pdo->query("SELECT id, name FROM objects WHERE status='active' ORDER BY name")->fetchAll();
$engineers = $pdo->query("SELECT id, full_name, role FROM users WHERE role IN ('engineer','technician') AND is_active ORDER BY full_name")->fetchAll();

// Get active assignments
$assignments = $pdo->query("
    SELECT oa.*, o.name as object_name, u.full_name as user_name, u.role as user_role
    FROM object_assignments oa
    JOIN objects o ON o.id = oa.object_id
    JOIN users u ON u.id = oa.user_id
    WHERE oa.unassigned_at IS NULL
    ORDER BY o.name, u.full_name
")->fetchAll();

$csrf = auth_csrf_token();
require __DIR__ . '/../../inc/header.php';
?>

<div class="main-header">
    <div>
        <h1>Назначения</h1>
        <div class="breadcrumb"><a href="/service/dashboard.php">Главная</a> / Назначения</div>
    </div>
</div>

<?php if ($message): ?>
<div class="alert alert-info"><?= htmlspecialchars($message) ?></div>
<?php endif; ?>

<div class="card">
    <div class="card-header"><h2>Новое назначение</h2></div>
    <form method="post" class="form-row" style="align-items:end;">
        <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
        <div class="form-group">
            <label>Объект</label>
            <select name="object_id" required>
                <option value="">— выберите —</option>
                <?php foreach ($objects as $o): ?>
                <option value="<?= $o['id'] ?>"><?= htmlspecialchars($o['name']) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="form-group">
            <label>Сотрудник</label>
            <select name="user_id" required>
                <option value="">— выберите —</option>
                <?php foreach ($engineers as $e): ?>
                <option value="<?= $e['id'] ?>"><?= htmlspecialchars($e['full_name']) ?> (<?= $e['role'] === 'engineer' ? 'Инженер' : 'Техник' ?>)</option>
                <?php endforeach; ?>
            </select>
        </div>
        <button type="submit" class="btn btn-primary">Назначить</button>
    </form>
</div>

<div class="card">
    <div class="card-header"><h2>Текущие назначения</h2></div>
    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th>Объект</th>
                    <th>Сотрудник</th>
                    <th>Роль на объекте</th>
                    <th>Назначен</th>
                    <th class="actions">Действия</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($assignments)): ?>
                <tr><td colspan="5" style="text-align:center;color:var(--text-muted);">Нет активных назначений</td></tr>
                <?php endif; ?>
                <?php foreach ($assignments as $a): ?>
                <tr>
                    <td><?= htmlspecialchars($a['object_name']) ?></td>
                    <td><?= htmlspecialchars($a['user_name']) ?></td>
                    <td><span class="badge badge-<?= $a['role'] === 'engineer' ? 'high' : 'medium' ?>"><?= $a['role'] === 'engineer' ? 'Инженер' : 'Техник' ?></span></td>
                    <td><?= date('d.m.Y H:i', strtotime($a['assigned_at'])) ?></td>
                    <td class="actions">
                        <a href="?remove=<?= $a['id'] ?>&csrf=<?= $csrf ?>" class="btn btn-danger btn-sm" onclick="return confirm('Отвязать сотрудника от объекта?')" data-tooltip="Отвязать">Отвязать</a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<?php require __DIR__ . '/../../inc/footer.php'; ?>
