<?php
if (!defined('ABSPATH')) {
    exit;
}

class Manfiet_Expense_Tracker_Blocks {
    private static $assets_enqueued = false;

    public function __construct() {
        add_action('init', [$this, 'register_blocks']);
        add_filter('block_categories_all', [$this, 'register_block_category'], 10, 2);
    }

    /**
     * Register a custom Gutenberg block category for Manfi Expense Tracker.
     */
    public function register_block_category($categories, $post) {
        if (!get_option('manfiet_enable_gutenberg_blocks', 1)) {
            return $categories;
        }

        return array_merge(
            $categories,
            [
                [
                    'slug'  => 'manfi-expense-tracker',
                    'title' => __('Manfi Expense Tracker', 'manfi-expense-tracker'),
                    'icon'  => 'money-alt',
                ]
            ]
        );
    }

    /**
     * Register Gutenberg blocks using metadata block.json.
     */
    public function register_blocks() {
        if (!function_exists('register_block_type')) {
            return;
        }

        // Check if Gutenberg blocks are enabled in settings
        if (!get_option('manfiet_enable_gutenberg_blocks', 1)) {
            return;
        }

        // Register the editor script with standard core Gutenberg dependencies
        wp_register_script(
            'manfiet-blocks-editor',
            MANFIET_EXPENSE_TRACKER_PLUGIN_URL . 'assets/js/blocks-editor.js',
            ['wp-blocks', 'wp-element', 'wp-i18n'],
            MANFIET_EXPENSE_TRACKER_VERSION,
            true
        );

        // Register Expense Entry Block
        register_block_type(MANFIET_EXPENSE_TRACKER_PLUGIN_DIR . 'blocks/expense-entry', [
            'render_callback' => [$this, 'render_expense_entry_block'],
        ]);

        // Register Expense Dashboard Block
        register_block_type(MANFIET_EXPENSE_TRACKER_PLUGIN_DIR . 'blocks/expense-dashboard', [
            'render_callback' => [$this, 'render_expense_dashboard_block'],
        ]);

        // Register Budget Showcase Block
        register_block_type(MANFIET_EXPENSE_TRACKER_PLUGIN_DIR . 'blocks/budget-showcase', [
            'render_callback' => [$this, 'render_budget_showcase_block'],
        ]);
    }

    /**
     * Enqueue dynamic block scripts, styles, and localized REST credentials.
     */
    private function enqueue_frontend_assets() {
        if (self::$assets_enqueued) {
            return;
        }

        wp_enqueue_style(
            'manfiet-expense-frontend-style',
            MANFIET_EXPENSE_TRACKER_PLUGIN_URL . 'assets/css/frontend.css',
            [],
            MANFIET_EXPENSE_TRACKER_VERSION
        );

        wp_enqueue_script(
            'manfiet-frontend-app',
            MANFIET_EXPENSE_TRACKER_PLUGIN_URL . 'assets/js/admin.js',
            ['wp-element'],
            MANFIET_EXPENSE_TRACKER_VERSION,
            true
        );

        wp_localize_script('manfiet-frontend-app', 'manfietExpenseTrackerData', [
            'restBase' => esc_url_raw(rest_url('manfi-expense-tracker/v1/')),
            'restNonce' => wp_create_nonce('wp_rest'),
            'canManageExpenses' => current_user_can('manage_expenses') || current_user_can('manage_options'),
            'pageView' => 'frontend',
            'expensesPerPage' => (int) get_option('manfiet_expenses_per_page', 20),
            'currencySymbol' => class_exists('Manfiet_Expense_Tracker_Settings') ? Manfiet_Expense_Tracker_Settings::get_current_currency_symbol() : '$',
            'currencyCode' => get_option('manfiet_currency', 'USD'),
        ]);

        self::$assets_enqueued = true;
    }

    /**
     * Render Callback: Expense Entry
     */
    public function render_expense_entry_block($attributes, $content) {
        if (!is_user_logged_in()) {
            return '<p>' . esc_html__('You need to be logged in to track your expenses.', 'manfi-expense-tracker') . '</p>';
        }

        if (!current_user_can('read')) {
            return '<p>' . esc_html__('You do not have permission to access this tracker.', 'manfi-expense-tracker') . '</p>';
        }

        $this->enqueue_frontend_assets();

        return '<div class="manfi-expense-tracker-mount" data-view="expense-entry"></div>';
    }

    /**
     * Render Callback: Expense Dashboard
     */
    public function render_expense_dashboard_block($attributes, $content) {
        if (!is_user_logged_in()) {
            return '<p>' . esc_html__('You need to be logged in to track your expenses.', 'manfi-expense-tracker') . '</p>';
        }

        if (!current_user_can('read')) {
            return '<p>' . esc_html__('You do not have permission to access this tracker.', 'manfi-expense-tracker') . '</p>';
        }

        $this->enqueue_frontend_assets();

        return '<div class="manfi-expense-tracker-mount" data-view="dashboard"></div>';
    }

    /**
     * Render Callback: Budget Showcase
     */
    public function render_budget_showcase_block($attributes, $content) {
        if (!is_user_logged_in()) {
            return '<p>' . esc_html__('You need to be logged in to track your expenses.', 'manfi-expense-tracker') . '</p>';
        }

        if (!current_user_can('read')) {
            return '<p>' . esc_html__('You do not have permission to access this tracker.', 'manfi-expense-tracker') . '</p>';
        }

        $this->enqueue_frontend_assets();

        return '<div class="manfi-expense-tracker-mount" data-view="budget"></div>';
    }
}
