<?php
// admin/config_mp.php
ini_set('display_errors', 1);
error_reporting(E_ALL);

session_start();
require '../includes/conexao.php';

// SEGURANÇA
if (!isset($_SESSION['account_id'])) { header("Location: ../login.php"); exit; }
$stmt = $pdo->prepare("SELECT page_access FROM accounts WHERE id = ?");
$stmt->execute([$_SESSION['account_id']]);
$acc = $stmt->fetch();
if (!$acc || $acc['page_access'] < 3) die("Acesso Negado.");

$page_title = "Configuração de Doações";

if(file_exists('../includes/admin_header.php')) include '../includes/admin_header.php';
else include '../includes/header.php';

$msg = '';

// --- HELPER FUNCTION (Se não estiver no functions.php) ---
if (!function_exists('get_mp_config')) {
    function get_mp_config($pdo) {
        $stmt = $pdo->query("SELECT * FROM mp_config WHERE id = 1");
        $config = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$config) return ['points_per_real' => 1.00, 'bonus_min_amount' => 35.00, 'bonus_percentage' => 10, 'public_key' => '', 'access_token' => ''];
        return $config;
    }
}

// --- 1. SALVAR GERAL ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save_general'])) {
    $pk = trim($_POST['public_key']);
    $tk = trim($_POST['access_token']);
    $pts = (float)$_POST['points_per_real']; 
    $min = (float)$_POST['bonus_min_amount'];
    $perc = (int)$_POST['bonus_percentage'];

    if ($pts < 0.01) $pts = 1.00;

    try {
        $stmt = $pdo->prepare("INSERT INTO mp_config (id, public_key, access_token, points_per_real, bonus_min_amount, bonus_percentage) VALUES (1, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE public_key=VALUES(public_key), access_token=VALUES(access_token), points_per_real=VALUES(points_per_real), bonus_min_amount=VALUES(bonus_min_amount), bonus_percentage=VALUES(bonus_percentage)");
        $stmt->execute([$pk, $tk, $pts, $min, $perc]);
        $msg = '<div class="alert alert-success shadow-sm border-0"><i class="fas fa-check-circle me-2"></i> Configurações salvas!</div>';
    } catch (PDOException $e) {
        $msg = '<div class="alert alert-danger shadow-sm border-0">Erro: ' . $e->getMessage() . '</div>';
    }
}

// --- 2. SALVAR OFERTAS ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action_offer'])) {
    $id = (int)($_POST['offer_id'] ?? 0);
    $name = trim($_POST['name']);
    $pts = (int)$_POST['points'];
    $val = (float)$_POST['amount'];
    $promo = isset($_POST['is_promo']) ? 1 : 0;
    $prio = (int)$_POST['priority'];

    try {
        if ($_POST['action_offer'] == 'add') {
            $pdo->prepare("INSERT INTO mp_offers (name, points, amount, is_promo, priority) VALUES (?, ?, ?, ?, ?)")->execute([$name, $pts, $val, $promo, $prio]);
            $msg = '<div class="alert alert-success shadow-sm border-0">Oferta adicionada!</div>';
        } elseif ($_POST['action_offer'] == 'edit') {
            $pdo->prepare("UPDATE mp_offers SET name=?, points=?, amount=?, is_promo=?, priority=? WHERE id=?")->execute([$name, $pts, $val, $promo, $prio, $id]);
            $msg = '<div class="alert alert-info shadow-sm border-0">Oferta atualizada!</div>';
        } elseif ($_POST['action_offer'] == 'delete') {
            $pdo->prepare("DELETE FROM mp_offers WHERE id=?")->execute([$id]);
            $msg = '<div class="alert alert-warning shadow-sm border-0">Oferta removida!</div>';
        }
    } catch (Exception $e) { $msg = '<div class="alert alert-danger">Erro: '.$e->getMessage().'</div>'; }
}

$config = get_mp_config($pdo);
$offers = $pdo->query("SELECT * FROM mp_offers ORDER BY priority ASC, amount ASC")->fetchAll(PDO::FETCH_ASSOC);
$editOffer = isset($_GET['edit_offer']) ? $pdo->query("SELECT * FROM mp_offers WHERE id = ".(int)$_GET['edit_offer'])->fetch(PDO::FETCH_ASSOC) : null;
?>

<style>
    /* Admin Dark Theme */
    body { background-color: #0f172a; color: #f8fafc; font-family: 'Poppins', sans-serif; }
    .card { background-color: #1e293b; border: 1px solid rgba(255,255,255,0.1); color: #fff; border-radius: 12px; }
    .nav-tabs .nav-link { color: #94a3b8; border: none; font-weight: 600; }
    .nav-tabs .nav-link.active { background-color: #1e293b; color: #3b82f6; border-bottom: 3px solid #3b82f6; }
    .form-control { background-color: #0f172a; border: 1px solid rgba(255,255,255,0.2); color: #fff; }
    .form-control:focus { background-color: #0f172a; color: #fff; border-color: #3b82f6; box-shadow: 0 0 0 0.25rem rgba(59, 130, 246, 0.25); }
    .form-label { color: #cbd5e1; font-weight: 600; font-size: 0.85rem; }
    .form-text { color: rgba(255,255,255,0.5); }
    .table { color: #cbd5e1; }
    .table tbody tr:hover { background-color: rgba(255,255,255,0.02); color: #fff; }
    .table thead th { background-color: #0f172a; border-bottom: 2px solid #334155; color: #94a3b8; font-size: 0.8rem; text-transform: uppercase; }
</style>

<div class="container my-5">
    
    <div class="d-flex justify-content-between align-items-center mb-4 border-bottom border-secondary pb-3">
        <div>
            <h2 class="fw-bold text-white mb-0"><i class="fas fa-donate text-success me-2"></i>Configuração de Doação</h2>
            <p class="text-white-50 m-0">Mercado Pago e Promoções.</p>
        </div>
    </div>

    <?php echo $msg; ?>

    <ul class="nav nav-tabs mb-4 border-secondary" id="configTabs" role="tablist">
        <li class="nav-item"><button class="nav-link active" id="general-tab" data-bs-toggle="tab" data-bs-target="#general" type="button"><i class="fas fa-sliders-h me-2"></i> Geral & Bônus</button></li>
        <li class="nav-item"><button class="nav-link" id="offers-tab" data-bs-toggle="tab" data-bs-target="#offers" type="button"><i class="fas fa-list me-2"></i> Ofertas Fixas</button></li>
    </ul>

    <div class="tab-content">
        
        <div class="tab-pane fade show active" id="general">
            <div class="row g-4">
                <div class="col-lg-6">
                    <div class="card shadow h-100">
                        <div class="card-header bg-dark text-white fw-bold"><i class="fas fa-key text-warning me-2"></i> Credenciais & Taxas</div>
                        <div class="card-body">
                            <form method="POST">
                                <input type="hidden" name="save_general" value="1">
                                
                                <h6 class="text-primary fw-bold mb-3">Mercado Pago</h6>
                                <div class="mb-3">
                                    <label class="form-label">Public Key</label>
                                    <input type="text" name="public_key" class="form-control" value="<?php echo htmlspecialchars($config['public_key']); ?>" required>
                                </div>
                                <div class="mb-4">
                                    <label class="form-label">Access Token</label>
                                    <input type="text" name="access_token" class="form-control" value="<?php echo htmlspecialchars($config['access_token']); ?>" required>
                                </div>

                                <h6 class="text-warning fw-bold mb-3 border-top border-secondary pt-3">Economia</h6>
                                <div class="mb-3">
                                    <label class="form-label">Pontos por R$ 1,00</label>
                                    <div class="input-group">
                                        <span class="input-group-text bg-dark text-white border-secondary">1x</span>
                                        <input type="number" step="0.01" name="points_per_real" class="form-control" value="<?php echo $config['points_per_real']; ?>" required>
                                    </div>
                                    <div class="form-text">Ex: 1.00 = 1 Ponto por Real. 2.00 = 2 Pontos por Real.</div>
                                </div>

                                <div class="row">
                                    <div class="col-6">
                                        <label class="form-label">Mínimo para Bônus (R$)</label>
                                        <input type="number" step="0.01" name="bonus_min_amount" class="form-control" value="<?php echo $config['bonus_min_amount']; ?>">
                                    </div>
                                    <div class="col-6">
                                        <label class="form-label">% Bônus</label>
                                        <input type="number" name="bonus_percentage" class="form-control" value="<?php echo $config['bonus_percentage']; ?>">
                                    </div>
                                </div>

                                <button type="submit" class="btn btn-primary w-100 fw-bold mt-4"><i class="fas fa-save me-2"></i> Salvar Configurações</button>
                            </form>
                        </div>
                    </div>
                </div>

                <div class="col-lg-6">
                    <div class="card shadow border-success h-100">
                        <div class="card-header bg-success text-white fw-bold"><i class="fas fa-calculator me-2"></i> Simulação</div>
                        <div class="card-body">
                            <p class="text-white-50">Exemplo de cálculo baseado nas configurações atuais para uma doação de R$ 50,00.</p>
                            
                            <?php 
                            $simVal = 50.00;
                            $base = $simVal * $config['points_per_real'];
                            $hasBonus = ($simVal >= $config['bonus_min_amount']);
                            $bonus = $hasBonus ? round($base * ($config['bonus_percentage']/100)) : 0;
                            ?>

                            <ul class="list-group list-group-flush bg-transparent">
                                <li class="list-group-item d-flex justify-content-between">
                                    <span>Valor Doado:</span> <span class="text-white fw-bold">R$ <?php echo number_format($simVal, 2, ',', '.'); ?></span>
                                </li>
                                <li class="list-group-item d-flex justify-content-between">
                                    <span>Pontos Base (<?php echo $config['points_per_real']; ?>x):</span> <span class="text-info"><?php echo $base; ?></span>
                                </li>
                                <li class="list-group-item d-flex justify-content-between">
                                    <span>Bônus (<?php echo $hasBonus ? $config['bonus_percentage'].'%' : '0%'; ?>):</span> <span class="text-success">+<?php echo $bonus; ?></span>
                                </li>
                                <li class="list-group-item d-flex justify-content-between bg-dark rounded mt-2 border border-success">
                                    <span class="text-success fw-bold">TOTAL RECEBIDO:</span> <span class="text-warning fw-bold fs-5"><?php echo $base + $bonus; ?> Pts</span>
                                </li>
                            </ul>
                            
                            <div class="mt-4 p-3 bg-dark rounded border border-secondary">
                                <small class="text-white-50 d-block mb-1">URL de Notificação (Webhook):</small>
                                <code class="text-info user-select-all">https://seusite.com/api/webhook_mp.php</code>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="tab-pane fade" id="offers">
            <div class="row g-4">
                <div class="col-lg-4">
                    <div class="card shadow border-top border-4 <?php echo $editOffer ? 'border-warning' : 'border-info'; ?>">
                        <div class="card-header bg-transparent text-white fw-bold py-3">
                            <?php echo $editOffer ? 'Editando Oferta' : 'Nova Oferta Fixa'; ?>
                        </div>
                        <div class="card-body">
                            <form method="POST">
                                <input type="hidden" name="action_offer" value="<?php echo $editOffer ? 'edit' : 'add'; ?>">
                                <?php if($editOffer): ?><input type="hidden" name="offer_id" value="<?php echo $editOffer['id']; ?>"><?php endif; ?>

                                <div class="mb-3">
                                    <label class="form-label">Nome (Ex: Pacote Iniciante)</label>
                                    <input type="text" name="name" class="form-control" required value="<?php echo $editOffer['name'] ?? ''; ?>">
                                </div>
                                <div class="row g-2 mb-3">
                                    <div class="col-6">
                                        <label class="form-label">Pontos</label>
                                        <input type="number" name="points" class="form-control" required value="<?php echo $editOffer['points'] ?? ''; ?>">
                                    </div>
                                    <div class="col-6">
                                        <label class="form-label">Valor R$</label>
                                        <input type="number" step="0.01" name="amount" class="form-control" required value="<?php echo $editOffer['amount'] ?? ''; ?>">
                                    </div>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Prioridade (Ordem)</label>
                                    <input type="number" name="priority" class="form-control" value="<?php echo $editOffer['priority'] ?? 100; ?>">
                                </div>
                                <div class="form-check mb-3">
                                    <input class="form-check-input" type="checkbox" name="is_promo" id="promo" <?php echo ($editOffer && $editOffer['is_promo']) ? 'checked' : ''; ?>>
                                    <label class="form-check-label text-warning fw-bold" for="promo">Destaque Visual</label>
                                </div>
                                
                                <button class="btn w-100 fw-bold <?php echo $editOffer ? 'btn-warning text-dark' : 'btn-info text-white'; ?>">
                                    <?php echo $editOffer ? 'Salvar' : 'Adicionar'; ?>
                                </button>
                                <?php if($editOffer): ?>
                                    <a href="config_mp.php?tab=offers" class="btn btn-outline-secondary w-100 mt-2 btn-sm">Cancelar</a>
                                <?php endif; ?>
                            </form>
                        </div>
                    </div>
                </div>

                <div class="col-lg-8">
                    <div class="card shadow">
                        <div class="card-header bg-dark text-white fw-bold">Ofertas Ativas</div>
                        <div class="table-responsive">
                            <table class="table table-hover align-middle mb-0">
                                <thead>
                                    <tr>
                                        <th>#</th>
                                        <th>Nome</th>
                                        <th>Pts</th>
                                        <th>Valor</th>
                                        <th>Status</th>
                                        <th class="text-end">Ações</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach($offers as $off): ?>
                                    <tr>
                                        <td><?php echo $off['priority']; ?></td>
                                        <td class="fw-bold text-white"><?php echo htmlspecialchars($off['name']); ?></td>
                                        <td class="text-info"><?php echo number_format($off['points'],0,',','.'); ?></td>
                                        <td class="text-success fw-bold">R$ <?php echo number_format($off['amount'],2,',','.'); ?></td>
                                        <td><?php echo $off['is_promo'] ? '<span class="badge bg-warning text-dark">Promo</span>' : '-'; ?></td>
                                        <td class="text-end">
                                            <a href="?edit_offer=<?php echo $off['id']; ?>#offers" class="btn btn-sm btn-primary"><i class="fas fa-edit"></i></a>
                                            <form method="POST" class="d-inline" onsubmit="return confirm('Deletar?');">
                                                <input type="hidden" name="action_offer" value="delete">
                                                <input type="hidden" name="offer_id" value="<?php echo $off['id']; ?>">
                                                <button class="btn btn-sm btn-danger"><i class="fas fa-trash"></i></button>
                                            </form>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    </div>
</div>

<?php if(file_exists('../includes/admin_footer.php')) include '../includes/admin_footer.php'; else include '../includes/footer.php'; ?>