<?php
// OneLauncher - plans.php
require_once 'includes/auth.php';
require_once 'db.php';

$pageTitle = 'Gestão de Planos e Assinaturas';
$nav = 'plans';
$msg = "";

// Adicionar/Editar Plano
if (isset($_POST['save_plan'])) {
    $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
    $name = $_POST['name'];
    $days = (int)$_POST['duration_days'];
    $price = (float)$_POST['price'];

    if ($id > 0) {
        $stmt = $conn->prepare("UPDATE plans SET name = ?, duration_days = ?, price = ? WHERE id = ?");
        $stmt->bind_param("sidi", $name, $days, $price, $id);
    } else {
        $stmt = $conn->prepare("INSERT INTO plans (name, duration_days, price) VALUES (?, ?, ?)");
        $stmt->bind_param("sid", $name, $days, $price);
    }
    
    if ($stmt->execute()) {
        $msg = "Plano salvo com sucesso!";
    } else {
        $msg = "Erro ao salvar plano.";
    }
}

// Excluir Plano
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $conn->query("DELETE FROM plans WHERE id = $id");
    header("Location: plans.php?msg=deleted");
    exit;
}

if (isset($_GET['msg']) && $_GET['msg'] == 'deleted') $msg = "Plano removido.";

$plans = $conn->query("SELECT * FROM plans ORDER BY price ASC");

include 'includes/head.php';
?>

<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet">

<style>
<style>
    /* DataTables Integração com Novo Tema */
    div.dataTables_wrapper div.dataTables_length select,
    div.dataTables_wrapper div.dataTables_filter input {
        background: rgba(8, 15, 37, 0.4) !important;
        border: 1px solid rgba(255, 255, 255, 0.1) !important;
        color: rgba(255,255,255,0.7) !important;
        border-radius: 8px;
    }
    .table-dark-custom { --bs-table-bg: transparent; --bs-table-color: rgba(255,255,255,0.8); }
    .table-dark-custom th { color: rgba(255,255,255,0.5); font-weight: 600; text-transform: uppercase; font-size: 0.75rem; letter-spacing: 0.5px; border-bottom: 2px solid rgba(255, 255, 255, 0.05); }
    .table-dark-custom td { border-bottom: 1px solid rgba(255, 255, 255, 0.05); vertical-align: middle; }
    .table-dark-custom tbody tr:hover { background: rgba(59, 130, 246, 0.05); }
    
    .page-link { background: rgba(8, 15, 37, 0.4); border-color: rgba(255,255,255,0.1); color: #fff; }
    .page-item.active .page-link { background-color: var(--accent-blue); border-color: var(--accent-blue); }
    
    .modal-content-custom {
        background: #0B1121;
        border: 1px solid rgba(255,255,255,0.1);
        border-radius: 16px;
        box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);
    }
    .form-control-custom {
        background: rgba(255,255,255,0.05); 
        border: 1px solid rgba(255,255,255,0.1); 
        color: #fff; 
        border-radius: 12px;
        padding: 12px;
    }
    .form-control-custom:focus {
        background: rgba(255,255,255,0.08); 
        border-color: var(--accent-blue); 
        box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.15);
        color: #fff;
    }
</style>

<?php 
include 'includes/sidebar.php';
include 'includes/topbar.php';
include 'includes/layout-open.php';
?>

<div class="container-fluid">

        <div class="row align-items-center mb-4">
            <div class="col">
                <h2 class="mb-1"><i class="fa-solid fa-tags me-2"></i> Planos de Assinatura</h2>
                <p class="text-white-50 small mb-0">Gerencie os planos para o Kill Switch do seu App.</p>
            </div>
            <div class="col-auto">
                <button class="btn btn-app-primary py-2 px-4" data-bs-toggle="modal" data-bs-target="#addPlanModal">
                    <i class="fa-solid fa-plus me-2"></i> Adicionar Plano
                </button>
            </div>
        </div>

    <div class="app-card">
        <div class="table-responsive">
            <table class="table table-dark-custom w-100" id="plansTable">
                <thead>
                    <tr>
                        <th>Nome do Plano</th>
                        <th>Duração (Dias)</th>
                        <th>Valor (R$)</th>
                        <th class="text-end">Ações</th>
                    </tr>
                </thead>
                <tbody>
                    <?php while($plan = $plans->fetch_assoc()): ?>
                        <tr>
                            <td class="text-white fw-bold" data-label="Plano"><?php echo $plan['name']; ?></td>
                            <td class="text-white-50" data-label="Duração"><?php echo $plan['duration_days']; ?> dias</td>
                            <td class="text-success fw-bold" data-label="Valor">R$ <?php echo number_format($plan['price'], 2, ',', '.'); ?></td>
                            <td class="text-end" data-label="Ações">
                                <button class="btn btn-sm btn-outline-primary border-opacity-25" data-bs-toggle="modal" data-bs-target="#editModal<?php echo $plan['id']; ?>">
                                    <i class="fa-solid fa-pen"></i>
                                </button>
                                <button type="button" onclick="confirmDelete(<?php echo $plan['id']; ?>)" class="btn btn-sm btn-outline-danger border-opacity-25 ms-1">
                                    <i class="fa-solid fa-trash"></i>
                                </button>
                            </td>
                        </tr>
                    <?php 
                        $plans_list[] = $plan;
                    endwhile; 
                    ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Modais de Edição -->
<?php if (isset($plans_list)): foreach($plans_list as $plan): ?>
    <div class="modal fade" id="editModal<?php echo $plan['id']; ?>" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content modal-content-custom">
                <div class="modal-header border-0 border-bottom border-secondary border-opacity-10 p-4">
                    <h5 class="modal-title fw-bold text-white"><i class="fa-solid fa-tag me-2 text-primary"></i>Editar Plano</h5>
                    <button type="button" class="btn-close btn-close-white opacity-50" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <div class="modal-body p-4">
                        <input type="hidden" name="id" value="<?php echo $plan['id']; ?>">
                        <div class="mb-4">
                            <label class="form-label text-white-50 fw-bold small text-uppercase">Nome do Plano</label>
                            <input type="text" name="name" class="form-control form-control-custom" value="<?php echo $plan['name']; ?>" required>
                        </div>
                        <div class="mb-4">
                            <label class="form-label text-white-50 fw-bold small text-uppercase">Duração em Dias</label>
                            <input type="number" name="duration_days" class="form-control form-control-custom" value="<?php echo $plan['duration_days']; ?>" required>
                        </div>
                        <div class="mb-4">
                            <label class="form-label text-white-50 fw-bold small text-uppercase">Preço (R$)</label>
                            <input type="number" step="0.01" name="price" class="form-control form-control-custom" value="<?php echo $plan['price']; ?>" required>
                        </div>
                    </div>
                    <div class="modal-footer border-0 p-4 pt-0">
                        <button type="submit" name="save_plan" class="btn btn-app-primary w-100 py-3">Salvar Alterações</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
<?php endforeach; endif; ?>

<!-- Modal Adicionar -->
<div class="modal fade" id="addPlanModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content modal-content-custom">
            <div class="modal-header border-0 border-bottom border-secondary border-opacity-10 p-4">
                <h5 class="modal-title fw-bold text-white"><i class="fa-solid fa-plus-circle me-2 text-success"></i>Novo Plano</h5>
                <button type="button" class="btn-close btn-close-white opacity-50" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body p-4">
                    <div class="mb-4">
                        <label class="form-label text-white-50 fw-bold small text-uppercase">Nome do Plano</label>
                        <input type="text" name="name" class="form-control form-control-custom" placeholder="Ex: Mensal VIP" required>
                    </div>
                    <div class="mb-4">
                        <label class="form-label text-white-50 fw-bold small text-uppercase">Duração em Dias</label>
                        <input type="number" name="duration_days" class="form-control form-control-custom" placeholder="Ex: 30" required>
                    </div>
                    <div class="mb-4">
                        <label class="form-label text-white-50 fw-bold small text-uppercase">Preço (R$)</label>
                        <input type="number" step="0.01" name="price" class="form-control form-control-custom" placeholder="Ex: 29.90" required>
                    </div>
                </div>
                <div class="modal-footer border-0 p-4 pt-0">
                    <button type="submit" name="save_plan" class="btn btn-app-primary w-100 py-3">Criar Plano</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
    $(document).ready(function() {
        $('#plansTable').DataTable({
            language: { url: '//cdn.datatables.net/plug-ins/1.13.6/i18n/pt-BR.json' },
            pageLength: 10,
            ordering: true
        });
    });

    function confirmDelete(id) {
        Swal.fire({
            title: 'Tem certeza?',
            text: "Esta ação não pode ser revertida!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#0066FF',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'Sim, excluir!',
            cancelButtonText: 'Cancelar',
            background: '#0B1121',
            color: '#fff'
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = 'plans.php?delete=' + id;
            }
        });
    }
</script>

<?php
include 'includes/layout-close.php';
include 'includes/footer.php';
?>
