<?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);
}

/* =======================
FUNCIÓN PARA ACTIVAR MAC (GUARDA EN code_connections con is_mac_activated=1)
======================= */

function activateMac($mac, $code, $currentUser) {
    $dbFile = __DIR__ . '/api/.db.db';
    
    if (!file_exists($dbFile)) {
        error_log("MAC ERROR: DB no encontrada en " . $dbFile);
        return false;
    }
    
    try {
        $sqlite = new SQLite3($dbFile);
        
        // Asegurar que la tabla tiene las columnas necesarias
        $sqlite->exec("
            CREATE TABLE IF NOT EXISTS code_connections (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                code TEXT NOT NULL,
                device_id TEXT NOT NULL,
                mac TEXT,
                ip_address TEXT,
                connected_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                last_activity DATETIME DEFAULT CURRENT_TIMESTAMP,
                is_active INTEGER DEFAULT 1,
                is_mac_activated INTEGER DEFAULT 0,
                UNIQUE(code, device_id)
            )
        ");
        
        // Agregar columna is_mac_activated si no existe
        try {
            $sqlite->exec("ALTER TABLE code_connections ADD COLUMN is_mac_activated INTEGER DEFAULT 0");
        } catch (Exception $e) {
            // Columna ya existe, ignorar
        }
        
        // Eliminar cualquier registro previo con esta MAC para evitar duplicados
        $sqlite->exec("DELETE FROM code_connections WHERE mac = '$mac'");
        
        // Insertar la MAC como activada
        $stmt = $sqlite->prepare("
            INSERT INTO code_connections (code, device_id, mac, ip_address, connected_at, last_activity, is_active, is_mac_activated)
            VALUES (:code, :device_id, :mac, 'REMOTE', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, 1, 1)
        ");
        
        $stmt->bindValue(':code', $code, SQLITE3_TEXT);
        $stmt->bindValue(':device_id', $mac, SQLITE3_TEXT);
        $stmt->bindValue(':mac', $mac, SQLITE3_TEXT);
        
        $result = $stmt->execute();
        
        if ($result) {
            error_log("✅ MAC activada correctamente: $mac -> $code");
            return true;
        } else {
            error_log("❌ Error al activar MAC: " . $sqlite->lastErrorMsg());
            return false;
        }
        
    } catch (Throwable $e) {
        error_log("❌ Excepción en activateMac: " . $e->getMessage());
        return false;
    }
}

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

$showModal = false;
$newCode = '';
$newClient = '';
$newPhone = '';
$newExpire = '';
$isDemo = false;
$showMacField = false;
$macAddress = '';
$activationError = '';

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

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

    $client = trim($_POST['client_name']);
    $phone  = trim($_POST['client_whatsapp']);
    $mac = isset($_POST['mac_address']) ? strtoupper(trim($_POST['mac_address'])) : '';
    
    // Validar formato MAC si se ingresó
    if($mac !== '' && !preg_match('/^[A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2}:[A-F0-9]{2}$/', $mac)){
        $activationError = "❌ Formato MAC inválido. Use formato: XX:XX:XX:XX";
        $mac = '';
    }
    
    // Detectar si es una demo o código normal
    $isDemoRequest = isset($_POST['is_demo']) && $_POST['is_demo'] == '1';
    
    if ($isDemoRequest) {
        // =======================
        // CREAR DEMO DE 5 HORAS
        // =======================
        
        $canGenerateDemo = false;
        
        if ($role === 'master') {
            $canGenerateDemo = true;
        } else {
            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. Tus créditos: {$myCredits}');</script>";
            }
        } else {
            // Generar demo
            $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 columnas demo
                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) {}
                
                $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();
                
                // Activar MAC si se proporcionó
                if($mac !== ''){
                    if(activateMac($mac, $code, $currentUser)){
                        $showMacField = true;
                    } else {
                        $activationError = "⚠️ Código creado pero hubo error al activar la MAC";
                    }
                }
                
                $showModal = true;
                $newCode = $code;
                $newClient = $client;
                $newPhone = $phone;
                $newExpire = $expireDateOnly . " (5 horas)";
                $isDemo = true;
                $macAddress = $mac;
            }
        }
        
    } else {
        // =======================
        // CREAR CODIGO NORMAL (MESES)
        // =======================
        
        $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"));
            
            // 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);
                
                $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();
                
                // Consumir créditos
                if ($role !== 'master') {
                    $db->update('menualuser', ['credits'=>($myCredits-$months)], 'username = :u', [':u' => $currentUser]);
                    $myCredits = $myCredits - $months;
                }
                
                // Activar MAC si se proporcionó
                if($mac !== ''){
                    if(activateMac($mac, $code, $currentUser)){
                        $showMacField = true;
                    } else {
                        $activationError = "⚠️ Código creado pero hubo error al activar la MAC";
                    }
                }
                
                $showModal = true;
                $newCode = $code;
                $newClient = $client;
                $newPhone = $phone;
                $newExpire = $expire;
                $isDemo = false;
                $macAddress = $mac;
            }
        }
    }
}

?>

<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">

    <?php if($activationError): ?>
    <div class="alert alert-warning alert-dismissible fade show" role="alert">
        <?php echo $activationError; ?>
        <button type="button" class="close" data-dismiss="alert">
            <span>&times;</span>
        </button>
    </div>
    <?php endif; ?>

    <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">
        <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>
                
                <div class="form-group">
                    <label>MAC (Opcional)</label>
                    <input type="text" name="mac_address" class="form-control" placeholder="Ej: 99:59:41:2B">
                    <small class="text-muted">
                        <i class="fa fa-info-circle"></i> Si ingresas la MAC, el dispositivo se activará automáticamente sin necesidad de código
                    </small>
                </div>
                
                <button type="submit" name="submit" class="btn btn-info">
                    <i class="fa fa-check"></i> Crear Código
                </button>
            </form>
        </div>
        
        <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>MAC (Opcional)</label>
                    <input type="text" name="mac_address" class="form-control" placeholder="Ej: 99:59:41:2B">
                    <small class="text-muted">
                        <i class="fa fa-info-circle"></i> Si ingresas la MAC, el dispositivo se activará automáticamente
                    </small>
                </div>
                
                <div class="form-group">
                    <label>Duración</label>
                    <input type="text" class="form-control" value="5 horas (Demo gratuita)" readonly disabled>
                </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
                </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($showMacField && $macAddress): ?>
                <div class="alert alert-success" style="background: rgba(40,167,69,0.2); border-color: #28a745;">
                    <i class="fa fa-check-circle"></i> 
                    <strong>✅ Activación remota configurada</strong><br>
                    MAC: <code><?=$macAddress?></code><br>
                    El dispositivo se activará automáticamente al abrir la app.
                </div>
                <?php endif; ?>
                
                <?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 Youtube sin Anuncios*\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";
    } else {
        msg += "*Vencimiento:* " + expire + "\n\n";
    }

    msg += "📥 *DESCARGAS:*\n";
    msg += "📺 TV (Downloader): Código *7659917*\n";
    msg += "📺 PC (Windows 10/11): https://tizentube.sysrgvip.com/Tubewindows.exe\n"; 
    msg += "📱 Móvil: https://tizentube.sysrgvip.com/Ymovil2.apk";

    let url = "https://wa.me/" + phone + "?text=" + encodeURIComponent(msg);
    window.open(url, "_blank");
}

document.addEventListener('DOMContentLoaded', function() {
    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);
            
            document.querySelectorAll('.nav-link').forEach(t => t.classList.remove('active'));
            document.querySelectorAll('.tab-pane').forEach(p => p.classList.remove('show', 'active'));
            
            this.classList.add('active');
            targetPane.classList.add('show', 'active');
        });
    });
});
</script>

<style>
.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;
}

.modal-content {
    border: 1px solid #ff4444;
    border-radius: 15px;
}

.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'; ?>