<?php

namespace FleekDash\Integrations\Core;

defined('ABSPATH') || exit;

/**
 * View Renderer for Integrations
 *
 * Renders view files with data
 */
class ViewRenderer
{
    /**
     * Base path for views
     */
    private string $viewPath;

    /**
     * Constructor
     */
    public function __construct(string $viewPath = '')
    {
        $this->viewPath = $viewPath ?: FLEEKDASH_PLUGIN_DIR . 'views/';
    }

    /**
     * Render a view file
     *
     * @param string $view View name (e.g., 'integrations/settings')
     * @param array $data Data to pass to the view
     * @return string Rendered HTML
     */
    public function render(string $view, array $data = []): string
    {
        $viewFile = $this->viewPath . str_replace('.', '/', $view) . '.php';

        if (!file_exists($viewFile)) {
            return "<!-- View not found: {$view} -->";
        }

        // Extract data to variables
        extract($data, EXTR_SKIP);

        // Start output buffering
        ob_start();

        try {
            include $viewFile;
            return ob_get_clean();
        } catch (\Exception $e) {
            ob_end_clean();
            return "<!-- Error rendering view {$view}: {$e->getMessage()} -->";
        }
    }

    /**
     * Check if view exists
     *
     * @param string $view View name
     * @return bool
     */
    public function exists(string $view): bool
    {
        $viewFile = $this->viewPath . str_replace('.', '/', $view) . '.php';
        return file_exists($viewFile);
    }

    /**
     * Set view path
     *
     * @param string $path Path to views directory
     * @return void
     */
    public function setViewPath(string $path): void
    {
        $this->viewPath = rtrim($path, '/') . '/';
    }

    /**
     * Get view path
     *
     * @return string
     */
    public function getViewPath(): string
    {
        return $this->viewPath;
    }
}

