<?php
require_once __DIR__ . '/../includes/header.php';
$pdo = db();

$success = $error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrf_check($_POST['csrf_token'] ?? null)) {
        $error = 'Token inválido.';
    } else {
        $action = $_POST['action'] ?? '';
        if ($action === 'create') {
            $title     = trim($_POST['title'] ?? 'Manutenção');
            $startsAt  = trim($_POST['starts_at'] ?? '');
            $endsAt    = trim($_POST['ends_at'] ?? '');
            $ipId      = (int)($_POST['monitored_ip_id'] ?? 0);
            $allIps    = isset($_POST['all_ips']) ? true : false;

            if (!$title || !$startsAt || !$endsAt) {
                $error = 'Preencha todos os campos.';
            } elseif ($startsAt >= $endsAt) {
                $error = 'A data de início deve ser anterior à data de fim.';
            } else {
                $pdo->prepare("
                    INSERT INTO maintenance_windows (user_id, monitored_ip_id, title, starts_at, ends_at, all_ips)
                    VALUES (?, ?, ?, ?, ?, ?)
                ")->execute([$user['id'], $allIps ? null : ($ipId ?: null), $title, $startsAt, $endsAt, $allIps]);
                $success = 'Janela de manutenção criada!';
            }
        } elseif ($action === 'delete') {
            $wId = (int)($_POST['window_id'] ?? 0);
            if ($wId) {
                $pdo->prepare("DELETE FROM maintenance_windows WHERE id = ? AND user_id = ?")->execute([$wId, $user['id']]);
                $success = 'Janela removida.';
            }
        } elseif ($action === 'toggle') {
            $wId = (int)($_POST['window_id'] ?? 0);
            if ($wId) {
                $pdo->prepare("UPDATE maintenance_windows SET active = NOT active WHERE id = ? AND user_id = ?")->execute([$wId, $user['id']]);
                $success = 'Status alterado.';
            }
        }
        redirect('index.php?page=user_maintenance' . ($success ? '&ok=1' : ''));
    }
}
if (isset($_GET['ok'])) $success = 'Operação realizada!';

// Lista hosts do usuário para o select
$myIps = $pdo->prepare("SELECT id, label, host FROM monitored_ips WHERE user_id = ? AND active = TRUE ORDER BY label ASC");
$myIps->execute([$user['id']]);
$myIps = $myIps->fetchAll();

// Lista janelas de manutenção
$windows = $pdo->prepare("
    SELECT mw.*, mi.label AS ip_label, mi.host AS ip_host
    FROM maintenance_windows mw
    LEFT JOIN monitored_ips mi ON mi.id = mw.monitored_ip_id
    WHERE mw.user_id = ?
    ORDER BY mw.starts_at DESC
    LIMIT 50
");
$windows->execute([$user['id']]);
$windows = $windows->fetchAll();

$now = new DateTimeImmutable();
?>

<div class="card">
    <div class="card-head">
        <div>
            <h2>🔧 Janelas de Manutenção</h2>
            <p>Agende períodos de manutenção para suprimir alertas automaticamente.</p>
        </div>
    </div>

    <?php if ($success): ?><div class="alert alert-success"><?php echo h($success); ?></div><?php endif; ?>
    <?php if ($error): ?><div class="alert alert-error"><?php echo h($error); ?></div><?php endif; ?>

    <!-- Formulário -->
    <form method="POST" style="background:var(--bg-main);border:1px solid var(--border);border-radius:12px;padding:20px;margin-bottom:24px;">
        <input type="hidden" name="csrf_token" value="<?php echo csrf_token(); ?>">
        <input type="hidden" name="action" value="create">
        <h3 style="margin:0 0 16px;">Nova janela de manutenção</h3>
        <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:12px;">
            <div>
                <label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px;">Título</label>
                <input type="text" name="title" value="Manutenção programada" maxlength="150" required
                       style="width:100%;padding:9px 12px;border:1px solid var(--border);border-radius:8px;background:var(--bg-card);color:var(--text-primary);font-size:14px;">
            </div>
            <div>
                <label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px;">Início</label>
                <input type="datetime-local" name="starts_at" required
                       style="width:100%;padding:9px 12px;border:1px solid var(--border);border-radius:8px;background:var(--bg-card);color:var(--text-primary);font-size:14px;">
            </div>
            <div>
                <label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px;">Fim</label>
                <input type="datetime-local" name="ends_at" required
                       style="width:100%;padding:9px 12px;border:1px solid var(--border);border-radius:8px;background:var(--bg-card);color:var(--text-primary);font-size:14px;">
            </div>
            <div>
                <label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px;">Host específico</label>
                <select name="monitored_ip_id" id="ipSelect"
                        style="width:100%;padding:9px 12px;border:1px solid var(--border);border-radius:8px;background:var(--bg-card);color:var(--text-primary);font-size:14px;">
                    <option value="">— Todos os hosts —</option>
                    <?php foreach ($myIps as $ip): ?>
                    <option value="<?php echo $ip['id']; ?>"><?php echo h($ip['label']); ?> (<?php echo h($ip['host']); ?>)</option>
                    <?php endforeach; ?>
                </select>
            </div>
        </div>
        <div style="margin-top:12px;display:flex;align-items:center;gap:10px;">
            <label style="display:flex;align-items:center;gap:6px;font-size:13px;cursor:pointer;">
                <input type="checkbox" name="all_ips" id="allIpsChk" onchange="document.getElementById('ipSelect').disabled=this.checked">
                Aplicar a <strong>todos</strong> os meus hosts
            </label>
        </div>
        <div style="margin-top:16px;">
            <button type="submit" class="primary-button">🔧 Criar janela de manutenção</button>
        </div>
    </form>

    <!-- Lista de janelas -->
    <?php if (empty($windows)): ?>
        <div style="text-align:center;padding:40px;color:var(--text-secondary);">
            <div style="font-size:48px;margin-bottom:12px;">🔧</div>
            <p>Nenhuma janela de manutenção cadastrada.</p>
            <p style="font-size:13px;">Durante manutenções, os alertas ficam automaticamente suprimidos.</p>
        </div>
    <?php else: ?>
        <table>
            <thead>
                <tr>
                    <th>Título</th>
                    <th>Host</th>
                    <th>Início</th>
                    <th>Fim</th>
                    <th>Status</th>
                    <th>Ações</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($windows as $w):
                    $start = new DateTimeImmutable($w['starts_at']);
                    $end   = new DateTimeImmutable($w['ends_at']);
                    $isActive = $w['active'] && $now >= $start && $now <= $end;
                    $isPast   = $now > $end;
                    $isFuture = $now < $start;
                    $statusLabel = $isActive ? '🟢 Ativa' : ($isPast ? '⬜ Concluída' : ($isFuture ? '🕐 Agendada' : '⏸️ Pausada'));
                    $statusColor = $isActive ? 'var(--success)' : ($isPast ? 'var(--text-secondary)' : 'var(--primary)');
                ?>
                <tr>
                    <td><strong><?php echo h($w['title']); ?></strong></td>
                    <td>
                        <?php if ($w['all_ips']): ?>
                            <span style="color:var(--primary);">Todos os hosts</span>
                        <?php elseif ($w['ip_label']): ?>
                            <?php echo h($w['ip_label']); ?>
                        <?php else: ?>
                            <span style="color:var(--text-secondary);">—</span>
                        <?php endif; ?>
                    </td>
                    <td><?php echo format_datetime_tz($w['starts_at'], $user['timezone'] ?? null, 'd/m/Y H:i'); ?></td>
                    <td><?php echo format_datetime_tz($w['ends_at'], $user['timezone'] ?? null, 'd/m/Y H:i'); ?></td>
                    <td><span style="color:<?php echo $statusColor; ?>;font-weight:600;"><?php echo $statusLabel; ?></span></td>
                    <td>
                        <div style="display:flex;gap:6px;">
                            <?php if (!$isPast): ?>
                            <form method="POST" style="display:inline;">
                                <input type="hidden" name="csrf_token" value="<?php echo csrf_token(); ?>">
                                <input type="hidden" name="action" value="toggle">
                                <input type="hidden" name="window_id" value="<?php echo $w['id']; ?>">
                                <button type="submit" class="ghost-button" style="padding:4px 10px;font-size:12px;">
                                    <?php echo $w['active'] ? '⏸️ Pausar' : '▶️ Ativar'; ?>
                                </button>
                            </form>
                            <?php endif; ?>
                            <form method="POST" onsubmit="return confirm('Remover esta janela de manutenção?');" style="display:inline;">
                                <input type="hidden" name="csrf_token" value="<?php echo csrf_token(); ?>">
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="window_id" value="<?php echo $w['id']; ?>">
                                <button type="submit" class="ghost-button" style="padding:4px 10px;font-size:12px;color:var(--danger);">Remover</button>
                            </form>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</div>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>
