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

// Conectar a la base de datos SQLite
$db = new SQLite3('./api/.db.db');

// Recuperar datos del usuario basado en el parámetro 'update' de la URL
$updateId = $_GET['update'];

// Consulta preparada para seguridad
$stmt = $db->prepare('SELECT * FROM ibo WHERE id = :id');
$stmt->bindValue(':id', $updateId, SQLITE3_INTEGER);
$res = $stmt->execute();
$row = $res->fetchArray(SQLITE3_ASSOC);

if (!$row) {
    die("Usuario no encontrado");
}

// Asignar valores a variables
$id = $row['id'];
$mac_address = $row['mac_address'];
$expire_date = $row['expire_date'];
$username = $row['username'];
$password = $row['password'];
$url = $row['url'];
$title = $row['title'];
$whatsapp = $row['whatsapp'] ?? ''; // Nuevo campo whatsapp

// Verificar si el formulario ha sido enviado
if (isset($_POST['submit'])) {
    // Validar y formatear los datos
    $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.");
    }

    // Formatear fecha de expiración
    $we = strtotime($_POST['expire_date']);
    $ne = date('Y-m-d', $we);
    $start = date('Y-m-d');
    $end = date('H:i:s');
    $full = $start . 'T' . $end . '.000000Z';

    // Iniciar transacción para asegurar consistencia
    $db->exec('BEGIN TRANSACTION');
    
    try {
        // 1. Actualizar tabla 'ibo'
        $updateStmt = $db->prepare('UPDATE ibo SET 
            mac_address = :mac_address,
            expire_date = :expire_date,
            username = :username,
            url = :url,
            title = :title,
            password = :password,
            whatsapp = :whatsapp,
            created_at = :created_at
            WHERE id = :id');
        
        $updateStmt->bindValue(':mac_address', $_POST['mac_address'], SQLITE3_TEXT);
        $updateStmt->bindValue(':expire_date', $ne, SQLITE3_TEXT);
        $updateStmt->bindValue(':username', $_POST['username'], SQLITE3_TEXT);
        $updateStmt->bindValue(':url', $_POST['url'], SQLITE3_TEXT);
        $updateStmt->bindValue(':title', $_POST['title'], SQLITE3_TEXT);
        $updateStmt->bindValue(':password', $_POST['password'], SQLITE3_TEXT);
        $updateStmt->bindValue(':whatsapp', $whatsapp, SQLITE3_TEXT);
        $updateStmt->bindValue(':created_at', $full, SQLITE3_TEXT);
        $updateStmt->bindValue(':id', $_POST['id'], SQLITE3_INTEGER);
        
        if (!$updateStmt->execute()) {
            throw new Exception("Error al actualizar usuario: " . $db->lastErrorMsg());
        }

        // 2. Verificar si existe la suscripción antes de actualizar
        $checkSub = $db->prepare('SELECT 1 FROM subscription WHERE mac_address = :old_mac LIMIT 1');
        $checkSub->bindValue(':old_mac', $mac_address, SQLITE3_TEXT);
        $result = $checkSub->execute();
        
        if ($result->fetchArray()) {
           // Si existe, actualizar
$updateSubStmt = $db->prepare('UPDATE subscription SET 
    mac_address = :new_mac, 
    expire_date = :expire_date 
    WHERE mac_address = :old_mac');

$updateSubStmt->bindValue(':new_mac', $_POST['mac_address'], SQLITE3_TEXT);
$updateSubStmt->bindValue(':expire_date', $ne, SQLITE3_TEXT);
$updateSubStmt->bindValue(':old_mac', $mac_address, SQLITE3_TEXT);

if (!$updateSubStmt->execute()) {
    throw new Exception("Error al actualizar suscripción: " . $db->lastErrorMsg());
}

/*
// Si no existe, insertar nueva suscripción
$insertSubStmt = $db->prepare('INSERT INTO subscription 
    (mac_address, expire_date) 
    VALUES (:mac_address, :expire_date)');

$insertSubStmt->bindValue(':mac_address', $_POST['mac_address'], SQLITE3_TEXT);
$insertSubStmt->bindValue(':expire_date', $ne, SQLITE3_TEXT);

if (!$insertSubStmt->execute()) {
    throw new Exception("Error al crear suscripción: " . $db->lastErrorMsg());
}
*/

// Confirmar transacción si todo salió bien
$db->exec('COMMIT');

         }
        // Redirigir después de actualizar
        header('Location: users.php?update=success');
        exit();
        
    } catch (Exception $e) {
        $db->exec('ROLLBACK');
        die($e->getMessage());
    }
}

// Incluir el header
include 'includes/header.php';

// Asignar datos del usuario para usar en el formulario HTML
$userUpdateId = $row['id'];
$userUpdateMacAddress = $row['mac_address'];
$userUpdateExpireDate = $row['expire_date'];
$userUpdateUsername = $row['username'];
$userUpdatePassword = $row['password'];
$userUpdateUrl = $row['url'];
$userUpdateTitle = $row['title'];
$userUpdateWhatsapp = $row['whatsapp'] ?? '';
?>

<!-- Display the form with user data -->
<<div class="col-md-6 mx-auto">
    <div class="mx-auto" style="max-width: 900px;">
        <h1 class="title-outside-card mb-1">Actualizar Usuario</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="fa fa-user"></i> Editar Usuario</h6>
            </div>
            <div class="card-body">
                <form method="post">
                    <div class="form-group">
                        <label class="control-label" for="mac_address"><strong>Mac Address</strong></label>
                        <div class="input-group">
                            <input type="hidden" name="id" value="<?= $id ?>" />
                            <input class="form-control text-primary" id="description" name="mac_address" value="<?= $mac_address ?>" type="text" required />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label" for="username"><strong>Usuario</strong></label>
                        <div class="input-group">
                            <input type="text" class="form-control text-primary" name="username" value="<?= $username ?>" id="description" required />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label" for="password"><strong>Contraseña</strong></label>
                        <div class="input-group">
                            <input type="text" class="form-control text-primary" name="password" value="<?= $password ?>" id="description" required />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label" for="expire_date"><strong>Fecha de Expiración</strong></label>
                        <div class="input-group">
                            <input type="text" class="form-control text-primary" name="expire_date" value="<?= $expire_date ?>" id="datepicker" />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label" for="url"><strong>URL</strong></label>
                        <div class="input-group">
                            <input type="text" class="form-control text-primary" name="url" value="<?= $url ?>" id="description" required />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label" for="title"><strong>Título</strong></label>
                        <div class="input-group">
                            <input type="text" class="form-control text-primary" name="title" value="<?= $title ?>" id="description" required />
                        </div>
                    </div>
                    <!-- Nuevo campo WhatsApp -->
                    <div class="form-group">
                        <label class="control-label" for="whatsapp"><strong>WhatsApp</strong></label>
                        <div class="input-group">
                            <input type="text" class="form-control text-primary" name="whatsapp" value="<?= $whatsapp ?>" 
                                   placeholder="Ej: 593980649398" 
                                   pattern="[0-9]{10,15}" 
                                   title="Ingrese número con código de país (10-15 dígitos)" 
                                   required />
                            <small class="form-text text-muted">Formato: Código de país + número (sin +, espacios ni guiones)</small>
                        </div>
                    </div>
                    <div class="form-group">
                        <div>
                            <button class="btn btn-success btn-icon-split" name="submit" type="submit">
                                <span class="icon text-white-50"><i class="fa fa-check"></i></span><span class="text">Guardar</span>
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>