<?php
/**
 * SAC 2025 - GUARDADO SEGURO DE USUARIOS v6.2
 * Soporta Email, Telegram Chat ID, Hashing Bcrypt y Periodos Demo.
 */
require_once 'config.php';
checkAccess(['admin', 'programmer']);

$data = $REQUEST_DATA;

if (!$data) {
    response(["error" => "No se recibieron datos válidos"], 400);
}

try {
    if (isset($data['id']) && !empty($data['id'])) {
        // --- ACTUALIZACIÓN ---
        $sql = "UPDATE users SET 
                full_name = ?, 
                username = ?, 
                email = ?, 
                phone = ?, 
                role = ?, 
                cedula = ?, 
                status = ?, 
                telegram_chat_id = ? ";
        
        $params = [
            $data['fullName'], 
            $data['username'], 
            $data['email'] ?? null, 
            $data['phone'] ?? null,
            $data['role'], 
            $data['cedula'], 
            ($data['status'] === 'active' || $data['status'] === 'Activo') ? 'active' : 'inactive',
            $data['telegramChatId'] ?? null
        ];

        // Lógica Demo: Si el programador activa días
        if (isset($data['activate_demo_days']) && (int)$data['activate_demo_days'] > 0) {
            $sql .= ", expires_at = DATE_ADD(CURDATE(), INTERVAL ? DAY) ";
            $params[] = (int)$data['activate_demo_days'];
        }

        // Si el usuario envió una contraseña (no vacía), la hasheamos
        if (!empty($data['password'])) {
            $sql .= ", password = ? ";
            $params[] = password_hash($data['password'], PASSWORD_DEFAULT);
        }

        $sql .= " WHERE id = ?";
        $params[] = $data['id'];

        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        
        logSystemAction("ACTUALIZÓ Perfil de Usuario: " . $data['fullName'] . ($data['role'] === 'demo' ? " (DEMO ACTIVADO)" : ""), "USUARIOS");
    } else {
        // --- CREACIÓN NUEVA ---
        $check = $pdo->prepare("SELECT id FROM users WHERE username = ? OR cedula = ?");
        $check->execute([$data['username'], $data['cedula']]);
        if ($check->fetch()) {
            response(["error" => "La Cédula o el Usuario ya existen en el sistema"], 409);
        }

        $stmt = $pdo->prepare("INSERT INTO users 
            (full_name, username, password, email, phone, role, cedula, status, telegram_chat_id) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
        
        $stmt->execute([
            $data['fullName'], 
            $data['username'], 
            password_hash($data['password'] ?? $data['cedula'], PASSWORD_DEFAULT), 
            $data['email'] ?? null,
            $data['phone'] ?? null, 
            $data['role'], 
            $data['cedula'], 
            'active', 
            $data['telegramChatId'] ?? null
        ]);

        logSystemAction("CREÓ nuevo usuario: " . $data['fullName'], "USUARIOS");
    }

    response(["success" => true]);

} catch (PDOException $e) {
    response(["error" => "Error de Base de Datos: " . $e->getMessage()], 500);
} catch (Exception $e) {
    response(["error" => "Error General: " . $e->getMessage()], 500);
}
?>