<?php
namespace ComptaFlowUK\Admin;

use ComptaFlowUK\Admin\Screens\DashboardScreen;
use ComptaFlowUK\Admin\Screens\SalesScreen;
use ComptaFlowUK\Admin\Screens\ExpensesScreen;
use ComptaFlowUK\Admin\Screens\ManualJournalEntryScreen;
use ComptaFlowUK\Admin\Screens\JournalEntriesScreen;
use ComptaFlowUK\Admin\Screens\SettingsScreen;
use ComptaFlowUK\Admin\Screens\PlanScreen;
use ComptaFlowUK\Admin\Screens\FinancialScreen;
use ComptaFlowUK\Admin\Screens\ExportScreen;
use ComptaFlowUK\Admin\Screens\BackupScreen;
use ComptaFlowUK\Admin\Screens\VATSettingsScreen;
use ComptaFlowUK\Admin\Screens\ClientsScreen;
use ComptaFlowUK\Admin\Screens\InvoicesScreen;
use ComptaFlowUK\Admin\Screens\CreditNotesScreen;

defined('ABSPATH') || exit;

class Menu
{
    public static function register(): void
    {
        self::addMenus();
        add_action('admin_enqueue_scripts', [self::class, 'enqueueAssets']);
    }

    /**
     * Render placeholder for features in development
     */
    public static function renderPlaceholder(): void
    {
        echo '<div class="wrap">';
        echo '<h1>' . esc_html__('Feature in Development', 'comptaflow-uk-by-meetempo') . '</h1>';
        echo '<p>' . esc_html__('This section will be available soon.', 'comptaflow-uk-by-meetempo') . '</p>';
        echo '</div>';
    }

    /**
     * Render info page for VAT when not registered
     */
    public static function renderVatNotRegisteredInfoPage(): void
    {
        $company_settings = get_option('comptaflow_uk_company_settings', []);
        $vat_scheme = $company_settings['vat_scheme'] ?? 'NOT_REGISTERED';

        echo '<div class="wrap">';

        if ($vat_scheme === 'NOT_REGISTERED') {
            echo '<h1>' . esc_html__('VAT - Not Registered', 'comptaflow-uk-by-meetempo') . '</h1>';
            echo '<div class="notice notice-info inline" style="padding: 20px; margin-top: 20px;">';
            echo '<h2 style="margin-top:0;">' . esc_html__('You are not currently registered for VAT', 'comptaflow-uk-by-meetempo') . '</h2>';
            echo '<p>' . esc_html__('You do not need to submit VAT Returns unless your taxable turnover exceeds the registration threshold (currently £90,000).', 'comptaflow-uk-by-meetempo') . '</p>';
            echo '<p>' . sprintf(
                /* translators: %s: link to settings page */
                esc_html__('To change your VAT scheme, go to %s.', 'comptaflow-uk-by-meetempo'),
                '<a href="' . esc_url(admin_url('admin.php?page=comptaflow-uk-settings')) . '" class="button-secondary">' . esc_html__('Settings', 'comptaflow-uk-by-meetempo') . '</a>'
            ) . '</p>';
            echo '</div>';

        } else {
            // Registered — informational page about VAT Returns
            $scheme_label = str_replace('_', ' ', $vat_scheme);
            echo '<h1>' . esc_html__('VAT Returns', 'comptaflow-uk-by-meetempo') . ' - ' . esc_html($scheme_label) . '</h1>';

            echo '<div class="notice notice-info inline" style="padding: 20px; margin-top: 20px;">';
            echo '<h2 style="margin-top:0;">' . esc_html__('VAT Return Information', 'comptaflow-uk-by-meetempo') . '</h2>';
            echo '<p>' . sprintf(
                /* translators: %s: VAT scheme name */
                esc_html__('You have selected the %s VAT scheme in your settings.', 'comptaflow-uk-by-meetempo'),
                '<strong>' . esc_html($scheme_label) . '</strong>'
            ) . '</p>';
            echo '<p>' . esc_html__('ComptaFlow UK tracks your Output VAT and Input VAT automatically on every sale and expense you record. Use the Exports section to download your data and prepare your VAT Return.', 'comptaflow-uk-by-meetempo') . '</p>';
            echo '</div>';

            // Helpful guidance
            echo '<div class="notice notice-success inline" style="padding: 20px; margin-top: 20px;">';
            echo '<h3 style="margin-top:0;">' . esc_html__('How to file your VAT Return', 'comptaflow-uk-by-meetempo') . '</h3>';
            echo '<ol style="line-height: 2;">';
            echo '<li>' . esc_html__('Export your Audit Trail and Profit & Loss from the Exports page.', 'comptaflow-uk-by-meetempo') . '</li>';
            echo '<li>' . esc_html__('Review your Output VAT (collected on sales) and Input VAT (paid on purchases).', 'comptaflow-uk-by-meetempo') . '</li>';
            echo '<li>' . sprintf(
                /* translators: %s: link to HMRC */
                esc_html__('Submit your VAT Return via %s or through your accountant.', 'comptaflow-uk-by-meetempo'),
                '<a href="https://www.gov.uk/vat-returns" target="_blank" rel="noopener noreferrer">' . esc_html__('HMRC online services', 'comptaflow-uk-by-meetempo') . '</a>'
            ) . '</li>';
            echo '</ol>';
            echo '</div>';

            // Links
            echo '<div style="margin-top: 20px;">';
            echo '<a href="' . esc_url(admin_url('admin.php?page=comptaflow-uk-exports')) . '" class="button button-primary">' . esc_html__('Go to Exports', 'comptaflow-uk-by-meetempo') . '</a> ';
            echo '<a href="' . esc_url(admin_url('admin.php?page=comptaflow-uk-settings')) . '" class="button">' . esc_html__('VAT Settings', 'comptaflow-uk-by-meetempo') . '</a> ';
            echo '</div>';
        }

        echo '</div>';
    }

    /**
     * Render info page for financial operations not applicable to sole traders
     */
    public static function renderFinancialsNotApplicable(): void
    {
        echo '<div class="wrap">';
        echo '<h1>' . esc_html__('Financial Operations', 'comptaflow-uk-by-meetempo') . '</h1>';
        echo '<div class="notice notice-info inline" style="padding: 20px; margin-top: 20px;">';
        echo '<h2 style="margin-top:0;">' . esc_html__('Not applicable to your business type', 'comptaflow-uk-by-meetempo') . '</h2>';
        echo '<p>' . esc_html__('As a Sole Trader, you do not have share capital or a director\'s loan account.', 'comptaflow-uk-by-meetempo') . '</p>';
        echo '<p>' . esc_html__('Personal capital introduced and drawings are managed via the Capital Introduced (3000) / Drawings (3100) accounts.', 'comptaflow-uk-by-meetempo') . '</p>';
        echo '<p><a href="' . esc_url(admin_url('admin.php?page=comptaflow-uk-settings')) . '" class="button">' . esc_html__('Check my business type', 'comptaflow-uk-by-meetempo') . '</a></p>';
        echo '</div>';
        echo '</div>';
    }

    /**
     * Register all admin menus
     */
    public static function addMenus(): void
    {
        // Main menu
        add_menu_page(
            'ComptaFlow UK',
            'ComptaFlow UK',
            'manage_options',
            'comptaflow-uk-by-meetempo',
            [DashboardScreen::class, 'render'],
            'dashicons-calculator',
            30
        );

        $company_settings = get_option('comptaflow_uk_company_settings', []);
        $vat_scheme = $company_settings['vat_scheme'] ?? 'NOT_REGISTERED';
        $company_type = $company_settings['status'] ?? 'SOLE_TRADER';

        // Dashboard - Always accessible
        add_submenu_page(
            'comptaflow-uk-by-meetempo',
            __('Dashboard', 'comptaflow-uk-by-meetempo'),
            __('Dashboard', 'comptaflow-uk-by-meetempo'),
            'manage_options',
            'comptaflow-uk-by-meetempo',
            [DashboardScreen::class, 'render']
        );

        // Sales - Always accessible
        add_submenu_page(
            'comptaflow-uk-by-meetempo',
            __('Sales', 'comptaflow-uk-by-meetempo'),
            __('Sales', 'comptaflow-uk-by-meetempo'),
            'manage_options',
            'comptaflow-uk-sales',
            [SalesScreen::class, 'render']
        );

        // Expenses - Always accessible
        add_submenu_page(
            'comptaflow-uk-by-meetempo',
            __('Expenses', 'comptaflow-uk-by-meetempo'),
            __('Expenses', 'comptaflow-uk-by-meetempo'),
            'manage_options',
            'comptaflow-uk-expenses',
            [ExpensesScreen::class, 'render']
        );

        // Clients
        add_submenu_page(
            'comptaflow-uk-by-meetempo',
            __('Clients', 'comptaflow-uk-by-meetempo'),
            __('Clients', 'comptaflow-uk-by-meetempo'),
            'manage_options',
            'comptaflow-uk-clients',
            [ClientsScreen::class, 'render']
        );

        // Invoices
        add_submenu_page(
            'comptaflow-uk-by-meetempo',
            __('Invoices', 'comptaflow-uk-by-meetempo'),
            __('Invoices', 'comptaflow-uk-by-meetempo'),
            'manage_options',
            'comptaflow-uk-invoices',
            [InvoicesScreen::class, 'render']
        );

        // Credit Notes
        add_submenu_page(
            'comptaflow-uk-by-meetempo',
            __('Credit Notes', 'comptaflow-uk-by-meetempo'),
            __('Credit Notes', 'comptaflow-uk-by-meetempo'),
            'manage_options',
            'comptaflow-uk-credit-notes',
            [CreditNotesScreen::class, 'render']
        );

        // Financial Operations - Depends on company type
        $financial_screen_callback = ($company_type !== 'SOLE_TRADER')
            ? [FinancialScreen::class, 'render']
            : [self::class, 'renderFinancialsNotApplicable'];
        add_submenu_page(
            'comptaflow-uk-by-meetempo',
            __('Financial Operations', 'comptaflow-uk-by-meetempo'),
            __('Finance', 'comptaflow-uk-by-meetempo'),
            'manage_options',
            'comptaflow-uk-financial',
            $financial_screen_callback
        );

        // Journal - Always accessible
        add_submenu_page(
            'comptaflow-uk-by-meetempo',
            __('Journal', 'comptaflow-uk-by-meetempo'),
            __('Journal', 'comptaflow-uk-by-meetempo'),
            'manage_options',
            'comptaflow-uk-journal',
            [JournalEntriesScreen::class, 'render']
        );

        // Manual entries - Always accessible
        add_submenu_page(
            'comptaflow-uk-by-meetempo',
            __('Manual Journal Entries', 'comptaflow-uk-by-meetempo'),
            '  └─ ' . __('Manual Entries', 'comptaflow-uk-by-meetempo'),
            'manage_options',
            'comptaflow-uk-journal-manual',
            [ManualJournalEntryScreen::class, 'render']
        );

        // Separator - VAT & Tax
        add_submenu_page(
            'comptaflow-uk-by-meetempo',
            '── ' . __('VAT & Tax', 'comptaflow-uk-by-meetempo') . ' ──',
            '── ' . __('VAT & Tax', 'comptaflow-uk-by-meetempo') . ' ──',
            'manage_options',
            'comptaflow-uk-separator-vat',
            '__return_false'
        );

        // VAT Returns - Info page
        add_submenu_page(
            'comptaflow-uk-by-meetempo',
            __('VAT Returns', 'comptaflow-uk-by-meetempo'),
            '📋 ' . __('VAT Returns', 'comptaflow-uk-by-meetempo'),
            'manage_options',
            'comptaflow-uk-vat-returns',
            [self::class, 'renderVatNotRegisteredInfoPage']
        );

        // VAT Settings - Always accessible
        add_submenu_page(
            'comptaflow-uk-by-meetempo',
            __('VAT Settings', 'comptaflow-uk-by-meetempo'),
            '⚙️ ' . __('VAT Settings', 'comptaflow-uk-by-meetempo'),
            'manage_options',
            'comptaflow-uk-vat-settings',
            [VATSettingsScreen::class, 'render']
        );

        // Additional features - Informational page
        add_submenu_page(
            'comptaflow-uk-by-meetempo',
            __('More Features', 'comptaflow-uk-by-meetempo'),
            __('More Features', 'comptaflow-uk-by-meetempo'),
            'manage_options',
            'comptaflow-uk-plans',
            [PlanScreen::class, 'render']
        );

        // Settings - Always accessible
        add_submenu_page(
            'comptaflow-uk-by-meetempo',
            __('Settings', 'comptaflow-uk-by-meetempo'),
            __('Settings', 'comptaflow-uk-by-meetempo'),
            'manage_options',
            'comptaflow-uk-settings',
            [SettingsScreen::class, 'render']
        );

        // Exports - Always accessible
        add_submenu_page(
            'comptaflow-uk-by-meetempo',
            __('Exports', 'comptaflow-uk-by-meetempo'),
            __('Exports', 'comptaflow-uk-by-meetempo'),
            'manage_options',
            'comptaflow-uk-exports',
            [ExportScreen::class, 'render']
        );

        // Backup - Always accessible
        add_submenu_page(
            'comptaflow-uk-by-meetempo',
            __('Backup & Restore', 'comptaflow-uk-by-meetempo'),
            __('Backup', 'comptaflow-uk-by-meetempo'),
            'manage_options',
            'comptaflow-uk-backup',
            [BackupScreen::class, 'render']
        );
    }

    /**
     * Enqueue admin assets
     */
    public static function enqueueAssets($hook): void
    {
        if (strpos($hook, 'comptaflow') === false) {
            return;
        }

        // Global CSS
        wp_enqueue_style(
            'comptaflow-uk-admin',
            COMPTAFLOW_UK_PLUGIN_URL . 'assets/css/admin.css',
            [],
            '1.0.0'
        );

        // Inline CSS for menu separators
        wp_add_inline_style(
            'comptaflow-uk-admin',
            '#adminmenu .wp-submenu a[href*="comptaflow-uk-separator"] {
                background: #f0f0f1 !important;
                color: #3c434a !important;
                font-weight: 600;
                cursor: default;
                pointer-events: none;
            }
            #adminmenu .wp-submenu a[href*="comptaflow-uk-vat-"] {
                padding-left: 25px;
            }'
        );

        // Global JS
        wp_enqueue_script(
            'comptaflow-uk-admin',
            COMPTAFLOW_UK_PLUGIN_URL . 'assets/js/admin.js',
            ['jquery'],
            '1.0.0',
            true
        );

        // Data for JS (chart of accounts)
        wp_localize_script('comptaflow-uk-admin', 'comptaflow_uk_data', [
            'accounts' => \ComptaFlowUK\Services\ChartOfAccounts::getAllAccounts(),
            'ajaxurl'  => admin_url('admin-ajax.php'),
        ]);

        // Manual Journal JS (only on this page)
        if (strpos($hook, 'comptaflow-uk-journal-manual') !== false) {
            wp_enqueue_script(
                'comptaflow-uk-manual-journal',
                COMPTAFLOW_UK_PLUGIN_URL . 'assets/js/manual-journal.js',
                ['jquery'],
                '1.0.0',
                true
            );
        }

        // Financial JS (only on this page)
        if (strpos($hook, 'comptaflow-uk-financial') !== false) {
            wp_enqueue_script(
                'comptaflow-uk-financial',
                COMPTAFLOW_UK_PLUGIN_URL . 'assets/js/financial.js',
                ['jquery'],
                '1.0.0',
                true
            );
        }

        // Invoices JS (invoices and credit notes pages)
        if (strpos($hook, 'comptaflow-uk-invoices') !== false || strpos($hook, 'comptaflow-uk-credit-notes') !== false) {
            wp_enqueue_script(
                'comptaflow-uk-invoices',
                COMPTAFLOW_UK_PLUGIN_URL . 'assets/js/invoices.js',
                ['jquery'],
                '1.1.0',
                true
            );
        }

        // Export JS (only on exports page)
        if (strpos($hook, 'comptaflow-uk-exports') !== false) {
            wp_enqueue_script(
                'comptaflow-uk-export',
                plugins_url('assets/js/export.js', COMPTAFLOW_UK_PLUGIN_FILE),
                [],
                '1.0.0',
                true
            );
        }
    }
}
