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

// Buscar ou criar registro existente
$stmt = $pdo->prepare("SELECT * FROM status_pages WHERE user_id = ? LIMIT 1");
$stmt->execute([$user['id']]);
$statusPage = $stmt->fetch();

$ipsStmt = $pdo->prepare("SELECT id, label, host, last_status, last_latency_ms, last_check_at FROM monitored_ips WHERE user_id = ? ORDER BY created_at DESC");
$ipsStmt->execute([$user['id']]);
$userIps = $ipsStmt->fetchAll();

$pageIps = [];
if ($statusPage) {
    $stmtIps = $pdo->prepare("SELECT monitored_ip_id FROM status_pages_ips WHERE status_page_id = ?");
    $stmtIps->execute([$statusPage['id']]);
    $pageIps = array_column($stmtIps->fetchAll(), 'monitored_ip_id');
}

$successMsg = null;
$errorMsg = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrf_check($_POST['csrf_token'] ?? null)) {
        $errorMsg = 'CSRF invalido.';
    } else {
        $title = trim($_POST['title'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $active = isset($_POST['active']) ? 1 : 0;
        $accessPasswordRaw = trim($_POST['access_password'] ?? '');
        // Se veio nova senha, faz hash. Se campo vazio, mantém a atual (null = sem proteção)
        if ($accessPasswordRaw !== '') {
            $accessPassword = password_hash($accessPasswordRaw, PASSWORD_DEFAULT);
        } elseif ($statusPage && !empty($statusPage['access_password'])) {
            $accessPassword = $statusPage['access_password']; // mantém hash existente
        } else {
            $accessPassword = null;
        }
        $selectedIps = isset($_POST['ips']) && is_array($_POST['ips']) ? array_map('intval', $_POST['ips']) : [];

        if ($title === '') {
            $title = 'Status de ' . ($user['name'] ?? 'Meu serviço');
        }

        // Garantir slug
        $slug = $statusPage['slug'] ?? '';
        if (empty($slug) || isset($_POST['regen_slug'])) {
            do {
                $slug = generate_slug(12);
                $check = $pdo->prepare("SELECT COUNT(*) FROM status_pages WHERE slug = ?");
                $check->execute([$slug]);
            } while ((int)$check->fetchColumn() > 0);
        }

        try {
            if ($statusPage) {
                $stmtUpd = $pdo->prepare("
                    UPDATE status_pages
                    SET title = ?, description = ?, active = ?, slug = ?, access_password = ?
                    WHERE id = ? AND user_id = ?
                ");
                $stmtUpd->execute([$title, $description, $active, $slug, $accessPassword, $statusPage['id'], $user['id']]);
                $statusPageId = (int)$statusPage['id'];
            } else {
                $stmtIns = $pdo->prepare("
                    INSERT INTO status_pages (user_id, slug, title, description, active, access_password)
                    VALUES (?, ?, ?, ?, ?, ?)
                ");
                $stmtIns->execute([$user['id'], $slug, $title, $description, $active, $accessPassword]);
                $statusPageId = (int)$pdo->lastInsertId();
            }

            // Atualizar IPs selecionados
            $pdo->prepare("DELETE FROM status_pages_ips WHERE status_page_id = ?")->execute([$statusPageId]);
            $insertLink = $pdo->prepare("INSERT INTO status_pages_ips (status_page_id, monitored_ip_id) VALUES (?, ?)");
            foreach ($selectedIps as $ipId) {
                $insertLink->execute([$statusPageId, $ipId]);
            }

            $successMsg = 'Página de status atualizada.';
            $statusPage = [
                'id' => $statusPageId,
                'slug' => $slug,
                'title' => $title,
                'description' => $description,
                'active' => $active,
            ];
            $pageIps = $selectedIps;
        } catch (Exception $e) {
            $errorMsg = $e->getMessage();
        }
    }
}

$publicUrl = $statusPage ? (BASE_URL . 'status.php?slug=' . $statusPage['slug']) : null;
?>

<div style="background:#fff; border-radius:20px; border:1px solid #e2e8f0; box-shadow:0 10px 15px -3px rgba(0,0,0,0.05); overflow:hidden;">
    <div style="padding: 24px 32px; border-bottom:1px solid #e2e8f0; background:#f8fafc;">
        <h2 style="margin:0; font-size:1.6rem; color:#0f172a; font-weight:800;">Status Page (Página Pública)</h2>
        <p style="margin:4px 0 0; color:#64748b; font-size:1rem;">Gere e gerencie um portal público de transparência (SLA) para mostrar aos seus clientes a saúde dos sistemas em tempo real.</p>
    </div>
    
    <div style="padding: 32px;">
        <?php if ($successMsg): ?>
            <div style="padding:12px 16px; background:#dcfce7; border-left:4px solid #22c55e; color:#166534; border-radius:6px; margin-bottom:24px; font-weight:600;">
                <?php echo h($successMsg); ?>
            </div>
        <?php endif; ?>
        <?php if ($errorMsg): ?>
            <div style="padding:12px 16px; background:#fee2e2; border-left:4px solid #ef4444; color:#b91c1c; border-radius:6px; margin-bottom:24px; font-weight:600;">
                <?php echo h($errorMsg); ?>
            </div>
        <?php endif; ?>

        <?php if ($publicUrl): ?>
            <div style="background:#eff6ff; border:1px solid #bfdbfe; border-radius:12px; padding:20px; margin-bottom:32px; display:flex; flex-wrap:wrap; gap:16px; justify-content:space-between; align-items:center;">
                <div>
                    <h4 style="margin:0 0 4px; color:#1e3a8a; font-size:1rem;">Seu link público já está no ar 🚀</h4>
                    <a href="<?php echo h($publicUrl); ?>" target="_blank" style="color:#2563eb; font-weight:700; font-family:monospace; font-size:1.1rem; text-decoration:none;"><?php echo h($publicUrl); ?></a>
                </div>
                <form method="post" style="margin:0;">
                    <input type="hidden" name="csrf_token" value="<?php echo h(csrf_token()); ?>">
                    <!-- Precisamos recriar os hiddens do form para não perder estado ao regenerar link -->
                    <input type="hidden" name="title" value="<?php echo h($statusPage['title']); ?>">
                    <input type="hidden" name="description" value="<?php echo h($statusPage['description'] ?? ''); ?>">
                    <?php if(isset($statusPage['active']) && $statusPage['active']): ?>
                        <input type="hidden" name="active" value="1">
                    <?php endif; ?>
                    <?php foreach($pageIps as $pid): ?>
                        <input type="hidden" name="ips[]" value="<?php echo $pid; ?>">
                    <?php endforeach; ?>
                    
                    <button type="submit" name="regen_slug" value="1" style="background:#fff; border:1px solid #93c5fd; color:#2563eb; font-weight:600; padding:8px 16px; border-radius:8px; cursor:pointer; font-size:0.9rem; transition:0.2s;" onmouseover="this.style.background='#dbeafe'" onmouseout="this.style.background='#fff'">Refazer URL (Revogar anterior)</button>
                </form>
            </div>
        <?php endif; ?>

        <form method="post" style="display:flex; flex-direction:column; gap:24px;">
            <input type="hidden" name="csrf_token" value="<?php echo h(csrf_token()); ?>">
            
            <div style="display:grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap:24px;">
                <div>
                    <label style="display:block; font-weight:600; font-size:0.95rem; color:#475569; margin-bottom:6px;">Título da página</label>
                    <input type="text" name="title" value="<?php echo h($statusPage['title'] ?? ('Status de ' . ($user['name'] ?? ''))); ?>" style="width:100%; border:1px solid #cbd5e1; border-radius:10px; padding:12px 14px; font-size:0.95rem; font-weight:500;" placeholder="Ex: Sistemas ACME Inc.">
                </div>
                <div>
                    <label style="display:block; font-weight:600; font-size:0.95rem; color:#475569; margin-bottom:6px;">Subtítulo ou Descrição (opcional)</label>
                    <input type="text" name="description" value="<?php echo h($statusPage['description'] ?? ''); ?>" style="width:100%; border:1px solid #cbd5e1; border-radius:10px; padding:12px 14px; font-size:0.95rem; color:#334155;" placeholder="Acompanhe a disponibilidade dos nossos serviços">
                </div>
            </div>

            <div>
                <label style="display:inline-flex; align-items:center; gap:8px; cursor:pointer; background:#f8fafc; padding:12px 20px; border-radius:10px; border:1px solid #e2e8f0; width:fit-content;">
                    <input type="checkbox" name="active" <?php echo (($statusPage['active'] ?? 1) ? 'checked' : ''); ?> style="width:18px; height:18px; accent-color:#3b82f6; margin:0;">
                    <span style="font-weight:700; color:#0f172a; font-size:0.95rem;">Habilitar Página (Deixar online)</span>
                </label>
                <p style="margin:6px 0 0 4px; color:#94a3b8; font-size:0.9rem;">Se desmarcado, o link exibirá indisponibilidade temporária.</p>
            </div>

            <div>
                <label style="display:block; font-weight:600; font-size:0.95rem; color:#475569; margin-bottom:6px;">Senha de Acesso (opcional)</label>
                <input type="text" name="access_password" value="<?php echo h($statusPage['access_password'] ?? ''); ?>" placeholder="Deixe em branco para acesso público" style="width:100%; max-width:400px; border:1px solid #cbd5e1; border-radius:10px; padding:12px 14px; font-size:0.95rem;">
                <p style="margin:6px 0 0; color:#94a3b8; font-size:0.85rem;">Visitantes precisarão digitar esta senha para ver o status. Deixe vazio para manter público.</p>
            </div>

            <h3 style="margin:16px 0 8px; color:#0f172a; font-size:1.1rem; border-bottom:1px solid #e2e8f0; padding-bottom:12px;">Componentes Exibidos na Status Page</h3>
            <p style="margin:0 0 16px; color:#64748b; font-size:0.95rem;">Marque as instâncias e redes que deseja expor publicamente no monitor. Desmarque serviços privados.</p>

            <div style="display:grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap:16px; background:#f8fafc; padding:24px; border-radius:16px; border:1px solid #e2e8f0;">
                <?php if (empty($userIps)): ?>
                    <p style="color:#94a3b8; grid-column:1/-1; text-align:center; padding:12px 0; margin:0;">Você ainda não tem instâncias cadastradas.</p>
                <?php else: ?>
                    <?php foreach ($userIps as $ipRow): ?>
                        <label style="display:flex; align-items:flex-start; gap:12px; cursor:pointer; background:#fff; padding:16px; border-radius:12px; border:1px solid #cbd5e1; transition:0.2s; box-shadow:0 1px 2px rgba(0,0,0,0.05);" onmouseover="this.style.borderColor='#3b82f6'" onmouseout="this.style.borderColor='#cbd5e1'">
                            <input type="checkbox" name="ips[]" value="<?php echo (int)$ipRow['id']; ?>" <?php echo in_array((int)$ipRow['id'], $pageIps, true) ? 'checked' : ''; ?> style="width:20px; height:20px; accent-color:#3b82f6; margin-top:2px;">
                            <div style="flex:1;">
                                <div style="font-weight:700; color:#1e293b; font-size:1rem; margin-bottom:4px;"><?php echo h($ipRow['label']); ?></div>
                                <div style="display:inline-block; color:#ea580c; background:#fff7ed; border:1.5px solid #fed7aa; font-family:monospace; font-size:0.9rem; font-weight:700; padding:3px 8px; border-radius:6px; word-break:break-all;"><?php echo h($ipRow['host']); ?></div>
                            </div>
                        </label>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>

            <div style="margin-top:24px; display:flex; justify-content:flex-end; border-top:1px solid #e2e8f0; padding-top:24px;">
                <button type="submit" style="padding:14px 40px; font-size:1.1rem; border-radius:12px; font-weight:700;">Salvar e Refletir Publicamente</button>
            </div>
        </form>
    </div>
</div>

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