<?php

namespace Modules\Workflows\Services\Actions;

use PDO;

class CreateRecordAction implements ActionInterface {
    private string $tenantId;
    private PDO $pdo;

    public function __construct(string $tenantId) {
        $this->tenantId = $tenantId;
        $this->pdo = \Gestoreasy\Core\Tenant\ConnectionManager::forTenant($tenantId);
    }

    public function execute(array $config, array $context): array {
        $table = $config['table'] ?? '';
        $data = $config['data'] ?? [];

        if (!$table) {
            throw new \Exception('Table name is required');
        }

        // Resolver variáveis nos dados
        $resolvedData = $this->resolveVariables($data, $context);

        // Construir query INSERT
        $columns = array_keys($resolvedData);
        $placeholders = array_map(fn($col) => ":{$col}", $columns);
        
        $sql = "INSERT INTO {$table} (" . implode(', ', $columns) . ") VALUES (" . implode(', ', $placeholders) . ")";
        $stmt = $this->pdo->prepare($sql);
        
        foreach ($resolvedData as $key => $value) {
            $stmt->bindValue(":{$key}", $value);
        }

        $stmt->execute();
        $id = (int)$this->pdo->lastInsertId();

        return [
            'created' => true,
            'table' => $table,
            'id' => $id
        ];
    }

    private function resolveVariables(array $data, array $context): array {
        $resolved = [];
        foreach ($data as $key => $value) {
            if (is_string($value)) {
                $resolved[$key] = $this->resolveVariable($value, $context);
            } elseif (is_array($value)) {
                $resolved[$key] = $this->resolveVariables($value, $context);
            } else {
                $resolved[$key] = $value;
            }
        }
        return $resolved;
    }

    private function resolveVariable(string $value, array $context): string {
        return preg_replace_callback('/\{\{([^}]+)\}\}/', function($matches) use ($context) {
            $var = trim($matches[1]);
            $parts = explode('.', $var);
            $result = $context;

            foreach ($parts as $part) {
                if (isset($result[$part])) {
                    $result = $result[$part];
                } else {
                    return $matches[0];
                }
            }

            return is_scalar($result) ? (string)$result : $matches[0];
        }, $value);
    }
}

