<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$db = new SQLite3('./api/.db.db');

// Verificar y agregar columna whatsapp si no existe
$tableInfo = $db->query("PRAGMA table_info(ibo)");
$whatsappColumnExists = false;
while ($column = $tableInfo->fetchArray(SQLITE3_ASSOC)) {
    if ($column['name'] === 'whatsapp') {
        $whatsappColumnExists = true;
        break;
    }
}

if (!$whatsappColumnExists) {
    if (!$db->exec('ALTER TABLE ibo ADD COLUMN whatsapp TEXT')) {
        die("Error al agregar la columna whatsapp: " . $db->lastErrorMsg());
    }
}

// Crear la tabla ibo si no existe (con la estructura completa)
$db->exec('CREATE TABLE IF NOT EXISTS ibo(
    id INTEGER PRIMARY KEY NOT NULL, 
    mac_address VARCHAR(100), 
    username VARCHAR(100), 
    password VARCHAR(100), 
    expire_date VARCHAR(100), 
    url VARCHAR(100), 
    title VARCHAR(100), 
    created_at VARCHAR(100),
    whatsapp TEXT
)');

// Crear la tabla subscription si no existe
$db->exec("CREATE TABLE IF NOT EXISTS subscription(id INTEGER PRIMARY KEY, mac_address TEXT, expire_date TEXT)");

// Obtener las opciones de DNS
$dnsOptions = [];
$dnsResult = $db->query('SELECT * FROM dns');
while ($row = $dnsResult->fetchArray(SQLITE3_ASSOC)) {
    $dnsOptions[] = $row;
}

if (isset($_GET['index'])) {
    $index = $_GET['index'];
} else {
    $index = "";
}

if (isset($_POST['submit'])) {
    // Validar y formatear fecha de expiración
    try {
        $expireDate = new DateTime($_POST['expire_date']);
        $ne = $expireDate->format('Y-m-d');
    } catch (Exception $e) {
        die("Fecha de expiración inválida: " . $e->getMessage());
    }
    
    $start = date('Y-m-d');
    $end = date('H:i:s');
    $full = $start . 'T' . $end . '.000000Z';

    // Validar y limpiar número de WhatsApp
    $whatsapp = preg_replace('/[^0-9]/', '', $_POST['whatsapp']);
    if (empty($whatsapp) || strlen($whatsapp) < 10 || strlen($whatsapp) > 15) {
        die("Número de WhatsApp inválido. Debe tener entre 10 y 15 dígitos.");
    }

    $macAddresses = $_POST['mac_address'];
    $isSuccess = true;

    foreach ($macAddresses as $mac) {
        $formattedMac = strtoupper(str_replace([':', '-', ' '], '', $mac));
        $formattedMac = implode(':', str_split($formattedMac, 2));

        // Insertar en la tabla ibo con manejo de errores
        $iboQuery = $db->prepare("INSERT INTO ibo(mac_address, username, password, expire_date, url, title, created_at, whatsapp)
                     VALUES(:mac, :username, :password, :expire, :url, :title, :created, :whatsapp)");
        
        if (!$iboQuery) {
            die("Error al preparar la consulta: " . $db->lastErrorMsg());
        }
        
        $iboQuery->bindValue(':mac', $formattedMac, SQLITE3_TEXT);
        $iboQuery->bindValue(':username', $_POST['username'], SQLITE3_TEXT);
        $iboQuery->bindValue(':password', $_POST['password'], SQLITE3_TEXT);
        $iboQuery->bindValue(':expire', $ne, SQLITE3_TEXT);
        $iboQuery->bindValue(':url', $_POST['dns'], SQLITE3_TEXT);
        $iboQuery->bindValue(':title', $_POST['title'], SQLITE3_TEXT);
        $iboQuery->bindValue(':created', $full, SQLITE3_TEXT);
        $iboQuery->bindValue(':whatsapp', $whatsapp, SQLITE3_TEXT);
        
        if (!$iboQuery->execute()) {
            $isSuccess = false;
            error_log("Error al insertar en ibo: " . $db->lastErrorMsg());
        }

        // Insertar en la tabla subscription
        $checkQuery = $db->prepare("SELECT COUNT(*) as count FROM subscription WHERE mac_address = :macAddress");
        $checkQuery->bindValue(':macAddress', $formattedMac, SQLITE3_TEXT);
        $result = $checkQuery->execute();
        
        if (!$result) {
            error_log("Error al verificar suscripción: " . $db->lastErrorMsg());
            continue;
        }
        
        $row = $result->fetchArray(SQLITE3_ASSOC);

        if ($row['count'] == 0) {
            $insertQuery = $db->prepare("INSERT INTO subscription (mac_address, expire_date) VALUES (:macAddress, :expireDate)");
            $insertQuery->bindValue(':macAddress', $formattedMac, SQLITE3_TEXT);
            $insertQuery->bindValue(':expireDate', $ne, SQLITE3_TEXT);
            if (!$insertQuery->execute()) {
                $isSuccess = false;
                error_log("Error al insertar en subscription: " . $db->lastErrorMsg());
            }
        }
    }

    if ($isSuccess) {
        header('Location: users.php?success=1');
        exit;
    } else {
        die("Hubo un error al registrar los datos. Por favor revise los logs.");
    }
}

include 'includes/header.php';
?>
<script>
document.addEventListener("DOMContentLoaded", function() {
    function formatMacInput(input) {
        input.addEventListener("input", function(e) {
            var value = e.target.value.replace(/[^a-fA-F0-9]/g, "").toUpperCase();
            var formatted = "";
            for (var i = 0; i < value.length; i++) {
                formatted += value[i];
                if ((i + 1) % 2 === 0 && i < value.length - 1) {
                    formatted += ":";
                }
                if (formatted.length >= 17) break; // Limitar a longitud MAC estándar
            }
            e.target.value = formatted;
        });
    }

    formatMacInput(document.querySelector('.mac-input'));

    document.getElementById('add_mac_field').addEventListener('click', function () {
        var container = document.getElementById('mac_fields');
        var newInputGroup = document.createElement('div');
        newInputGroup.classList.add('input-group', 'mt-2');
        newInputGroup.innerHTML = `<input class="form-control text-primary mac-input" name="mac_address[]" type="text" placeholder="Ingrese MAC Address" required/>`;
        container.appendChild(newInputGroup);
        formatMacInput(newInputGroup.querySelector('.mac-input'));
    });

    // Validar WhatsApp al enviar el formulario
    document.querySelector('form').addEventListener('submit', function(e) {
        var whatsappInput = document.querySelector('input[name="whatsapp"]');
        var whatsappValue = whatsappInput.value.replace(/[^0-9]/g, '');
        
        if (whatsappValue.length < 10 || whatsappValue.length > 15) {
            alert('Ingresar WhatsApp válido con código de país (ej: 593980649398)');
            e.preventDefault();
            return false;
        }
        
        // Actualizar el valor limpio en el campo
        whatsappInput.value = whatsappValue;
        return true;
    });
});
</script>

<div class="col-md-6 mx-auto">
    <div class="mx-auto" style="max-width: 900px;">
        <h1 class="title-outside-card mb-1">Registrar Clientes</h1>
        <div class="card border-left-primary shadow h-100 card shadow mb-4">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-color"><i class="fas fa-user"></i> Detalles</h6>
            </div>
            <div class="card-body">
                <form method="post">
                    <div class="form-group">
                        <label><strong>Mac Address</strong></label>
                        <div id="mac_fields">
                            <div class="input-group">
                                <input class="form-control text-primary mac-input" name="mac_address[]" type="text" placeholder="Ingrese MAC Address" value="<?php echo strtoupper($index); ?>" required/>
                            </div>
                        </div>
                        <button type="button" id="add_mac_field" class="btn btn-secondary mt-2">Agregar otra MAC</button>
                    </div>
                    <div class="form-group">
                        <label>Usuario</label>
                        <input type="text" name="username" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>Contraseña</label>
                        <input type="text" name="password" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>DNS</label>
                        <select name="dns" class="form-control" required>
                            <option value="">Seleccionar DNS</option>
                            <?php foreach ($dnsOptions as $dns): ?>
                                <option value="<?= htmlspecialchars($dns['url']) ?>"><?= htmlspecialchars($dns['url']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Nombre del Servidor o del Cliente</label>
                        <input type="text" name="title" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>WhatsApp (ej: 593980649398)</label>
                        <input type="text" name="whatsapp" class="form-control" 
                               placeholder="" 
                               pattern="[0-9]{10,15}" 
                               title="Ingrese un número válido con código de país (10-15 dígitos)" 
                               required>
                        <small class="form-text text-muted">Número con código de país (sin +, espacios ni guiones)</small>
                    </div>
                    <div class="form-group">
                        <label>Fecha de Expiración</label>
                        <input type="date" name="expire_date" class="form-control" min="<?= date('Y-m-d') ?>" required>
                    </div>
                    <button type="submit" name="submit" class="btn btn-success btn-icon-split">
                        <span class="icon text-white-50"><i class="fas fa-check"></i></span>
                        <span class="text">Guardar</span>
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<?php include 'includes/footer.php'; ?>