<?php
require_once __DIR__ . '/includes/header.php';

/* =======================
SEGURIDAD
======================= */

if (!isset($_SESSION['loggedin'], $_SESSION['name'], $_SESSION['role'])) {
    header("Location: index.php");
    exit;
}

$currentUser = $_SESSION['name'];
$role = $_SESSION['role'];

if (!in_array($role, ['master','super-reseller','reseller'])) {
    die("Acceso denegado");
}

/* =======================
OBTENER CREDITOS
======================= */

$myCredits = 0;

if ($role !== 'master') {
    $me = $db->select(
        'menualuser',
        'credits',
        'username = :u',
        '',
        [':u' => $currentUser]
    );
    $myCredits = (int)($me[0]['credits'] ?? 0);
}

/* =======================
GENERAR CODIGO
======================= */

function generateCode(){
    return str_pad(random_int(0,999999),6,'0',STR_PAD_LEFT);
}

/* =======================
VARIABLES MODAL
======================= */

$showModal = false;
$newCode = '';
$newClient = '';
$newPhone = '';
$newExpire = '';
$isDemo = false;
$demoHours = 0;

/* =======================
PROCESAR FORMULARIO
======================= */

if(isset($_POST['submit'])){

    $client = trim($_POST['client_name']);
    $phone  = trim($_POST['client_whatsapp']);
    
    // Detectar si es una demo (5 horas) o código normal (meses)
    $isDemoRequest = isset($_POST['is_demo']) && $_POST['is_demo'] == '1';
    
    if ($isDemoRequest) {
        // =======================
        // CREAR DEMO DE 5 HORAS (NO CONSUME CREDITOS)
        // =======================
        
        // Verificar si puede generar demo
        $canGenerateDemo = false;
        
        if ($role === 'master') {
            $canGenerateDemo = true;
        } else {
            // Reseller o Super-reseller: requiere al menos 3 créditos
            if ($myCredits >= 3) {
                $canGenerateDemo = true;
            }
        }
        
        if (!$canGenerateDemo) {
            if ($role !== 'master') {
                echo "<script>alert('❌ Créditos insuficientes para generar demo. Se requieren al menos 3 créditos disponibles. Tus créditos: {$myCredits}');</script>";
            } else {
                echo "<script>alert('❌ Error de permisos');</script>";
            }
        } else {
            // Generar demo de 5 horas
            $expire = date("Y-m-d H:i:s", strtotime("+5 hours"));
            $expireDateOnly = date("Y-m-d", strtotime("+5 hours"));
            
            // Generar código único
            $code = '';
            for($i=0;$i<50;$i++){
                $candidate = generateCode();
                $exist = $db->select(
                    'codes',
                    'id',
                    'code = :c',
                    '',
                    [':c' => $candidate]
                );
                if(!$exist){
                    $code = $candidate;
                    break;
                }
            }
            
            if($code != ''){
                $dbFile = __DIR__ . '/api/.db.db';
                $sqlite = new SQLite3($dbFile);
                
                // Verificar si la columna is_demo existe, si no, crearla
                try {
                    $checkColumn = $sqlite->query("PRAGMA table_info(codes)");
                    $hasDemoColumn = false;
                    while ($col = $checkColumn->fetchArray(SQLITE3_ASSOC)) {
                        if ($col['name'] == 'is_demo') {
                            $hasDemoColumn = true;
                            break;
                        }
                    }
                    if (!$hasDemoColumn) {
                        $sqlite->exec("ALTER TABLE codes ADD COLUMN is_demo INTEGER DEFAULT 0");
                        $sqlite->exec("ALTER TABLE codes ADD COLUMN demo_hours INTEGER DEFAULT 0");
                    }
                } catch (Exception $e) {
                    // Columna ya existe o error ignorable
                }
                
                $stmt = $sqlite->prepare("
                    INSERT INTO codes
                    (code, expires_at, owner, client_name, client_whatsapp, created_at, is_demo, demo_hours)
                    VALUES
                    (:code, :expire, :owner, :client, :phone, :created, :is_demo, :demo_hours)
                ");
                
                $stmt->bindValue(':code', $code);
                $stmt->bindValue(':expire', $expire);
                $stmt->bindValue(':owner', $currentUser);
                $stmt->bindValue(':client', $client);
                $stmt->bindValue(':phone', $phone);
                $stmt->bindValue(':created', date("Y-m-d H:i:s"));
                $stmt->bindValue(':is_demo', 1);
                $stmt->bindValue(':demo_hours', 5);
                
                $stmt->execute();
                
                // NO se restan créditos para demos
                
                $showModal = true;
                $newCode = $code;
                $newClient = $client;
                $newPhone = $phone;
                $newExpire = $expireDateOnly . " (5 horas)";
                $isDemo = true;
                $demoHours = 5;
            } else {
                echo "<script>alert('Error al generar código único. Intenta nuevamente.');</script>";
            }
        }
        
    } else {
        // =======================
        // CREAR CODIGO NORMAL (MESES) - CONSUME CREDITOS
        // =======================
        
        $months = (int)$_POST['months'];
        if($months < 1) $months = 1;
        
        if ($role !== 'master' && $months > $myCredits){
            echo "<script>alert('❌ Créditos insuficientes. Necesitas {$months} créditos, tienes {$myCredits}.');</script>";
        } else {
            $expire = date("Y-m-d", strtotime("+".($months*30)." days"));
            
            $code = '';
            for($i=0;$i<50;$i++){
                $candidate = generateCode();
                $exist = $db->select(
                    'codes',
                    'id',
                    'code = :c',
                    '',
                    [':c' => $candidate]
                );
                if(!$exist){
                    $code = $candidate;
                    break;
                }
            }
            
            if($code != ''){
                $dbFile = __DIR__ . '/api/.db.db';
                $sqlite = new SQLite3($dbFile);
                
                $stmt = $sqlite->prepare("
                    INSERT INTO codes
                    (code, expires_at, owner, client_name, client_whatsapp, created_at, is_demo, demo_hours)
                    VALUES
                    (:code, :expire, :owner, :client, :phone, :created, :is_demo, :demo_hours)
                ");
                
                $stmt->bindValue(':code', $code);
                $stmt->bindValue(':expire', $expire);
                $stmt->bindValue(':owner', $currentUser);
                $stmt->bindValue(':client', $client);
                $stmt->bindValue(':phone', $phone);
                $stmt->bindValue(':created', date("Y-m-d H:i:s"));
                $stmt->bindValue(':is_demo', 0);
                $stmt->bindValue(':demo_hours', 0);
                
                $stmt->execute();
                
                if ($role !== 'master') {
                    $db->update(
                        'menualuser',
                        ['credits'=>($myCredits-$months)],
                        'username = :u',
                        [':u' => $currentUser]
                    );
                    // Actualizar variable local para mostrar créditos actualizados
                    $myCredits = $myCredits - $months;
                }
                
                $showModal = true;
                $newCode = $code;
                $newClient = $client;
                $newPhone = $phone;
                $newExpire = $expire;
                $isDemo = false;
                $demoHours = 0;
            }
        }
    }
}

?>

<div class="col-md-8 mx-auto">

<div class="card text-white ctluser-main">

<div class="card-header text-center">
    <h2><i class="fa fa-key"></i> Crear Código</h2>
</div>

<div class="card-body">

    <!-- Tabs para seleccionar tipo de código -->
    <ul class="nav nav-tabs mb-4" id="codeTypeTab" role="tablist" style="border-bottom-color: #444;">
        <li class="nav-item" role="presentation">
            <button class="nav-link active" id="normal-tab" data-bs-toggle="tab" data-bs-target="#normal" type="button" role="tab" style="color: white; background: transparent;">
                <i class="fa fa-calendar"></i> Código por Meses
            </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="demo-tab" data-bs-toggle="tab" data-bs-target="#demo" type="button" role="tab" style="color: white; background: transparent;">
                <i class="fa fa-clock"></i> Demo (5 horas)
            </button>
        </li>
    </ul>
    
    <div class="tab-content">
        <!-- TAB: CÓDIGO NORMAL (MESES) -->
        <div class="tab-pane fade show active" id="normal" role="tabpanel">
            <form method="post">
                <input type="hidden" name="is_demo" value="0">
                
                <div class="form-group">
                    <label>Cliente</label>
                    <input type="text" name="client_name" class="form-control" required>
                </div>
                
                <div class="form-group">
                    <label>WhatsApp</label>
                    <input type="text" name="client_whatsapp" class="form-control" placeholder="593xxxxxxxxx" required>
                </div>
                
                <div class="form-group">
                    <label>Meses</label>
                    <select name="months" class="form-control">
                        <?php for($i=1;$i<=12;$i++): ?>
                        <option value="<?=$i?>"><?=$i?> mes<?=$i>1?'es':''?></option>
                        <?php endfor; ?>
                    </select>
                    
                    <?php if($role !== 'master'): ?>
                    <small class="text-muted">
                        <i class="fa fa-coins"></i> Créditos disponibles: <b class="text-warning"><?=$myCredits?></b>
                    </small>
                    <?php endif; ?>
                </div>
                
                <button type="submit" name="submit" class="btn btn-info">
                    <i class="fa fa-check"></i> Crear Código
                </button>
            </form>
        </div>
        
        <!-- TAB: DEMO (5 HORAS) -->
        <div class="tab-pane fade" id="demo" role="tabpanel">
            <form method="post">
                <input type="hidden" name="is_demo" value="1">
                
                <div class="form-group">
                    <label>Cliente</label>
                    <input type="text" name="client_name" class="form-control" required>
                </div>
                
                <div class="form-group">
                    <label>WhatsApp</label>
                    <input type="text" name="client_whatsapp" class="form-control" placeholder="593xxxxxxxxx" required>
                </div>
                
                <div class="form-group">
                    <label>Duración</label>
                    <input type="text" class="form-control" value="5 horas (Demo gratuita)" readonly disabled>
                    <small class="text-muted">
                        <i class="fa fa-info-circle"></i> Código de prueba válido por 5 horas
                    </small>
                </div>
                
                <?php if($role !== 'master'): ?>
                <div class="alert alert-warning" style="background: rgba(255,193,7,0.1); border-color: #ffc107; color: #ffc107;">
                    <i class="fa fa-exclamation-triangle"></i> 
                    Requisito: <strong>3 créditos disponibles</strong> (no se consumen)
                    <br>
                    <small>Tus créditos actuales: <b><?=$myCredits?></b></small>
                </div>
                <?php endif; ?>
                
                <button type="submit" name="submit" class="btn btn-success">
                    <i class="fa fa-gift"></i> Generar Demo (5 horas)
                </button>
            </form>
        </div>
    </div>
    
</div>
</div>
</div>

<?php if($showModal): ?>

<div class="modal fade show" style="display:block;background:rgba(0,0,0,0.7);">
    <div class="modal-dialog">
        <div class="modal-content bg-dark text-white">
            <div class="modal-header">
                <h5 class="modal-title">
                    <?php if($isDemo): ?>
                        <i class="fa fa-clock text-warning"></i> Demo Generada
                    <?php else: ?>
                        <i class="fa fa-check-circle text-success"></i> Código Creado
                    <?php endif; ?>
                </h5>
                <button type="button" class="close text-white" onclick="this.closest('.modal').remove()" style="background: none; border: none; font-size: 28px;">&times;</button>
            </div>
            
            <div class="modal-body text-center">
                
                <h2 style="font-size: 48px; letter-spacing: 5px; font-family: monospace; background: linear-gradient(135deg, #FF0000, #FF6666); -webkit-background-clip: text; -webkit-text-fill-color: transparent;">
                    <?=$newCode?>
                </h2>
                
                <p class="mt-3">
                    <strong>Cliente:</strong> <?=htmlspecialchars($newClient)?><br>
                    <strong>WhatsApp:</strong> <?=htmlspecialchars($newPhone)?><br>
                    <strong>Vencimiento:</strong> <?=$newExpire?>
                </p>
                
                <?php if($isDemo): ?>
                <div class="alert alert-info" style="background: rgba(0,123,255,0.2); border-color: #007bff;">
                    <i class="fa fa-hourglass-half"></i> Demo válida por 5 horas
                </div>
                <?php endif; ?>
                
                <div class="mt-3">
                    <button class="btn btn-success" onclick="sendWhatsApp('<?=$newCode?>','<?=$newExpire?>','<?=$newPhone?>','<?=addslashes($newClient)?>', <?=$isDemo ? 'true' : 'false'?>)">
                        <i class="fab fa-whatsapp"></i> Enviar por WhatsApp
                    </button>
                    
                    <button class="btn btn-info" onclick="copyCode('<?=$newCode?>')">
                        <i class="fa fa-copy"></i> Copiar Código
                    </button>
                </div>
                
                <br>
                <a href="clients.php" class="btn btn-light">
                    <i class="fa fa-users"></i> Ver Clientes
                </a>
                <a href="addclient.php" class="btn btn-outline-light">
                    <i class="fa fa-plus"></i> Crear Otro
                </a>
            </div>
        </div>
    </div>
</div>

<?php endif; ?>

<script>
function copyCode(code){
    navigator.clipboard.writeText(code);
    alert("✅ Código copiado: " + code);
}

function sendWhatsApp(code, expire, phone, name, isDemo){
    let msg = "📺 *DATOS DE ACCESO MyTube Premium*\n\n";
    msg += "*Cliente:* " + name + "\n";
    msg += "*Código:* " + code + "\n";
    
    if(isDemo){
        msg += "*Tipo:* Demo (5 horas de prueba)\n";
        msg += "*Válido hasta:* " + expire + "\n\n";
        msg += "✅ Disfruta YouTube sin anuncios durante 5 horas.";
    } else {
        msg += "*Vencimiento:* " + expire + "\n\n";
        msg += "✅ Disfruta YouTube sin anuncios durante todo el período.";
    }
    
    msg += "\n\n📱 Descarga la app: http://aftv.news/2293102\n";
    msg += "🔑 Código Downloader: 2293102";
    
    let url = "https://wa.me/" + phone + "?text=" + encodeURIComponent(msg);
    window.open(url, "_blank");
}

// Script para inicializar Bootstrap tabs si es necesario
document.addEventListener('DOMContentLoaded', function() {
    // Si Bootstrap JS no está disponible, agregar funcionalidad manual de tabs
    const tabs = document.querySelectorAll('[data-bs-toggle="tab"]');
    tabs.forEach(tab => {
        tab.addEventListener('click', function(e) {
            e.preventDefault();
            const targetId = this.getAttribute('data-bs-target');
            const targetPane = document.querySelector(targetId);
            
            // Remover active de todos los tabs y panes
            document.querySelectorAll('.nav-link').forEach(t => t.classList.remove('active'));
            document.querySelectorAll('.tab-pane').forEach(p => p.classList.remove('show', 'active'));
            
            // Activar tab actual y su pane
            this.classList.add('active');
            targetPane.classList.add('show', 'active');
        });
    });
});
</script>

<style>
/* Estilos para los tabs */
.nav-tabs .nav-link {
    border: none;
    color: #aaa;
    padding: 10px 20px;
    transition: all 0.3s;
}

.nav-tabs .nav-link:hover {
    color: #fff;
    border-bottom: 2px solid #ff4444;
}

.nav-tabs .nav-link.active {
    color: #ff4444;
    background: transparent;
    border-bottom: 2px solid #ff4444;
}

/* Mejorar estilo de modales */
.modal-content {
    border: 1px solid #ff4444;
    border-radius: 15px;
}

/* Estilo para select y inputs */
.form-control, .form-control:focus {
    background-color: #1a1a1a;
    border-color: #333;
    color: white;
}

.form-control:focus {
    border-color: #ff4444;
    box-shadow: 0 0 0 0.2rem rgba(255, 68, 68, 0.25);
}

select.form-control {
    background-color: #1a1a1a;
    color: white;
}

select.form-control option {
    background-color: #1a1a1a;
}
</style>

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