<?php
// ARQUIVO: migrar.php
// VERSÃO: VISUAL IDÊNTICO AO ORIGINAL + SIDEBAR
session_start();
require_once 'includes/db.php'; 

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

$user_id = $_SESSION['user_id'];
$is_admin = (($_SESSION['role'] ?? '') === 'admin');

// --- LÓGICA DE MIGRAÇÃO (MANTIDA INTACTA) ---
$logs = [];
$stats = ['total' => 0, 'success' => 0, 'fail' => 0, 'api_found' => 0];
$show_results = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $show_results = true;
    $type = $_POST['type'];
    $owner_id = $user_id; 

    // === FUNÇÃO DE INSERÇÃO ===
    function insertUser($pdo, $u, $p, $date, $owner) {
        $u = trim($u); $p = trim($p);
        $chk = $pdo->prepare("SELECT id FROM users WHERE username = ?");
        $chk->execute([$u]);
        if($chk->rowCount() > 0) return ['ok'=>false, 'msg'=>'Usuário já existe'];

        try {
            $sql = "INSERT INTO users (username, password, revendedor_id, expire_date, active, is_trial, bouquets, max_connections) 
                    VALUES (?, ?, ?, ?, 1, 0, '[]', 1)";
            $stmt = $pdo->prepare($sql);
            if($stmt->execute([$u, $p, $owner, $date])) return ['ok'=>true, 'msg'=>'Migrado com Sucesso'];
            $err = $stmt->errorInfo();
            return ['ok'=>false, 'msg'=>'Erro SQL: ' . $err[2]];
        } catch(PDOException $e) { return ['ok'=>false, 'msg'=>'Erro: ' . $e->getMessage()]; }
    }

    // === FUNÇÃO API ===
    function checkRemoteApi($host, $u, $p) {
        $urls = [rtrim($host, '/') . "/player_api.php?username=$u&password=$p", rtrim($host, '/') . "/panel_api.php?username=$u&password=$p"];
        foreach($urls as $url) {
            $ch = curl_init();
            curl_setopt_array($ch, [CURLOPT_URL=>$url, CURLOPT_RETURNTRANSFER=>1, CURLOPT_TIMEOUT=>5, CURLOPT_SSL_VERIFYPEER=>0, CURLOPT_FOLLOWLOCATION=>1, CURLOPT_USERAGENT=>'Mozilla/5.0']);
            $res = curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch);
            if($code == 200 && $res) {
                $json = json_decode($res, true);
                if(isset($json['user_info']['exp_date'])) return $json['user_info']['exp_date'];
            }
        }
        return false;
    }

    // PROCESSAMENTO
    if ($type === 'single') {
        $u = $_POST['username']; $p = $_POST['password']; $d = $_POST['expire_date'] . ' 23:59:59';
        $res = insertUser($pdo, $u, $p, $d, $owner_id);
        $logs[] = ['user'=>$u, 'ok'=>$res['ok'], 'msg'=>$res['msg'], 'date'=>$d];
        $stats['total']++; ($res['ok']) ? $stats['success']++ : $stats['fail']++;
    }
    elseif ($type === 'mass') {
        $lines = explode("\n", $_POST['mass_data']);
        foreach($lines as $line) {
            $line = trim($line); if(empty($line)) continue;
            $parts = explode($_POST['separator'], $line);
            if(count($parts) >= 2) {
                $u = trim($parts[0]); $p = trim($parts[1]);
                $date = empty($parts[2]) ? date('Y-m-d H:i:s', strtotime("+30 days")) : date('Y-m-d H:i:s', strtotime(str_replace('/','-',trim($parts[2]))));
                $res = insertUser($pdo, $u, $p, $date, $owner_id);
                $logs[] = ['user'=>$u, 'ok'=>$res['ok'], 'msg'=>$res['msg'], 'date'=>$date];
                $stats['total']++; ($res['ok']) ? $stats['success']++ : $stats['fail']++;
            }
        }
    }
    elseif ($type === 'm3u') {
        $text = $_POST['m3u_data'];
        $def = $_POST['m3u_default_date'] ? $_POST['m3u_default_date'].' 23:59:59' : date('Y-m-d H:i:s', strtotime("+30 days"));
        preg_match_all('/(?:https?:\/\/)([^ \/]+)[\w\/\.]*(?:username=([a-zA-Z0-9]+)&password=([a-zA-Z0-9]+)|\/get\.php\?username=([a-zA-Z0-9]+)&password=([a-zA-Z0-9]+)|([a-zA-Z0-9]+)\/([a-zA-Z0-9]+))/', $text, $matches, PREG_SET_ORDER);
        foreach($matches as $m) {
            $host = $m[1]; $u = $m[2]?:($m[4]?:$m[6]); $p = $m[3]?:($m[5]?:$m[7]);
            if($u && $p) {
                $final = $def; $origin = "Padrão"; $api = checkRemoteApi("http://$host", $u, $p);
                if($api) { $final = is_numeric($api)?date('Y-m-d H:i:s',$api):date('Y-m-d H:i:s',strtotime($api)); $stats['api_found']++; $origin="API"; }
                $res = insertUser($pdo, $u, $p, $final, $owner_id);
                $logs[] = ['user'=>$u, 'ok'=>$res['ok'], 'msg'=>$res['msg']." ($origin)", 'date'=>$final];
                $stats['total']++; ($res['ok']) ? $stats['success']++ : $stats['fail']++;
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> 
    <title>Migração de Clientes</title>
    
    <link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_css/bootstrap/bootstrap.min.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_css/bootstrap/mdb.min.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_css/style.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_fonts/font-awesome/css/all.min.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_css/dark-theme.css">

    <style>
        /* Fundo padrão do seu tema */
        body { background-color: #1a1c23; color: #fff; overflow-x: hidden; }
        
        .card {
            background-color: #232730;
            border: none;
            border-radius: 5px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
        }
        
        /* Inputs e Formulários no estilo do tema */
        .form-control, .form-select { 
            background-color: #1a1c23; 
            border: 1px solid #3a3f4b; 
            color: #fff; 
        }
        .form-control:focus { 
            background-color: #1a1c23; 
            color: #fff; 
            border-color: #007bff; 
        }

        /* Abas de Navegação */
        .nav-pills .nav-link { 
            color: #aaa; 
            background: #1a1c23; 
            border: 1px solid #3a3f4b; 
            margin-right: 10px; 
        }
        .nav-pills .nav-link.active { 
            background: #007bff; 
            color: #fff; 
            border-color: #007bff; 
        }

        /* Cores do Relatório */
        .text-success-soft { color: #00c851 !important; }
        .text-danger-soft { color: #ff3547 !important; }

        /* ============================================================
           LAYOUT RESPONSIVO (SIDEBAR + CONTEÚDO)
           ============================================================ */
        
        /* PC (Telas Grandes) */
        @media (min-width: 992px) {
            #sidebar { 
                display: block !important; 
                width: 240px; 
                position: fixed; top: 0; left: 0; height: 100vh; 
                z-index: 1000; overflow-y: auto; 
            }
            .right-column { 
                margin-left: 240px; 
                width: calc(100% - 240px); 
                padding: 20px;
            }
            .btn-voltar-mobile { display: none; }
        }

        /* CELULAR (Telas Pequenas) */
        @media (max-width: 991px) {
            #sidebar { display: none !important; }
            .navbar { display: none !important; } /* Esconde navbar padrão se houver conflito */
            .right-column { 
                margin-left: 0 !important; 
                width: 100% !important; 
                padding: 10px;
            }
            .btn-voltar-mobile {
                display: inline-block;
                margin-bottom: 15px;
                background: #333;
                color: #fff;
                padding: 8px 15px;
                border-radius: 5px;
                text-decoration: none;
                border: 1px solid #444;
            }
        }
        
        .page-title {
            font-size: 1.5rem;
            color: #fff;
            text-transform: uppercase;
            font-weight: 500;
            margin-bottom: 20px;
            margin-top: 10px;
        }
    </style>
</head>
<body>

<div class="container-fluid p-0">
    <div class="row no-gutters">
        
        <?php include 'includes/sidebar.php'; ?>

        <div class="right-column">

            <nav class="navbar navbar-expand-lg navbar-dark bg-dark border-bottom border-secondary mb-4" style="background-color: #1a1c23 !important;">
                <div class="d-flex align-items-center">
                    <a href="dashboard.php" class="btn-voltar-mobile mr-3"><i class="fas fa-arrow-left"></i></a>
                    <span class="navbar-brand">Migração de Clientes</span>
                </div>
                <a href="dashboard.php" class="btn btn-secondary btn-sm ml-auto d-none d-lg-block"><i class="fa fa-arrow-left"></i> Voltar</a>
            </nav>

            <div class="container-fluid">
                
                <?php if($show_results): ?>
                <div class="row mb-4">
                    <div class="col-6 col-md-3 mb-2"><div class="card p-3 text-center"><h3 class="text-white"><?php echo $stats['total']; ?></h3><small class="text-muted">Total</small></div></div>
                    <div class="col-6 col-md-3 mb-2"><div class="card p-3 text-center"><h3 class="text-info"><?php echo $stats['api_found']; ?></h3><small class="text-muted">Via API</small></div></div>
                    <div class="col-6 col-md-3 mb-2"><div class="card p-3 text-center"><h3 class="text-success-soft"><?php echo $stats['success']; ?></h3><small class="text-muted">Sucesso</small></div></div>
                    <div class="col-6 col-md-3 mb-2"><div class="card p-3 text-center"><h3 class="text-danger-soft"><?php echo $stats['fail']; ?></h3><small class="text-muted">Falhas</small></div></div>
                </div>

                <div class="card mb-4">
                    <div class="card-header">Relatório</div>
                    <div class="card-body p-0" style="max-height: 200px; overflow-y: auto;">
                        <ul class="list-group list-group-flush">
                            <?php foreach($logs as $l): ?>
                            <li class="list-group-item bg-transparent text-white border-secondary">
                                <strong><?php echo htmlspecialchars($l['user']); ?></strong>: 
                                <span class="<?php echo $l['ok']?'text-success-soft':'text-danger-soft'; ?>"><?php echo $l['msg']; ?></span>
                                <span class="float-right small text-muted"><?php echo date('d/m/Y', strtotime($l['date'])); ?></span>
                            </li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                </div>
                <?php endif; ?>

                <ul class="nav nav-pills mb-3" id="migTabs">
                    <li class="nav-item"><a class="nav-link active" data-toggle="pill" href="#single">Individual</a></li>
                    <li class="nav-item"><a class="nav-link" data-toggle="pill" href="#csv">Lista / CSV</a></li>
                    <li class="nav-item"><a class="nav-link" data-toggle="pill" href="#m3u">M3U Inteligente</a></li>
                </ul>

                <div class="tab-content">
                    
                    <div class="tab-pane fade show active" id="single">
                        <div class="card p-3">
                            <form method="POST">
                                <input type="hidden" name="type" value="single">
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label>Usuário</label>
                                        <input type="text" name="username" class="form-control" required>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label>Senha</label>
                                        <input type="text" name="password" class="form-control" required>
                                    </div>
                                </div>
                                <div class="form-group mb-3">
                                    <label>Vencimento</label>
                                    <input type="date" name="expire_date" class="form-control" required value="<?php echo date('Y-m-d', strtotime('+30 days')); ?>">
                                </div>
                                <button type="submit" class="btn btn-primary btn-block">MIGRAR</button>
                            </form>
                        </div>
                    </div>

                    <div class="tab-pane fade" id="csv">
                        <div class="card p-3">
                            <form method="POST">
                                <input type="hidden" name="type" value="mass">
                                <div class="form-group mb-3">
                                    <label>Lista (usuario,senha,data)</label>
                                    <textarea name="mass_data" class="form-control" rows="8" placeholder="usuario,1234,2025-12-31"></textarea>
                                </div>
                                <div class="form-group mb-3">
                                    <label>Separador</label>
                                    <select name="separator" class="form-control">
                                        <option value=",">Vírgula (,)</option>
                                        <option value="|">Pipe (|)</option>
                                    </select>
                                </div>
                                <button type="submit" class="btn btn-info btn-block">PROCESSAR LISTA</button>
                            </form>
                        </div>
                    </div>

                    <div class="tab-pane fade" id="m3u">
                        <div class="card p-3">
                            <form method="POST" onsubmit="$('#btnM3U').text('Processando...').prop('disabled',true)">
                                <input type="hidden" name="type" value="m3u">
                                <div class="alert alert-dark mb-3 small">
                                    O sistema tentará conectar no servidor antigo para pegar a validade exata. Se falhar, usa a data abaixo.
                                </div>
                                <div class="form-group mb-3">
                                    <label>Cole os Links M3U</label>
                                    <textarea name="m3u_data" class="form-control" rows="8" required></textarea>
                                </div>
                                <div class="form-group mb-3">
                                    <label>Data Padrão (Fallback)</label>
                                    <input type="date" name="m3u_default_date" class="form-control" value="<?php echo date('Y-m-d', strtotime('+30 days')); ?>">
                                </div>
                                <button type="submit" id="btnM3U" class="btn btn-info btn-block">EXTRAIR E SINCRONIZAR</button>
                            </form>
                        </div>
                    </div>

                </div> </div> </div> </div>
</div>

<script src="https://vendedorp2p.com/views/_js/jquery/jquery-3.1.1.min.js"></script>
<script src="https://vendedorp2p.com/views/_js/bootstrap/bootstrap.min.js"></script>
</body>
</html>