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

$errors = [];
$editingPlan = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? 'create_plan';

    if (in_array($action, ['create_plan', 'update_plan'], true)) {
        $name = trim($_POST['name'] ?? '');
        $max_ips = (int)($_POST['max_ips'] ?? 0);
        $min_interval_seconds = (int)($_POST['min_interval_seconds'] ?? 0);
        $price = (float)($_POST['price'] ?? 0);
        $allow_email = isset($_POST['allow_email']) ? 1 : 0;
        $allow_webhook = isset($_POST['allow_webhook']) ? 1 : 0;
        $allow_sms = isset($_POST['allow_sms']) ? 1 : 0;
        $active = isset($_POST['active']) ? 1 : 0;

        if (!$name || $max_ips <= 0 || $min_interval_seconds <= 0) {
            $errors[] = 'Preencha os campos obrigatórios.';
        }

        if ($action === 'update_plan') {
            $planId = (int)($_POST['plan_id'] ?? 0);
            $planStmt = $pdo->prepare("SELECT * FROM plans WHERE id = ? LIMIT 1");
            $planStmt->execute([$planId]);
            $editingPlan = $planStmt->fetch();
            if (!$editingPlan) {
                $errors[] = 'Plano não encontrado.';
            }
        }

        if (!$errors) {
            if ($action === 'create_plan') {
                $stmt = $pdo->prepare("
                    INSERT INTO plans (name, max_ips, min_interval_seconds, allow_email, allow_webhook, allow_sms, price, active)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                ");
                $stmt->execute([$name, $max_ips, $min_interval_seconds, $allow_email, $allow_webhook, $allow_sms, $price, $active]);
            } else {
                $stmt = $pdo->prepare("
                    UPDATE plans
                    SET name = ?, max_ips = ?, min_interval_seconds = ?, allow_email = ?, allow_webhook = ?, allow_sms = ?, price = ?, active = ?
                    WHERE id = ?
                ");
                $stmt->execute([$name, $max_ips, $min_interval_seconds, $allow_email, $allow_webhook, $allow_sms, $price, $active, $editingPlan['id']]);
            }
            redirect("index.php?page=admin_plans");
        } else {
            $editingPlan = $editingPlan ?: [
                'id' => $action === 'create_plan' ? null : (int)($_POST['plan_id'] ?? 0),
                'name' => $name,
                'max_ips' => $max_ips,
                'min_interval_seconds' => $min_interval_seconds,
                'allow_email' => $allow_email,
                'allow_webhook' => $allow_webhook,
                'allow_sms' => $allow_sms,
                'price' => $price,
                'active' => $active,
            ];
        }
    } elseif ($action === 'delete_plan' && isset($_POST['plan_id'])) {
        $planId = (int)$_POST['plan_id'];
        $count = $pdo->prepare("SELECT COUNT(*) FROM subscriptions WHERE plan_id = ?");
        $count->execute([$planId]);
        if ($count->fetchColumn() > 0) {
            $errors[] = 'Não é possível excluir um plano com assinaturas vinculadas.';
        } else {
            $pdo->prepare("DELETE FROM plans WHERE id = ?")->execute([$planId]);
            redirect("index.php?page=admin_plans");
        }
    }
}

if (isset($_GET['edit']) && ctype_digit($_GET['edit'])) {
    $stmt = $pdo->prepare("SELECT * FROM plans WHERE id = ? LIMIT 1");
    $stmt->execute([(int)$_GET['edit']]);
    $editingPlan = $stmt->fetch();
}

if (isset($_GET['toggle']) && ctype_digit($_GET['toggle'])) {
    $id = (int)$_GET['toggle'];
    $pdo->prepare("UPDATE plans SET active = 1-active WHERE id = ?")->execute([$id]);
    redirect("index.php?page=admin_plans");
}

$plans = $pdo->query("SELECT * FROM plans ORDER BY id ASC")->fetchAll();
?>

<div class="card">
    <h2><?php echo $editingPlan ? 'Editar plano' : 'Novo plano'; ?></h2>
    <?php if (!empty($errors)): ?>
        <div class="card" style="background:#fee2e2;color:#b91c1c;">
            <?php foreach ($errors as $error): ?>
                <p><?php echo h($error); ?></p>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
    <form method="post">
        <input type="hidden" name="action" value="<?php echo $editingPlan ? 'update_plan' : 'create_plan'; ?>">
        <?php if ($editingPlan): ?>
            <input type="hidden" name="plan_id" value="<?php echo (int)$editingPlan['id']; ?>">
        <?php endif; ?>

        <label>Nome</label>
        <input type="text" name="name" value="<?php echo h($editingPlan['name'] ?? ''); ?>" required>

        <label>Máx. IPs</label>
        <input type="number" name="max_ips" min="1" value="<?php echo h($editingPlan['max_ips'] ?? ''); ?>" required>

        <label>Intervalo mínimo (segundos)</label>
        <input type="number" name="min_interval_seconds" min="10" value="<?php echo h($editingPlan['min_interval_seconds'] ?? ''); ?>" required>

        <label>Preço (R$)</label>
        <input type="number" step="0.01" name="price" value="<?php echo h($editingPlan['price'] ?? ''); ?>" required>

        <label><input type="checkbox" name="allow_email" <?php echo (($editingPlan['allow_email'] ?? 1) ? 'checked' : ''); ?>> E-mail</label><br>
        <label><input type="checkbox" name="allow_webhook" <?php echo (($editingPlan['allow_webhook'] ?? 0) ? 'checked' : ''); ?>> Webhook</label><br>
        <label><input type="checkbox" name="allow_sms" <?php echo (($editingPlan['allow_sms'] ?? 0) ? 'checked' : ''); ?>> SMS</label><br>
        <label><input type="checkbox" name="active" <?php echo (($editingPlan['active'] ?? 1) ? 'checked' : ''); ?>> Plano ativo</label><br><br>

        <button type="submit"><?php echo $editingPlan ? 'Salvar alterações' : 'Criar plano'; ?></button>
        <?php if ($editingPlan): ?>
            <a class="ghost-button" href="index.php?page=admin_plans" style="margin-left:8px;">Cancelar</a>
        <?php endif; ?>
    </form>

    <h3>Planos existentes</h3>
    <table>
        <thead>
        <tr>
            <th>Nome</th>
            <th>Máx IPs</th>
            <th>Min intervalo</th>
            <th>Preço</th>
            <th>Alertas</th>
            <th>Ativo</th>
            <th>Ações</th>
        </tr>
        </thead>
        <tbody>
        <?php foreach ($plans as $p): ?>
            <tr>
                <td><?php echo h($p['name']); ?></td>
                <td><?php echo (int)$p['max_ips']; ?></td>
                <td><?php echo (int)$p['min_interval_seconds']; ?>s</td>
                <td>R$ <?php echo number_format($p['price'], 2, ',', '.'); ?></td>
                <td>
                    <span class="badge">E-mail: <?php echo $p['allow_email'] ? 'Sim' : 'Não'; ?></span>
                    <span class="badge">Webhook: <?php echo $p['allow_webhook'] ? 'Sim' : 'Não'; ?></span>
                    <span class="badge">SMS: <?php echo $p['allow_sms'] ? 'Sim' : 'Não'; ?></span>
                </td>
                <td><?php echo $p['active'] ? 'Sim' : 'Não'; ?></td>
                <td class="ip-card-actions">
                    <a href="index.php?page=admin_plans&edit=<?php echo $p['id']; ?>">Editar</a>
                    <a href="index.php?page=admin_plans&toggle=<?php echo $p['id']; ?>">
                        <?php echo $p['active'] ? 'Desativar' : 'Ativar'; ?>
                    </a>
                    <form method="post" style="display:inline;" onsubmit="return confirm('Excluir este plano?');">
                        <input type="hidden" name="action" value="delete_plan">
                        <input type="hidden" name="plan_id" value="<?php echo $p['id']; ?>">
                        <button type="submit" style="background:#dc2626;">Excluir</button>
                    </form>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>

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