<?php
// p2p_manager.php - Gerenciador de Clientes P2P
session_start();
require_once 'includes/db.php';

// Segurança
if (!isset($_SESSION['logged_in_fxtream'])) { header('Location: index.php'); exit; }

$admin_id = $_SESSION['user_id'];

// Busca Planos (se tabela existir, senão usa padrão)
try {
    $plans = $pdo->query("SELECT * FROM plans ORDER BY duration_days ASC")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { 
    $plans = [
        ['id'=>1, 'name'=>'Mensal', 'duration_days'=>30],
        ['id'=>2, 'name'=>'Trimestral', 'duration_days'=>90]
    ]; 
}

// Busca Clientes P2P
$stmt = $pdo->prepare("SELECT * FROM users WHERE is_p2p = 1 AND revendedor_id = ? ORDER BY id DESC");
$stmt->execute([$admin_id]);
$p2p_users = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Clientes P2P</title>
    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/hamburgers/1.1.3/hamburgers.min.css">
    
    <style>
        body { background-color: #121212; color: #e0e0e0; font-family: 'Segoe UI', sans-serif; }
        .card { background-color: #1e1e1e; border: 1px solid #333; }
        .table { color: #bfbfbf; margin-bottom: 0; }
        .table td, .table th { vertical-align: middle; border-top: 1px solid #333; }
        .table-hover tbody tr:hover { background-color: #2c2c2c; }
        .btn-p2p { background: linear-gradient(45deg, #6a11cb, #2575fc); color: white; border: none; }
        .btn-p2p:hover { color: #fff; filter: brightness(110%); }
        .modal-content { background-color: #1f1f1f; border: 1px solid #333; color: #fff; }
        .close { color: #fff; }
        .form-control, .custom-select { background-color: #2c2c2c; border: 1px solid #444; color: #fff; }
        
        /* Menu Responsivo */
        @media (min-width: 992px) {
            #sidebar { width: 240px; position: fixed; top: 0; left: 0; height: 100vh; z-index: 1000; overflow-y: auto; }
            .container-main { margin-left: 240px; width: calc(100% - 240px); padding: 20px; }
            .hamburger { display: none !important; }
        }
        @media (max-width: 991px) {
            #sidebar { position: fixed; top: 0; left: -260px; width: 250px; height: 100vh; z-index: 9999; transition: all 0.3s ease; box-shadow: 2px 0 10px rgba(0,0,0,0.5); }
            #sidebar.active { left: 0; }
            .container-main { margin-left: 0; width: 100%; padding: 15px; }
            .overlay-menu { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 9998; }
            .overlay-menu.active { display: block; }
        }
    </style>
</head>
<body>

<?php include 'includes/sidebar.php'; ?>
<div class="overlay-menu" id="overlayMenu"></div>

<div class="container-main">
    
    <div class="d-lg-none d-flex justify-content-between align-items-center mb-3 bg-dark p-2 rounded shadow-sm">
        <button class="hamburger hamburger--slider" type="button" id="btnToggleMenu">
            <span class="hamburger-box"><span class="hamburger-inner"></span></span>
        </button>
        <span class="font-weight-bold text-white">Clientes P2P</span>
        <div></div>
    </div>

    <div class="d-flex justify-content-between align-items-center mb-4">
        <h3 class="mb-0 d-none d-lg-block"><i class="fa fa-share-alt text-primary"></i> Clientes P2P</h3>
        <div>
            <button class="btn btn-warning font-weight-bold mr-2 shadow-sm" onclick="openTestModal()">
                <i class="fa fa-clock"></i> Teste Rápido
            </button>
            <button class="btn btn-p2p font-weight-bold shadow-sm" onclick="openCreateModal()">
                <i class="fa fa-plus-circle"></i> Novo Código
            </button>
        </div>
    </div>

    <?php if(isset($_SESSION['mensagem'])): ?>
        <div class="alert <?php echo ($_SESSION['msg_type'] == 'alert-success') ? 'alert-success' : 'alert-danger'; ?> alert-dismissible fade show shadow-sm">
            <?php echo $_SESSION['mensagem']; unset($_SESSION['mensagem']); ?>
            <button type="button" class="close" data-dismiss="alert">×</button>
        </div>
    <?php endif; ?>

    <div class="card shadow-sm">
        <div class="table-responsive">
            <table class="table table-hover mb-0 align-middle">
                <thead class="bg-secondary text-white">
                    <tr>
                        <th class="pl-3">Código</th>
                        <th>Cliente</th>
                        <th>Vencimento</th>
                        <th>Status</th>
                        <th class="text-right pr-3">Ações</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(count($p2p_users) > 0): ?>
                        <?php foreach($p2p_users as $u): 
                            $date_str = $u['expire_date'] ? date('d/m/Y H:i', strtotime($u['expire_date'])) : '--';
                            $is_expired = (strtotime($u['expire_date']) < time());
                            $status = $is_expired ? '<span class="badge badge-danger">Vencido</span>' : '<span class="badge badge-success">Ativo</span>';
                        ?>
                        <tr>
                            <td class="pl-3">
                                <span class="font-weight-bold text-info" style="font-size: 1.1em;"><?php echo $u['username']; ?></span>
                            </td>
                            <td>
                                <div class="font-weight-bold"><?php echo $u['username_display'] ?? 'Sem nome'; ?></div>
                                <?php if(!empty($u['whatsapp'])): ?>
                                    <small class="text-muted"><i class="fab fa-whatsapp"></i> <?php echo $u['whatsapp']; ?></small>
                                <?php endif; ?>
                            </td>
                            <td><?php echo $date_str; ?></td>
                            <td><?php echo $status; ?></td>
                            <td class="text-right pr-3">
                                <button class="btn btn-sm btn-success mr-1" onclick="shareP2P('<?php echo $u['username']; ?>', '<?php echo $date_str; ?>')" title="Compartilhar"><i class="fab fa-whatsapp"></i></button>
                                <button class="btn btn-sm btn-primary mr-1" onclick="openRenewModal(<?php echo $u['id']; ?>, '<?php echo $u['username_display']; ?>')" title="Renovar"><i class="fa fa-sync-alt"></i></button>
                                <a href="api/p2p_api.php?action=delete&id=<?php echo $u['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('Excluir este código?')" title="Excluir"><i class="fa fa-trash"></i></a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr><td colspan="5" class="text-center py-5 text-muted">Nenhum código P2P encontrado.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="modalCreate" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-primary border-0">
                <h5 class="modal-title font-weight-bold">Novo Código P2P</h5>
                <button class="close text-white" data-dismiss="modal">×</button>
            </div>
            <div class="modal-body">
                <form action="api/p2p_api.php" method="POST">
                    <input type="hidden" name="action" value="create">
                    
                    <div class="form-group">
                        <label>Nome do Cliente</label>
                        <input type="text" name="name" class="form-control" required placeholder="Ex: João Silva">
                    </div>
                    
                    <div class="form-group">
                        <label>WhatsApp (Opcional)</label>
                        <input type="text" name="whatsapp" class="form-control" placeholder="5511999999999">
                    </div>
                    
                    <div class="form-group">
                        <label>Plano</label>
                        <select name="plano_info" class="form-control">
                            <?php foreach($plans as $p): ?>
                                <option value="<?php echo $p['id'].'|'.$p['duration_days']; ?>">
                                    <?php echo $p['name']; ?> - <?php echo $p['duration_days']; ?> dias
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <button class="btn btn-primary btn-block font-weight-bold py-2">GERAR CÓDIGO</button>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalRenew" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-info border-0">
                <h5 class="modal-title font-weight-bold">Renovar Código</h5>
                <button class="close text-white" data-dismiss="modal">×</button>
            </div>
            <div class="modal-body">
                <form action="api/p2p_api.php" method="POST">
                    <input type="hidden" name="action" value="renew">
                    <input type="hidden" name="id_cliente" id="renewId">
                    
                    <p class="text-center mb-4" style="font-size: 1.1rem;">Renovando: <b id="renewName" class="text-info"></b></p>
                    
                    <div class="form-group">
                        <label>Escolha o Plano</label>
                        <select name="plano_info" class="form-control">
                            <?php foreach($plans as $p): ?>
                                <option value="<?php echo $p['id'].'|'.$p['duration_days']; ?>">
                                    <?php echo $p['name']; ?> - <?php echo $p['duration_days']; ?> dias
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <button class="btn btn-info btn-block font-weight-bold py-2">CONFIRMAR RENOVAÇÃO</button>
                </form>
            </div>
        </div>
    </div>
</div>

<?php if(isset($_SESSION['show_p2p_modal_message'])): ?>
<div class="modal fade" id="msgModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-success border-0">
                <h5 class="modal-title font-weight-bold"><?php echo $_SESSION['show_p2p_modal_title']; ?></h5>
                <button class="close text-white" data-dismiss="modal">×</button>
            </div>
            <div class="modal-body text-center">
                <textarea id="msgArea" class="form-control bg-dark text-white mb-3" rows="6" readonly style="resize:none;"><?php echo $_SESSION['show_p2p_modal_message']; ?></textarea>
                
                <div class="row">
                    <div class="col-6">
                        <button onclick="copyMsg()" class="btn btn-primary btn-block font-weight-bold py-2">
                            <i class="fa fa-copy"></i> COPIAR
                        </button>
                    </div>
                    <div class="col-6">
                        <a href="https://api.whatsapp.com/send?text=<?php echo urlencode($_SESSION['show_p2p_modal_message']); ?>" target="_blank" class="btn btn-success btn-block font-weight-bold py-2">
                            <i class="fab fa-whatsapp"></i> ENVIAR
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>

<script>
    // Menu Mobile
    $('#btnToggleMenu, #overlayMenu').click(function() {
        $('#sidebar').toggleClass('active');
        $('#overlayMenu').toggleClass('active');
        $('#btnToggleMenu').toggleClass('is-active');
    });

    function openCreateModal() { $('#modalCreate').modal('show'); }
    
    function openTestModal() {
        if(confirm('Gerar um teste rápido de 4 horas?')) {
            var form = $('<form action="api/p2p_api.php" method="post"><input type="hidden" name="action" value="test"></form>');
            $('body').append(form);
            form.submit();
        }
    }

    function openRenewModal(id, name) {
        $('#renewId').val(id);
        $('#renewName').text(name);
        $('#modalRenew').modal('show');
    }

    function shareP2P(code, date) {
        let linkLoja = "https://kofficepanel.tvsbr.top/loja";
        let msg = `✅ *SEU CÓDIGO P2P* \n\n🔑 Código: *${code}* \n📅 Vence em: ${date} \n\n📥 *Baixe o App:* ${linkLoja}`;
        window.open(`https://api.whatsapp.com/send?text=${encodeURIComponent(msg)}`, '_blank');
    }

    function copyMsg() {
        var copyText = document.getElementById("msgArea");
        copyText.select();
        copyText.setSelectionRange(0, 99999); /* Para mobile */
        document.execCommand("copy");
        toastr.success("Mensagem copiada!");
    }

    // Auto-show message modal
    <?php if(isset($_SESSION['show_p2p_modal_message'])): ?>
        $('#msgModal').modal('show');
    <?php 
        unset($_SESSION['show_p2p_modal_message']); 
        unset($_SESSION['show_p2p_modal_title']);
    endif; ?>
</script>

</body>
</html>
