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

class Manfiet_Expense_Tracker_Setup {
    private static $instance = null;

    public static function get_instance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        // Initialize hooks and schedules
        add_filter('cron_schedules', [$this, 'add_cron_schedules']);
        add_action('plugins_loaded', [$this, 'init_plugin_components']);
        add_action('init', [$this, 'sync_roles'], 20);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_scripts']);
        add_action('wp_enqueue_scripts', [$this, 'enqueue_google_fonts']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_google_fonts']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_global_admin_styles']);
    }

    public function add_cron_schedules($schedules) {
        if (!isset($schedules['weekly'])) {
            $schedules['weekly'] = [
                'interval' => WEEK_IN_SECONDS,
                'display'  => __('Once Weekly', 'manfi-expense-tracker'),
            ];
        }

        if (!isset($schedules['monthly'])) {
            $schedules['monthly'] = [
                'interval' => MONTH_IN_SECONDS,
                'display'  => __('Once Monthly', 'manfi-expense-tracker'),
            ];
        }

        return $schedules;
    }

    public function init_plugin_components() {
        new Manfiet_Expense_Tracker();
        new Manfiet_Invoice_Manager();
        new Manfiet_Financial_Account_Manager();
        new Manfiet_Vendor_Manager();
        new Manfiet_Client_Manager();
        new Manfiet_Expense_Tracker_Shortcodes();
        new Manfiet_Expense_Tracker_Blocks();
        new Manfiet_Expense_Tracker_Settings();
        new Manfiet_Expense_Tracker_Elementor();
        new Manfiet_Budget_Alerts();
        new Manfiet_Email_Reports();
        new Manfiet_Expense_Tracker_Other_Plugins();
        new Manfiet_Expense_Admin_Notice_Manager();
        new Manfiet_Google_Sheets_Manager();
    }

    public function sync_roles() {
        Manfiet_Expense_Role_Permissions::add_roles();
    }

    public function enqueue_admin_scripts($hook) {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin page slug for view routing.
        $requested_page = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : '';
        $admin_hooks = [
            'toplevel_page_manfi-expense-tracker',
            'toplevel_page_manfiet-invoice-manager',
            'expense-tracker_page_manfiet-expense-categories',
            'expense-tracker_page_manfiet-expense-tags',
            'expense-tracker_page_manfiet-expense-budget',
            'expense-tracker_page_manfiet-expense-reports',
            'expense-tracker_page_manfiet-expense-add',
            'invoice-manager_page_manfiet-invoice-manager',
            'invoice-manager_page_manfiet-invoice-create',
            'invoice-manager_page_manfiet-financial-accounts',
            'invoice-manager_page_manfiet-vendors',
            'invoice-manager_page_manfiet-clients',
            'manfiet-invoice-manager_page_manfiet-invoice-create',
            'manfiet-invoice-manager_page_manfiet-financial-accounts',
            'manfiet-invoice-manager_page_manfiet-vendors',
            'manfiet-invoice-manager_page_manfiet-clients',
            'manfi-expense-tracker_page_manfiet-expense-categories',
            'manfi-expense-tracker_page_manfiet-expense-tags',
            'manfi-expense-tracker_page_manfiet-expense-budget',
            'manfi-expense-tracker_page_manfiet-expense-reports',
            'manfi-expense-tracker_page_manfiet-expense-add',
            'manfi-expense-tracker_page_manfiet-invoice-manager',
            'manfi-expense-tracker_page_manfiet-invoice-create',
            'manfi-expense-tracker_page_manfiet-financial-accounts',
            'manfi-expense-tracker_page_manfiet-vendors',
            'manfi-expense-tracker_page_manfiet-clients',
        ];

        $admin_pages = [
            'manfiet-expense-categories',
            'manfiet-expense-tags',
            'manfiet-expense-budget',
            'manfiet-expense-reports',
            'manfiet-expense-add',
            'manfiet-invoice-manager',
            'manfiet-invoice-create',
            'manfiet-financial-accounts',
            'manfiet-financial-accounts-create',
            'manfiet-vendors',
            'manfiet-vendors-create',
            'manfiet-clients',
            'manfiet-clients-create',
            'manfiet-other-plugins',
            'manfiet-migration',
            'manfiet-expense-settings',
        ];

        if (in_array($hook, $admin_hooks, true) || in_array($requested_page, $admin_pages, true)) {
            $page_view = 'dashboard';
            if ($requested_page === 'manfiet-invoice-manager' || $hook === 'toplevel_page_manfiet-invoice-manager' || $hook === 'manfi-expense-tracker_page_manfiet-invoice-manager') {
                $page_view = 'invoice-manager';
            } elseif ($requested_page === 'manfiet-invoice-create' || $hook === 'manfiet-invoice-manager_page_manfiet-invoice-create' || $hook === 'manfi-expense-tracker_page_manfiet-invoice-create') {
                $page_view = 'invoice-create';
            } elseif ($requested_page === 'manfiet-financial-accounts' || $hook === 'manfiet-invoice-manager_page_manfiet-financial-accounts' || $hook === 'manfi-expense-tracker_page_manfiet-financial-accounts') {
                $page_view = 'financial-accounts';
            } elseif ($requested_page === 'manfiet-financial-accounts-create' || $hook === 'manfiet-invoice-manager_page_manfiet-financial-accounts-create' || $hook === 'manfi-expense-tracker_page_manfiet-financial-accounts-create') {
                $page_view = 'financial-accounts-create';
            } elseif ($requested_page === 'manfiet-vendors' || $hook === 'manfiet-invoice-manager_page_manfiet-vendors' || $hook === 'manfi-expense-tracker_page_manfiet-vendors') {
                $page_view = 'vendors';
            } elseif ($requested_page === 'manfiet-vendors-create' || $hook === 'manfiet-invoice-manager_page_manfiet-vendors-create' || $hook === 'manfi-expense-tracker_page_manfiet-vendors-create') {
                $page_view = 'vendors-create';
            } elseif ($requested_page === 'manfiet-clients' || $hook === 'manfiet-invoice-manager_page_manfiet-clients' || $hook === 'manfi-expense-tracker_page_manfiet-clients') {
                $page_view = 'clients';
            } elseif ($requested_page === 'manfiet-clients-create' || $hook === 'manfiet-invoice-manager_page_manfiet-clients-create' || $hook === 'manfi-expense-tracker_page_manfiet-clients-create') {
                $page_view = 'clients-create';
            } elseif ($hook === 'expense-tracker_page_manfiet-expense-categories' || $hook === 'manfi-expense-tracker_page_manfiet-expense-categories') {
                $page_view = 'categories';
            } elseif ($hook === 'expense-tracker_page_manfiet-expense-tags' || $hook === 'manfi-expense-tracker_page_manfiet-expense-tags') {
                $page_view = 'tags';
            } elseif ($hook === 'expense-tracker_page_manfiet-expense-budget' || $hook === 'manfi-expense-tracker_page_manfiet-expense-budget') {
                $page_view = 'budget';
            } elseif ($hook === 'expense-tracker_page_manfiet-expense-reports' || $hook === 'manfi-expense-tracker_page_manfiet-expense-reports') {
                $page_view = 'reports';
            } elseif ($hook === 'expense-tracker_page_manfiet-expense-add' || $hook === 'manfi-expense-tracker_page_manfiet-expense-add' || $requested_page === 'manfiet-expense-add') {
                $page_view = 'add-expense';
            } elseif ($requested_page === 'manfiet-migration') {
                $page_view = 'migration';
            } elseif ($requested_page === 'manfiet-expense-settings') {
                $page_view = 'settings';
            }

            $admin_js_path = MANFIET_EXPENSE_TRACKER_PLUGIN_DIR . 'assets/js/admin.js';
            $admin_js_ver = file_exists($admin_js_path) ? filemtime($admin_js_path) : MANFIET_EXPENSE_TRACKER_VERSION;
            wp_enqueue_script(
                'manfiet-react-app',
                MANFIET_EXPENSE_TRACKER_PLUGIN_URL . 'assets/js/admin.js',
                ['wp-element'],
                $admin_js_ver,
                true
            );

            $admin_css_path = MANFIET_EXPENSE_TRACKER_PLUGIN_DIR . 'assets/css/admin.css';
            $admin_css_ver = file_exists($admin_css_path) ? filemtime($admin_css_path) : MANFIET_EXPENSE_TRACKER_VERSION;
            wp_enqueue_style(
                'manfiet-expense-admin-style',
                MANFIET_EXPENSE_TRACKER_PLUGIN_URL . 'assets/css/admin.css',
                [],
                $admin_css_ver
            );

            wp_localize_script('manfiet-react-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' => $page_view,
                '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'),
                'invoiceLateFeeEnabled' => (int) get_option('manfiet_invoice_late_fee_enabled', 1),
                'invoiceLateFeePct' => (float) get_option('manfiet_invoice_late_fee_pct', 5.0),
                'invoiceLateFeeType' => (string) get_option('manfiet_invoice_late_fee_type', 'percentage'),
                'invoiceDefaultTerms' => (string) get_option('manfiet_invoice_default_terms', "• Payment is due on or before the specified due date.\n• An overdue/late payment fee of {late_fee}% will apply to any unpaid balance after the due date.\n• Please mention the invoice number as reference when making payments."),
                'exportUrls' => [
                    'csv' => esc_url_raw(add_query_arg([
                        'action' => 'manfiet_export_csv',
                        '_wpnonce' => wp_create_nonce('manfiet_export_expenses'),
                    ], admin_url('admin-post.php'))),
                    'excel' => esc_url_raw(add_query_arg([
                        'action' => 'manfiet_export_excel',
                        '_wpnonce' => wp_create_nonce('manfiet_export_expenses'),
                    ], admin_url('admin-post.php'))),
                    'pdf' => esc_url_raw(add_query_arg([
                        'action' => 'manfiet_export_pdf',
                        '_wpnonce' => wp_create_nonce('manfiet_export_expenses'),
                    ], admin_url('admin-post.php'))),
                ],
                'rollbackNonce' => wp_create_nonce('manfiet_migration_rollback_nonce'),
                'rollbackUrl' => admin_url('admin-post.php'),
                'addExpenseUrl' => esc_url_raw(admin_url('admin.php?page=manfiet-add-expense')),
            ]);
        }
    }

    public function enqueue_google_fonts() {
        $fonts_url = 'https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap';
        wp_enqueue_style(
            'manfiet-google-fonts',
            $fonts_url,
            [],
            MANFIET_EXPENSE_TRACKER_VERSION
        );
    }

    public function enqueue_global_admin_styles() {
        wp_enqueue_style(
            'manfiet-admin-menu-icon',
            MANFIET_EXPENSE_TRACKER_PLUGIN_URL . 'assets/css/menu-icon.css',
            [],
            MANFIET_EXPENSE_TRACKER_VERSION
        );
    }
}
