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

$pdo = getDB();
$message = '';
$userId = $session['user_id'];

// Get my open tasks
$stmt = $pdo->prepare("
    SELECT t.*, o.name as object_name, o.address
    FROM tasks t
    JOIN objects o ON o.id = t.object_id
    WHERE t.assigned_to = ? AND t.status IN ('open','in_progress')
    ORDER BY CASE t.priority WHEN 'P1' THEN 1 WHEN 'P2' THEN 2 WHEN 'P3' THEN 3 WHEN 'P4' THEN 4 END, t.deadline ASC
");
$stmt->execute([$userId]);
$myTasks = $stmt->fetchAll();

// Close task with checklist data
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['close_task'])) {
    $taskId = (int)$_POST['task_id'];
    $csrf = $_POST['csrf_token'] ?? '';
    if (!auth_csrf_verify($csrf)) {
        $message = 'Ошибка безопасности.';
    } else {
        $checklist = [
            'arrival_fixed' => isset($_POST['arrival_fixed']) ? 1 : 0,
            'photo_before'  => isset($_POST['photo_before']) ? 1 : 0,
            'power_check'   => isset($_POST['power_check']) ? 1 : 0,
            'cameras_check' => isset($_POST['cameras_check']) ? 1 : 0,
            'acs_check'     => isset($_POST['acs_check']) ? 1 : 0,
            'fire_check'    => isset($_POST['fire_check']) ? 1 : 0,
            'fault_found'   => isset($_POST['fault_found']) ? 1 : 0,
            'fault_fixed'   => isset($_POST['fault_fixed']) ? 1 : 0,
            'system_test'   => isset($_POST['system_test']) ? 1 : 0,
            'photo_after'   => isset($_POST['photo_after']) ? 1 : 0,
        ];
        $notes = trim($_POST['result_notes'] ?? '');

        $pdo->prepare("UPDATE tasks SET status='completed', closed_at=NOW(), checklist_data=?, result_notes=? WHERE id=? AND assigned_to=?")
            ->execute([json_encode($checklist), $notes, $taskId, $userId]);
        $message = 'Задача завершена.';
        auth_log($userId, 'task_complete', "Task: $taskId");
        // Reload
        $stmt->execute([$userId]);
        $myTasks = $stmt->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-success"><?= htmlspecialchars($message) ?></div>
<?php endif; ?>

<?php if (empty($myTasks)): ?>
<div class="card">
    <div class="empty-state">
        <h3>Нет активных задач</h3>
        <p>Вам пока не назначены задачи. Ожидайте назначения от инженера.</p>
    </div>
</div>
<?php else: ?>
    <?php foreach ($myTasks as $task): ?>
    <div class="card">
        <div class="card-header">
            <h2><?= htmlspecialchars($task['title']) ?> <span class="badge badge-<?= strtolower($task['priority']) ?>"><?= $task['priority'] ?></span></h2>
            <span style="color:var(--text-muted);">
                <?php if ($task['deadline']): ?>
                Дедлайн: <?= date('d.m.Y H:i', strtotime($task['deadline'])) ?>
                <?php endif; ?>
            </span>
        </div>
        <p style="margin-bottom:12px;color:var(--text-secondary);">
            <strong>Объект:</strong> <?= htmlspecialchars($task['object_name']) ?>
            <?php if ($task['address']): ?> · <?= htmlspecialchars($task['address']) ?><?php endif; ?>
        </p>
        <?php if ($task['description']): ?>
        <p style="margin-bottom:16px;"><?= nl2br(htmlspecialchars($task['description'])) ?></p>
        <?php endif; ?>

        <form method="post">
            <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
            <input type="hidden" name="task_id" value="<?= $task['id'] ?>">
            <input type="hidden" name="close_task" value="1">

            <h3 style="font-size:14px;font-weight:600;margin-bottom:12px;">Чек-лист выполнения</h3>
            <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:8px;margin-bottom:16px;">
                <label class="form-check"><input type="checkbox" name="arrival_fixed"> Прибытие зафиксировано</label>
                <label class="form-check"><input type="checkbox" name="photo_before"> Фото «до»</label>
                <label class="form-check"><input type="checkbox" name="power_check"> Проверка питания</label>
                <label class="form-check"><input type="checkbox" name="cameras_check"> Проверка камер / датчиков</label>
                <label class="form-check"><input type="checkbox" name="acs_check"> Проверка СКУД</label>
                <label class="form-check"><input type="checkbox" name="fire_check"> Проверка пожарной панели</label>
                <label class="form-check"><input type="checkbox" name="fault_found"> Неисправность локализована</label>
                <label class="form-check"><input type="checkbox" name="fault_fixed"> Неисправность устранена</label>
                <label class="form-check"><input type="checkbox" name="system_test"> Тестирование системы</label>
                <label class="form-check"><input type="checkbox" name="photo_after"> Фото «после»</label>
            </div>

            <div class="form-group">
                <label for="notes">Примечания / Результат</label>
                <textarea id="notes" name="result_notes" rows="3" placeholder="Что сделано, что выявлено..."></textarea>
            </div>

            <button type="submit" class="btn btn-success" onclick="return confirm('Завершить задачу?')">✓ Завершить задачу</button>
        </form>
    </div>
    <?php endforeach; ?>
<?php endif; ?>

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