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

class Manfiet_Expense_Tracker_Shortcodes {
    private static $scripts_loaded = false;

    public function __construct() {
        add_shortcode('manfiet_expense_tracker', [$this, 'render_expense_tracker']);
    }

    public function render_expense_tracker() {
        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>';
        }

        // Load React App for Frontend (only once)
        if (!self::$scripts_loaded) {
            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::$scripts_loaded = true;
        }

        return '<div id="manfi-expense-tracker"></div>';
    }
}
