<?php
require_once __DIR__ . '/../config/config_enhanced.php';
// Load DB connection
require_once __DIR__ . '/../classes/Database.php';

error_reporting(E_ALL);
ini_set('display_errors', 1);

/* This script was used to create the admin user 'yurley'.
   For security reasons, the original version that contained a plaintext password
   has been sanitized. To create or update admin users, use a secure script that
   accepts the password interactively or via a protected environment variable. */
$username = 'yurley';
$full_name = 'yurley';
$email = 'coordinacionsig@laboratorioximenacaicedo.com';
$sessionTimeoutSeconds = 31536000; // 1 year

try {
    $db = Database::getInstance();

    // Ensure admin_users table exists (same schema as migrar_passwords_bd)
    $db->execute("CREATE TABLE IF NOT EXISTS admin_users (
        id INT PRIMARY KEY AUTO_INCREMENT,
        username VARCHAR(50) UNIQUE NOT NULL,
        password_hash VARCHAR(255) NOT NULL,
        email VARCHAR(100),
        full_name VARCHAR(100),
        is_active TINYINT(1) DEFAULT 1,
        last_login DATETIME NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_username (username),
        INDEX idx_active (is_active)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;");

    // Hash password
    $passwordHash = password_hash($password, PASSWORD_BCRYPT);

    // Check if user exists
    $existing = $db->fetch("SELECT id FROM admin_users WHERE username = ?", [$username]);
    if ($existing) {
        $db->update('admin_users', [
            'password_hash' => $passwordHash,
            'email' => $email,
            'full_name' => $full_name,
            'is_active' => 1
        ], 'id = ?', ['id' => $existing['id']]);
        echo "Usuario '$username' actualizado (id={$existing['id']}).\n";
    } else {
        $id = $db->insert('admin_users', [
            'username' => $username,
            'password_hash' => $passwordHash,
            'email' => $email,
            'full_name' => $full_name,
            'is_active' => 1
        ]);
        echo "Usuario '$username' creado con id=$id.\n";
    }

    // Update system_config 'session_timeout' to 1 year (in seconds) if table exists
    try {
        $db->execute("CREATE TABLE IF NOT EXISTS system_config (
            id INT PRIMARY KEY AUTO_INCREMENT,
            config_key VARCHAR(100) UNIQUE NOT NULL,
            config_value TEXT,
            config_type VARCHAR(50) DEFAULT 'string',
            description TEXT,
            is_encrypted TINYINT(1) DEFAULT 0,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            INDEX idx_config_key (config_key)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;");

        // Upsert session_timeout
        $stmt = $db->getConnection()->prepare("INSERT INTO system_config (config_key, config_value, config_type, description) VALUES (?, ?, 'integer', ?) ON DUPLICATE KEY UPDATE config_value = VALUES(config_value)");
        $stmt->execute(['session_timeout', (string)$sessionTimeoutSeconds, 'Timeout de sesión en segundos (1 año)']);
        echo "Configuración 'session_timeout' actualizada a $sessionTimeoutSeconds segundos en DB.\n";
    } catch (Exception $ex) {
        echo "No se pudo actualizar system_config: " . $ex->getMessage() . "\n";
    }

    // Also update .env SESSION_TIMEOUT if writable
    $envFile = __DIR__ . '/../.env';
    if (is_writable($envFile)) {
        $contents = file_get_contents($envFile);
        if (strpos($contents, 'SESSION_TIMEOUT=') !== false) {
            $newContents = preg_replace('/SESSION_TIMEOUT\s*=\s*\d+/', 'SESSION_TIMEOUT=' . $sessionTimeoutSeconds, $contents);
        } else {
            $newContents = rtrim($contents, "\n") . "\nSESSION_TIMEOUT={$sessionTimeoutSeconds}\n";
        }
        if (@file_put_contents($envFile, $newContents) !== false) {
            echo ".env actualizado: SESSION_TIMEOUT={$sessionTimeoutSeconds}\n";
        } else {
            echo "No se pudo escribir en .env (permiso denegado).\n";
        }
    } else {
        echo ".env no es escribible o no existe, se omitió actualización del archivo.\n";
    }

    echo "Hecho. Recuerda que las sesiones actuales seguirán su tiempo de expiración hasta que los usuarios vuelvan a iniciar sesión (para aplicar el nuevo timeout).\n";

} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
    exit(1);
}
