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

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id       = (int)($_POST['id'] ?? 0);
    $objectId = (int)($_POST['object_id'] ?? 0);
    $type     = $_POST['report_type'] ?? 'service';
    $title    = trim($_POST['title'] ?? '');
    $desc     = trim($_POST['description'] ?? '');
    $findings = trim($_POST['findings'] ?? '');
    $recs     = trim($_POST['recommendations'] ?? '');
    $workDone = trim($_POST['work_done'] ?? '');
    $cause    = trim($_POST['cause_classification'] ?? '');
    $status   = $_POST['status'] ?? 'draft';
    $result   = $_POST['result_status'] ?? 'ok';
    $csrf     = $_POST['csrf_token'] ?? '';

    if (!auth_csrf_verify($csrf)) {
        $message = 'Ошибка безопасности.';
    } elseif (!$objectId) {
        $message = 'Объект обязателен.';
    } else {
        try {
            if ($id > 0) {
                $stmt = $pdo->prepare("UPDATE reports SET object_id=?, report_type=?, title=?, description=?, findings=?, recommendations=?, work_done=?, cause_classification=?, status=?, result_status=? WHERE id=? AND created_by=?");
                $stmt->execute([$objectId, $type, $title, $desc, $findings, $recs, $workDone, $cause, $status, $result, $id, $userId]);
            } else {
                $stmt = $pdo->prepare("INSERT INTO reports (object_id, created_by, report_type, title, description, findings, recommendations, work_done, cause_classification, status, result_status) VALUES (?,?,?,?,?,?,?,?,?,?,?)");
                $stmt->execute([$objectId, $userId, $type, $title, $desc, $findings, $recs, $workDone, $cause, $status, $result]);
            }
            $message = 'Отчёт сохранён.';
            auth_log($userId, 'report_save', "Object: $objectId");
        } catch (\PDOException $e) {
            $message = 'Ошибка: ' . $e->getMessage();
        }
    }
}

$editReport = null;
if (isset($_GET['edit'])) {
    $stmt = $pdo->prepare("SELECT * FROM reports WHERE id=? AND created_by=?");
    $stmt->execute([(int)$_GET['edit'], $userId]);
    $editReport = $stmt->fetch();
}

$typeFilter = $_GET['type'] ?? '';
$sql = "SELECT r.*, o.name as object_name FROM reports r JOIN objects o ON o.id=r.object_id WHERE 1=1";
$params = [];
if ($session['user_role'] === 'technician') {
    $sql .= " AND r.created_by = ?";
    $params[] = $userId;
}
if ($typeFilter) {
    $sql .= " AND r.report_type = ?";
    $params[] = $typeFilter;
}
$sql .= " ORDER BY r.created_at DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$reports = $stmt->fetchAll();

$objects = $pdo->query("SELECT id, name FROM objects WHERE status IN ('active','audit') ORDER BY 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>
    <button class="btn btn-primary btn-sm" onclick="openModal()">+ Создать</button>
</div>

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

<div class="filter-bar">
    <form method="get">
        <select name="type" onchange="this.form.submit()">
            <option value="">Все типы</option>
            <option value="inspection" <?= $typeFilter === 'inspection' ? 'selected' : '' ?>>Осмотр</option>
            <option value="service" <?= $typeFilter === 'service' ? 'selected' : '' ?>>Обслуживание</option>
            <option value="emergency" <?= $typeFilter === 'emergency' ? 'selected' : '' ?>>Аварийный</option>
            <option value="audit" <?= $typeFilter === 'audit' ? 'selected' : '' ?>>Аудит</option>
            <option value="monthly" <?= $typeFilter === 'monthly' ? 'selected' : '' ?>>Месячный</option>
        </select>
        <?php if ($typeFilter): ?><a href="reports.php" class="btn btn-secondary btn-sm">Сброс</a><?php endif; ?>
    </form>
</div>

<div class="card">
    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th>Тип</th>
                    <th>Название</th>
                    <th>Объект</th>
                    <th>Статус</th>
                    <th>Результат</th>
                    <th>Дата</th>
                    <th class="actions">Действия</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($reports)): ?>
                <tr><td colspan="7" style="text-align:center;color:var(--text-muted);">Нет отчётов</td></tr>
                <?php endif; ?>
                <?php foreach ($reports as $r): ?>
                <tr>
                    <td><span class="badge badge-medium"><?= $r['report_type'] ?></span></td>
                    <td><strong><?= htmlspecialchars($r['title'] ?: 'Без названия') ?></strong></td>
                    <td><?= htmlspecialchars($r['object_name']) ?></td>
                    <td><span class="badge badge-<?= $r['status'] ?>"><?= $r['status'] ?></span></td>
                    <td><span class="badge badge-<?= $r['result_status'] === 'ok' ? 'done' : ($r['result_status'] === 'partial' ? 'high' : 'medium') ?>"><?= $r['result_status'] ?></span></td>
                    <td><?= date('d.m.Y', strtotime($r['created_at'])) ?></td>
                    <td class="actions">
                        <a href="?edit=<?= $r['id'] ?>" class="btn btn-secondary btn-sm">✏️</a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<div class="modal-overlay <?= $editReport ? 'open' : '' ?>" id="reportModal">
    <div class="modal">
        <button class="modal-close" onclick="closeModal()">&times;</button>
        <h2><?= $editReport ? 'Редактировать' : 'Создать' ?> отчёт</h2>
        <form method="post" enctype="multipart/form-data">
            <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
            <input type="hidden" name="id" value="<?= $editReport['id'] ?? 0 ?>">
            <div class="form-row">
                <div class="form-group">
                    <label for="object_id">Объект *</label>
                    <select id="object_id" name="object_id" required>
                        <option value="">— выберите —</option>
                        <?php foreach ($objects as $o): ?>
                        <option value="<?= $o['id'] ?>" <?= ($editReport['object_id'] ?? 0) === $o['id'] ? 'selected' : '' ?>><?= htmlspecialchars($o['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label for="report_type">Тип</label>
                    <select id="report_type" name="report_type">
                        <option value="inspection" <?= ($editReport['report_type'] ?? '') === 'inspection' ? 'selected' : '' ?>>Осмотр</option>
                        <option value="service" <?= ($editReport['report_type'] ?? '') === 'service' ? 'selected' : '' ?>>Обслуживание</option>
                        <option value="emergency" <?= ($editReport['report_type'] ?? '') === 'emergency' ? 'selected' : '' ?>>Аварийный</option>
                        <option value="audit" <?= ($editReport['report_type'] ?? '') === 'audit' ? 'selected' : '' ?>>Аудит</option>
                        <option value="monthly" <?= ($editReport['report_type'] ?? '') === 'monthly' ? 'selected' : '' ?>>Месячный</option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label for="title">Название</label>
                <input type="text" id="title" name="title" value="<?= htmlspecialchars($editReport['title'] ?? '') ?>">
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label for="status">Статус</label>
                    <select id="status" name="status">
                        <option value="draft" <?= ($editReport['status'] ?? '') === 'draft' ? 'selected' : '' ?>>Черновик</option>
                        <option value="final" <?= ($editReport['status'] ?? '') === 'final' ? 'selected' : '' ?>>Итоговый</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="result_status">Результат</label>
                    <select id="result_status" name="result_status">
                        <option value="ok" <?= ($editReport['result_status'] ?? '') === 'ok' ? 'selected' : '' ?>>Исправлено</option>
                        <option value="fixed" <?= ($editReport['result_status'] ?? '') === 'fixed' ? 'selected' : '' ?>>Исправлено</option>
                        <option value="partial" <?= ($editReport['result_status'] ?? '') === 'partial' ? 'selected' : '' ?>>Частично</option>
                        <option value="revisit" <?= ($editReport['result_status'] ?? '') === 'revisit' ? 'selected' : '' ?>>Повторный выезд</option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label for="description">Описание</label>
                <textarea id="description" name="description"><?= htmlspecialchars($editReport['description'] ?? '') ?></textarea>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label for="findings">Выявленные проблемы</label>
                    <textarea id="findings" name="findings"><?= htmlspecialchars($editReport['findings'] ?? '') ?></textarea>
                </div>
                <div class="form-group">
                    <label for="recommendations">Рекомендации</label>
                    <textarea id="recommendations" name="recommendations"><?= htmlspecialchars($editReport['recommendations'] ?? '') ?></textarea>
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label for="work_done">Выполненные работы</label>
                    <textarea id="work_done" name="work_done"><?= htmlspecialchars($editReport['work_done'] ?? '') ?></textarea>
                </div>
                <div class="form-group">
                    <label for="cause_classification">Классификация причины</label>
                    <select id="cause_classification" name="cause_classification">
                        <option value="">—</option>
                        <option value="Hardware" <?= ($editReport['cause_classification'] ?? '') === 'Hardware' ? 'selected' : '' ?>>Hardware</option>
                        <option value="Software" <?= ($editReport['cause_classification'] ?? '') === 'Software' ? 'selected' : '' ?>>Software</option>
                        <option value="Network" <?= ($editReport['cause_classification'] ?? '') === 'Network' ? 'selected' : '' ?>>Network</option>
                        <option value="Human error" <?= ($editReport['cause_classification'] ?? '') === 'Human error' ? 'selected' : '' ?>>Человеческий фактор</option>
                        <option value="External" <?= ($editReport['cause_classification'] ?? '') === 'External' ? 'selected' : '' ?>>Внешний фактор</option>
                    </select>
                </div>
            </div>
            <button type="submit" class="btn btn-primary">Сохранить</button>
            <button type="button" class="btn btn-secondary" onclick="closeModal()">Отмена</button>
        </form>
    </div>
</div>

<script>
function openModal() { document.getElementById('reportModal').classList.add('open'); }
function closeModal() { document.getElementById('reportModal').classList.remove('open'); window.location.href = 'reports.php'; }
</script>

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