<?php
namespace ComptaFlowPro\Admin;

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

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-by-meetempo') . '</h1>';
        echo '<p>' . esc_html__('This section will be available soon.', 'comptaflow-by-meetempo') . '</p>';
        echo '</div>';
    }

    /**
     * Render info page for VAT declarations based on regime
     */
    public static function renderVatFranchiseInfoPage(): void
    {
        $company_settings = get_option('comptaflow_company_settings', []);
        $vat_regime = $company_settings['vat_regime'] ?? 'FRANCHISE';
        
        echo '<div class="wrap">';
        
        if ($vat_regime === 'FRANCHISE') {
            // Franchise regime - no VAT declarations needed
            echo '<h1>' . esc_html__('VAT - Franchise Regime', 'comptaflow-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 under the VAT Franchise Regime', 'comptaflow-by-meetempo') . '</h2>';
            echo '<p>' . esc_html__('Therefore, you do not need to file VAT returns as long as your turnover does not exceed the legal thresholds.', 'comptaflow-by-meetempo') . '</p>';
            echo '<p>' . sprintf(
                /* translators: %s: link to settings page */
                esc_html__('To change your regime, go to %s.', 'comptaflow-by-meetempo'),
                '<a href="' . esc_url(admin_url('admin.php?page=comptaflow-settings')) . '" class="button-secondary">' . esc_html__('Settings', 'comptaflow-by-meetempo') . '</a>'
            ) . '</p>';
            echo '</div>';
            
            // Upsell for PRO features
            echo '<div class="notice notice-warning inline" style="padding: 15px; margin-top: 20px;">';
            echo '<p>' . sprintf(
                /* translators: %s: link to Pro page */
                esc_html__('Upgrade to %s for automatic threshold alerts and real-time tracking.', 'comptaflow-by-meetempo'),
                '<a href="https://comptaflow.meetempo.com" target="_blank"><strong>ComptaFlow Pro</strong></a>'
            ) . '</p>';
            echo '</div>';
        } else {
            // CA3 or CA12 regime - PRO feature
            $regime_label = ($vat_regime === 'CA3') ? 'CA3' : 'CA12';
            echo '<h1>' . esc_html__('VAT Declarations', 'comptaflow-by-meetempo') . ' - ' . esc_html($regime_label) . '</h1>';
            
            echo '<div class="notice notice-info inline" style="padding: 20px; margin-top: 20px;">';
            echo '<h2 style="margin-top:0;">📋 ' . esc_html__('VAT Declaration Management', 'comptaflow-by-meetempo') . '</h2>';
            echo '<p>' . sprintf(
                /* translators: %s: VAT regime name */
                esc_html__('You have selected the %s VAT regime in your settings.', 'comptaflow-by-meetempo'),
                '<strong>' . esc_html($regime_label) . '</strong>'
            ) . '</p>';
            echo '<p>' . esc_html__('Automatic VAT declaration management is a Pro feature.', 'comptaflow-by-meetempo') . '</p>';
            echo '</div>';
            
            // PRO upsell
            echo '<div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 30px; margin: 20px 0; border-radius: 12px;">';
            echo '<h3 style="color: white; margin-top: 0;">🚀 ' . esc_html__('ComptaFlow Pro - VAT Management', 'comptaflow-by-meetempo') . '</h3>';
            echo '<ul style="color: white; line-height: 2;">';
            if ($vat_regime === 'CA3') {
                echo '<li>✅ ' . esc_html__('Automatic CA3 monthly/quarterly calculation', 'comptaflow-by-meetempo') . '</li>';
                echo '<li>✅ ' . esc_html__('VAT collected vs deductible tracking', 'comptaflow-by-meetempo') . '</li>';
                echo '<li>✅ ' . esc_html__('Declaration history and reminders', 'comptaflow-by-meetempo') . '</li>';
            } else {
                echo '<li>✅ ' . esc_html__('Automatic CA12 annual calculation', 'comptaflow-by-meetempo') . '</li>';
                echo '<li>✅ ' . esc_html__('July and December installment management', 'comptaflow-by-meetempo') . '</li>';
                echo '<li>✅ ' . esc_html__('Year-end regularization', 'comptaflow-by-meetempo') . '</li>';
            }
            echo '<li>✅ ' . esc_html__('One-click payment recording', 'comptaflow-by-meetempo') . '</li>';
            echo '</ul>';
            echo '<p style="margin-top: 20px;"><a href="https://comptaflow.meetempo.com" target="_blank" class="button button-hero" style="background: white; color: #667eea; border: none;">' . esc_html__('Upgrade to Pro', 'comptaflow-by-meetempo') . ' →</a></p>';
            echo '</div>';
        }

        echo '</div>';
    }

    /**
     * Render info page for financial operations not applicable to sole proprietors
     */
    public static function renderFinancialsNotApplicable(): void
    {
        echo '<div class="wrap">';
        echo '<h1>' . esc_html__('Financial Operations', 'comptaflow-by-meetempo') . '</h1>';
        echo '<div class="notice notice-info inline" style="padding: 20px; margin-top: 20px;">';
        echo '<h2 style="margin-top:0;">' . esc_html__('Feature not applicable to your status', 'comptaflow-by-meetempo') . '</h2>';
        echo '<p>' . esc_html__('As a Sole Proprietor (Auto-Entrepreneur), you do not have share capital or partner current accounts in the strict sense.', 'comptaflow-by-meetempo') . '</p>';
        echo '<p>' . esc_html__('Personal contributions and withdrawals are managed via the Owner\'s Account (108).', 'comptaflow-by-meetempo') . '</p>';
        echo '<p><a href="' . esc_url(admin_url('admin.php?page=comptaflow-settings')) . '" class="button">' . esc_html__('Check my legal status', 'comptaflow-by-meetempo') . '</a></p>';
        echo '</div>';
        echo '</div>';
    }

    /**
     * Register all admin menus
     */
    public static function addMenus(): void
    {
        // Main menu
        add_menu_page(
            'ComptaFlow',
            'ComptaFlow',
            'manage_options',
            'comptaflow-pro',
            [DashboardScreen::class, 'render'],
            'dashicons-calculator',
            30
        );
        
        $company_settings = get_option('comptaflow_company_settings', []);
        $vat_regime = $company_settings['vat_regime'] ?? 'FRANCHISE';
        $legal_status = $company_settings['status'] ?? 'AE';

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

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

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

        // Financing - Depends on legal status
        $financial_screen_callback = ($legal_status !== 'AE') 
            ? [FinancialScreen::class, 'render'] 
            : [self::class, 'renderFinancialsNotApplicable'];
        add_submenu_page(
            'comptaflow-pro',
            __('Financial Operations', 'comptaflow-by-meetempo'),
            __('Financing', 'comptaflow-by-meetempo'),
            'manage_options',
            'comptaflow-financial',
            $financial_screen_callback
        );

        // Journal - Always accessible
        add_submenu_page(
            'comptaflow-pro',
            __('Journal', 'comptaflow-by-meetempo'),
            __('Journal', 'comptaflow-by-meetempo'),
            'manage_options',
            'comptaflow-journal',
            [JournalEntriesScreen::class, 'render']
        );
        
        // Manual entries - Always accessible
        add_submenu_page(
            'comptaflow-pro',
            __('Manual Journal Entries', 'comptaflow-by-meetempo'),
            '  └─ ' . __('Manual Entries', 'comptaflow-by-meetempo'),
            'manage_options',
            'comptaflow-journal-manual',
            [ManualJournalEntryScreen::class, 'render']
        );
        
        // Separator
        add_submenu_page(
            'comptaflow-pro',
            '── ' . __('VAT & Tax', 'comptaflow-by-meetempo') . ' ──',
            '── ' . __('VAT & Tax', 'comptaflow-by-meetempo') . ' ──',
            'manage_options',
            'comptaflow-separator-vat',
            '__return_false'
        );
        
        // VAT Info page (franchise regime info or upsell)
        add_submenu_page(
            'comptaflow-pro',
            __('VAT Declarations', 'comptaflow-by-meetempo'),
            '📋 ' . __('VAT Declarations', 'comptaflow-by-meetempo'),
            'manage_options',
            'comptaflow-vat-declarations',
            [self::class, 'renderVatFranchiseInfoPage']
        );
        
        // VAT Settings - Always accessible
        add_submenu_page(
            'comptaflow-pro',
            __('VAT Settings', 'comptaflow-by-meetempo'),
            '⚙️ ' . __('VAT Settings', 'comptaflow-by-meetempo'),
            'manage_options',
            'comptaflow-vat-settings',
            [VATSettingsScreen::class, 'render']
        );
        
        // Go Pro - Informational page
        add_submenu_page(
            'comptaflow-pro',
            __('Go Pro', 'comptaflow-by-meetempo'),
            '💎 ' . __('Go Pro', 'comptaflow-by-meetempo'),
            'manage_options',
            'comptaflow-plans',
            [PlanScreen::class, 'render']
        );
        
        // Settings - Always accessible
        add_submenu_page(
            'comptaflow-pro',
            __('Settings', 'comptaflow-by-meetempo'),
            __('Settings', 'comptaflow-by-meetempo'),
            'manage_options',
            'comptaflow-settings',
            [SettingsScreen::class, 'render']
        );
        
        // Exports - Always accessible
        add_submenu_page(
            'comptaflow-pro',
            __('Exports', 'comptaflow-by-meetempo'),
            __('Exports', 'comptaflow-by-meetempo'),
            'manage_options',
            'comptaflow-exports',
            [ExportScreen::class, 'render']
        );
        
        // Backup - Always accessible
        add_submenu_page(
            'comptaflow-pro',
            __('Backup & Restore', 'comptaflow-by-meetempo'),
            __('Backup', 'comptaflow-by-meetempo'),
            'manage_options',
            'comptaflow-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-admin',
            COMPTAFLOW_PLUGIN_URL . 'assets/css/admin.css',
            [],
            '1.0.3'
        );
        
        // Inline CSS for menu separators
        wp_add_inline_style(
            'comptaflow-admin',
            '#adminmenu .wp-submenu a[href*="comptaflow-separator"] { 
                background: #f0f0f1 !important; 
                color: #3c434a !important; 
                font-weight: 600; 
                cursor: default; 
                pointer-events: none; 
            } 
            #adminmenu .wp-submenu a[href*="comptaflow-vat-"] { 
                padding-left: 25px; 
            }'
        );
        
        // Global JS
        wp_enqueue_script(
            'comptaflow-admin',
            COMPTAFLOW_PLUGIN_URL . 'assets/js/admin.js',
            ['jquery'],
            '1.0.3',
            true
        );
        
        // Data for JS (chart of accounts)
        wp_localize_script('comptaflow-admin', 'comptaflow_data', [
            'accounts' => \ComptaFlowPro\Services\ChartOfAccounts::getAllAccounts(),
            'ajaxurl'  => admin_url('admin-ajax.php'),
        ]);
        
        // Invoices JS (only on invoices page)
        if (strpos($hook, 'comptaflow-invoices') !== false) {
            wp_enqueue_script(
                'comptaflow-invoices',
                COMPTAFLOW_PLUGIN_URL . 'assets/js/invoices.js',
                ['jquery'],
                '1.0.3',
                true
            );
        }

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

        // Export JS (only on exports page)
        if ($hook === 'comptaflow-pro_page_comptaflow-exports') {
            wp_enqueue_script(
                'comptaflow-export',
                plugins_url('assets/js/export.js', COMPTAFLOW_PLUGIN_FILE),
                [],
                '1.0.0',
                true
            );
            
            // Pass translations to JavaScript
            wp_localize_script('comptaflow-export', 'comptaflowExport', [
                'pleaseSelectPeriod' => __('Please select a period.', 'comptaflow-by-meetempo'),
            ]);
        }
    }
}
