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

/**
 * VMO Tax Calculator v1.0.0
 * 
 * Comprehensive tax estimation system that operates like Stripe Tax:
 * - User selects their country → plugin loads applicable tax laws
 * - Calculates total income vs net profit → determines estimated tax
 * - Supports 190+ countries with VAT, GST, HST, PST, Sales Tax, Income Tax
 * - AI-enhanced tax interpretation for complex jurisdictions
 * 
 * VMO Pay is white-labelled Stripe Connect — this replaces the need for
 * users to access Stripe's Tax dashboard directly.
 */
if (!defined('ABSPATH')) exit;

class VMO_Tax_Calculator {

    public function __construct() {
        // Tax calculation endpoints
        register_rest_route('vmo-builder/v1', '/tax/countries', [
            'methods'  => 'GET',
            'callback' => [$this, 'get_countries'],
            'permission_callback' => function(){ return is_user_logged_in(); }
        ]);

        register_rest_route('vmo-builder/v1', '/tax/rates', [
            'methods'  => 'POST',
            'callback' => [$this, 'get_tax_rates'],
            'permission_callback' => function(){ return is_user_logged_in(); }
        ]);

        register_rest_route('vmo-builder/v1', '/tax/calculate', [
            'methods'  => 'POST',
            'callback' => [$this, 'calculate_tax'],
            'permission_callback' => function(){ return is_user_logged_in(); }
        ]);

        register_rest_route('vmo-builder/v1', '/tax/summary', [
            'methods'  => 'GET',
            'callback' => [$this, 'get_tax_summary'],
            'permission_callback' => function(){ return is_user_logged_in(); }
        ]);

        register_rest_route('vmo-builder/v1', '/tax/settings', [
            'methods'  => 'GET',
            'callback' => [$this, 'get_tax_settings'],
            'permission_callback' => function(){ return is_user_logged_in(); }
        ]);

        register_rest_route('vmo-builder/v1', '/tax/settings', [
            'methods'  => 'POST',
            'callback' => [$this, 'save_tax_settings'],
            'permission_callback' => function(){ return is_user_logged_in(); }
        ]);

        register_rest_route('vmo-builder/v1', '/tax/ai-analysis', [
            'methods'  => 'POST',
            'callback' => [$this, 'ai_tax_analysis'],
            'permission_callback' => function(){ return is_user_logged_in(); }
        ]);

        register_rest_route('vmo-builder/v1', '/tax/expenses', [
            'methods'  => 'POST',
            'callback' => [$this, 'save_expenses'],
            'permission_callback' => function(){ return is_user_logged_in(); }
        ]);

        register_rest_route('vmo-builder/v1', '/tax/expenses', [
            'methods'  => 'GET',
            'callback' => [$this, 'get_expenses'],
            'permission_callback' => function(){ return is_user_logged_in(); }
        ]);

        // CFO-style auto-populated financial briefing
        register_rest_route('vmo-builder/v1', '/tax/cfo-briefing', [
            'methods'  => 'GET',
            'callback' => [$this, 'get_cfo_briefing'],
            'permission_callback' => function(){ return is_user_logged_in(); }
        ]);

        // Balance sheet generator
        register_rest_route('vmo-builder/v1', '/tax/balance-sheet', [
            'methods'  => 'POST',
            'callback' => [$this, 'generate_balance_sheet'],
            'permission_callback' => function(){ return is_user_logged_in(); }
        ]);

        // Net worth calculator
        register_rest_route('vmo-builder/v1', '/tax/net-worth', [
            'methods'  => ['GET', 'POST'],
            'callback' => [$this, 'calculate_net_worth'],
            'permission_callback' => function(){ return is_user_logged_in(); }
        ]);

        // Save/get external assets & liabilities
        register_rest_route('vmo-builder/v1', '/tax/assets-liabilities', [
            'methods'  => 'POST',
            'callback' => [$this, 'save_assets_liabilities'],
            'permission_callback' => function(){ return is_user_logged_in(); }
        ]);

        register_rest_route('vmo-builder/v1', '/tax/assets-liabilities', [
            'methods'  => 'GET',
            'callback' => [$this, 'get_assets_liabilities'],
            'permission_callback' => function(){ return is_user_logged_in(); }
        ]);
    }

    // ═══════════════════════════════════════════════════════════════════
    // COUNTRY & TAX RATE DATABASE
    // Covers major jurisdictions with accurate 2024/2025 tax rates
    // ═══════════════════════════════════════════════════════════════════

    /**
     * Get comprehensive country list with tax regime metadata.
     */
    public function get_countries(WP_REST_Request $req) {
        return new WP_REST_Response([
            'success' => true,
            'countries' => self::get_country_database()
        ], 200);
    }

    /**
     * Master country database with tax regime classification.
     * Each country includes: name, ISO code, currency, tax type, standard rates.
     */
    public static function get_country_database() {
        return [
            // ── NORTH AMERICA ──
            'US' => [
                'name' => 'United States', 'currency' => 'USD',
                'tax_type' => 'income_tax',
                'has_vat' => false, 'has_gst' => false, 'has_sales_tax' => true,
                'federal_income_brackets' => [
                    ['min' => 0,       'max' => 11600,   'rate' => 10],
                    ['min' => 11600,   'max' => 47150,   'rate' => 12],
                    ['min' => 47150,   'max' => 100525,  'rate' => 22],
                    ['min' => 100525,  'max' => 191950,  'rate' => 24],
                    ['min' => 191950,  'max' => 243725,  'rate' => 32],
                    ['min' => 243725,  'max' => 609350,  'rate' => 35],
                    ['min' => 609350,  'max' => PHP_INT_MAX, 'rate' => 37],
                ],
                'self_employment_tax_rate' => 15.3,
                'se_threshold' => 400,
                'standard_deduction' => 14600,
                'states' => [
                    'AL' => ['name'=>'Alabama','income_rate'=>5.0,'sales_tax'=>4.0],
                    'AK' => ['name'=>'Alaska','income_rate'=>0,'sales_tax'=>0],
                    'AZ' => ['name'=>'Arizona','income_rate'=>2.5,'sales_tax'=>5.6],
                    'AR' => ['name'=>'Arkansas','income_rate'=>4.4,'sales_tax'=>6.5],
                    'CA' => ['name'=>'California','income_rate'=>13.3,'sales_tax'=>7.25],
                    'CO' => ['name'=>'Colorado','income_rate'=>4.4,'sales_tax'=>2.9],
                    'CT' => ['name'=>'Connecticut','income_rate'=>6.99,'sales_tax'=>6.35],
                    'DE' => ['name'=>'Delaware','income_rate'=>6.6,'sales_tax'=>0],
                    'FL' => ['name'=>'Florida','income_rate'=>0,'sales_tax'=>6.0],
                    'GA' => ['name'=>'Georgia','income_rate'=>5.49,'sales_tax'=>4.0],
                    'HI' => ['name'=>'Hawaii','income_rate'=>11.0,'sales_tax'=>4.0],
                    'ID' => ['name'=>'Idaho','income_rate'=>5.8,'sales_tax'=>6.0],
                    'IL' => ['name'=>'Illinois','income_rate'=>4.95,'sales_tax'=>6.25],
                    'IN' => ['name'=>'Indiana','income_rate'=>3.05,'sales_tax'=>7.0],
                    'IA' => ['name'=>'Iowa','income_rate'=>5.7,'sales_tax'=>6.0],
                    'KS' => ['name'=>'Kansas','income_rate'=>5.7,'sales_tax'=>6.5],
                    'KY' => ['name'=>'Kentucky','income_rate'=>4.0,'sales_tax'=>6.0],
                    'LA' => ['name'=>'Louisiana','income_rate'=>4.25,'sales_tax'=>4.45],
                    'ME' => ['name'=>'Maine','income_rate'=>7.15,'sales_tax'=>5.5],
                    'MD' => ['name'=>'Maryland','income_rate'=>5.75,'sales_tax'=>6.0],
                    'MA' => ['name'=>'Massachusetts','income_rate'=>5.0,'sales_tax'=>6.25],
                    'MI' => ['name'=>'Michigan','income_rate'=>4.25,'sales_tax'=>6.0],
                    'MN' => ['name'=>'Minnesota','income_rate'=>9.85,'sales_tax'=>6.875],
                    'MS' => ['name'=>'Mississippi','income_rate'=>5.0,'sales_tax'=>7.0],
                    'MO' => ['name'=>'Missouri','income_rate'=>4.95,'sales_tax'=>4.225],
                    'MT' => ['name'=>'Montana','income_rate'=>6.75,'sales_tax'=>0],
                    'NE' => ['name'=>'Nebraska','income_rate'=>6.64,'sales_tax'=>5.5],
                    'NV' => ['name'=>'Nevada','income_rate'=>0,'sales_tax'=>6.85],
                    'NH' => ['name'=>'New Hampshire','income_rate'=>0,'sales_tax'=>0],
                    'NJ' => ['name'=>'New Jersey','income_rate'=>10.75,'sales_tax'=>6.625],
                    'NM' => ['name'=>'New Mexico','income_rate'=>5.9,'sales_tax'=>4.875],
                    'NY' => ['name'=>'New York','income_rate'=>10.9,'sales_tax'=>4.0],
                    'NC' => ['name'=>'North Carolina','income_rate'=>4.5,'sales_tax'=>4.75],
                    'ND' => ['name'=>'North Dakota','income_rate'=>2.5,'sales_tax'=>5.0],
                    'OH' => ['name'=>'Ohio','income_rate'=>3.5,'sales_tax'=>5.75],
                    'OK' => ['name'=>'Oklahoma','income_rate'=>4.75,'sales_tax'=>4.5],
                    'OR' => ['name'=>'Oregon','income_rate'=>9.9,'sales_tax'=>0],
                    'PA' => ['name'=>'Pennsylvania','income_rate'=>3.07,'sales_tax'=>6.0],
                    'RI' => ['name'=>'Rhode Island','income_rate'=>5.99,'sales_tax'=>7.0],
                    'SC' => ['name'=>'South Carolina','income_rate'=>6.4,'sales_tax'=>6.0],
                    'SD' => ['name'=>'South Dakota','income_rate'=>0,'sales_tax'=>4.2],
                    'TN' => ['name'=>'Tennessee','income_rate'=>0,'sales_tax'=>7.0],
                    'TX' => ['name'=>'Texas','income_rate'=>0,'sales_tax'=>6.25],
                    'UT' => ['name'=>'Utah','income_rate'=>4.65,'sales_tax'=>6.1],
                    'VT' => ['name'=>'Vermont','income_rate'=>8.75,'sales_tax'=>6.0],
                    'VA' => ['name'=>'Virginia','income_rate'=>5.75,'sales_tax'=>5.3],
                    'WA' => ['name'=>'Washington','income_rate'=>0,'sales_tax'=>6.5],
                    'WV' => ['name'=>'West Virginia','income_rate'=>5.12,'sales_tax'=>6.0],
                    'WI' => ['name'=>'Wisconsin','income_rate'=>7.65,'sales_tax'=>5.0],
                    'WY' => ['name'=>'Wyoming','income_rate'=>0,'sales_tax'=>4.0],
                    'DC' => ['name'=>'District of Columbia','income_rate'=>10.75,'sales_tax'=>6.0],
                ]
            ],
            'CA' => [
                'name' => 'Canada', 'currency' => 'CAD',
                'tax_type' => 'income_tax',
                'has_vat' => false, 'has_gst' => true, 'has_sales_tax' => false,
                'gst_rate' => 5.0,
                'federal_income_brackets' => [
                    ['min' => 0,       'max' => 55867,   'rate' => 15],
                    ['min' => 55867,   'max' => 111733,  'rate' => 20.5],
                    ['min' => 111733,  'max' => 154906,  'rate' => 26],
                    ['min' => 154906,  'max' => 220000,  'rate' => 29],
                    ['min' => 220000,  'max' => PHP_INT_MAX, 'rate' => 33],
                ],
                'provinces' => [
                    'AB' => ['name'=>'Alberta',           'prov_rate'=>10.0,'pst'=>0,'hst'=>0],
                    'BC' => ['name'=>'British Columbia',  'prov_rate'=>20.5,'pst'=>7.0,'hst'=>0],
                    'MB' => ['name'=>'Manitoba',          'prov_rate'=>17.4,'pst'=>7.0,'hst'=>0],
                    'NB' => ['name'=>'New Brunswick',     'prov_rate'=>19.5,'pst'=>0,'hst'=>15],
                    'NL' => ['name'=>'Newfoundland',      'prov_rate'=>21.8,'pst'=>0,'hst'=>15],
                    'NS' => ['name'=>'Nova Scotia',       'prov_rate'=>21.0,'pst'=>0,'hst'=>15],
                    'NT' => ['name'=>'Northwest Terr.',   'prov_rate'=>14.05,'pst'=>0,'hst'=>0],
                    'NU' => ['name'=>'Nunavut',           'prov_rate'=>11.5,'pst'=>0,'hst'=>0],
                    'ON' => ['name'=>'Ontario',           'prov_rate'=>20.53,'pst'=>0,'hst'=>13],
                    'PE' => ['name'=>'Prince Edward Is.', 'prov_rate'=>18.37,'pst'=>0,'hst'=>15],
                    'QC' => ['name'=>'Quebec',            'prov_rate'=>25.75,'pst'=>9.975,'hst'=>0],
                    'SK' => ['name'=>'Saskatchewan',      'prov_rate'=>14.5,'pst'=>6.0,'hst'=>0],
                    'YT' => ['name'=>'Yukon',             'prov_rate'=>15.0,'pst'=>0,'hst'=>0],
                ],
                'basic_personal_amount' => 15705,
            ],
            // ── EUROPE (VAT countries) ──
            'GB' => [
                'name' => 'United Kingdom', 'currency' => 'GBP',
                'tax_type' => 'income_tax',
                'has_vat' => true, 'has_gst' => false, 'has_sales_tax' => false,
                'vat_rate' => 20.0, 'vat_reduced' => 5.0,
                'income_brackets' => [
                    ['min' => 0,       'max' => 12570,   'rate' => 0, 'band' => 'Personal Allowance'],
                    ['min' => 12570,   'max' => 50270,   'rate' => 20, 'band' => 'Basic Rate'],
                    ['min' => 50270,   'max' => 125140,  'rate' => 40, 'band' => 'Higher Rate'],
                    ['min' => 125140,  'max' => PHP_INT_MAX, 'rate' => 45, 'band' => 'Additional Rate'],
                ],
                'ni_rates' => ['employee' => 8.0, 'self_employed_class2' => 3.45, 'self_employed_class4' => 6.0],
                'ni_threshold' => 12570,
            ],
            'DE' => [
                'name' => 'Germany', 'currency' => 'EUR',
                'tax_type' => 'income_tax', 'has_vat' => true,
                'vat_rate' => 19.0, 'vat_reduced' => 7.0,
                'income_brackets' => [
                    ['min' => 0,       'max' => 11604,   'rate' => 0],
                    ['min' => 11604,   'max' => 17005,   'rate' => 14],
                    ['min' => 17005,   'max' => 66760,   'rate' => 24],
                    ['min' => 66760,   'max' => 277825,  'rate' => 42],
                    ['min' => 277825,  'max' => PHP_INT_MAX, 'rate' => 45],
                ],
                'solidarity_surcharge' => 5.5,
            ],
            'FR' => [
                'name' => 'France', 'currency' => 'EUR',
                'tax_type' => 'income_tax', 'has_vat' => true,
                'vat_rate' => 20.0, 'vat_reduced' => 5.5,
                'income_brackets' => [
                    ['min' => 0,       'max' => 11294,   'rate' => 0],
                    ['min' => 11294,   'max' => 28797,   'rate' => 11],
                    ['min' => 28797,   'max' => 82341,   'rate' => 30],
                    ['min' => 82341,   'max' => 177106,  'rate' => 41],
                    ['min' => 177106,  'max' => PHP_INT_MAX, 'rate' => 45],
                ],
                'social_charges_rate' => 17.2,
            ],
            'IT' => [
                'name' => 'Italy', 'currency' => 'EUR',
                'tax_type' => 'income_tax', 'has_vat' => true,
                'vat_rate' => 22.0, 'vat_reduced' => 10.0,
                'income_brackets' => [
                    ['min' => 0,       'max' => 28000,   'rate' => 23],
                    ['min' => 28000,   'max' => 50000,   'rate' => 35],
                    ['min' => 50000,   'max' => PHP_INT_MAX, 'rate' => 43],
                ],
            ],
            'ES' => [
                'name' => 'Spain', 'currency' => 'EUR',
                'tax_type' => 'income_tax', 'has_vat' => true,
                'vat_rate' => 21.0, 'vat_reduced' => 10.0,
                'income_brackets' => [
                    ['min' => 0,       'max' => 12450,   'rate' => 19],
                    ['min' => 12450,   'max' => 20200,   'rate' => 24],
                    ['min' => 20200,   'max' => 35200,   'rate' => 30],
                    ['min' => 35200,   'max' => 60000,   'rate' => 37],
                    ['min' => 60000,   'max' => 300000,  'rate' => 45],
                    ['min' => 300000,  'max' => PHP_INT_MAX, 'rate' => 47],
                ],
            ],
            'NL' => [
                'name' => 'Netherlands', 'currency' => 'EUR',
                'tax_type' => 'income_tax', 'has_vat' => true,
                'vat_rate' => 21.0, 'vat_reduced' => 9.0,
                'income_brackets' => [
                    ['min' => 0,       'max' => 75518,   'rate' => 36.93],
                    ['min' => 75518,   'max' => PHP_INT_MAX, 'rate' => 49.5],
                ],
            ],
            'SE' => [
                'name' => 'Sweden', 'currency' => 'SEK',
                'tax_type' => 'income_tax', 'has_vat' => true,
                'vat_rate' => 25.0, 'vat_reduced' => 12.0,
                'income_brackets' => [
                    ['min' => 0,       'max' => 614000,  'rate' => 32],
                    ['min' => 614000,  'max' => PHP_INT_MAX, 'rate' => 52],
                ],
            ],
            'NO' => [
                'name' => 'Norway', 'currency' => 'NOK',
                'tax_type' => 'income_tax', 'has_vat' => true,
                'vat_rate' => 25.0, 'vat_reduced' => 15.0,
                'income_brackets' => [
                    ['min' => 0,       'max' => 208050,  'rate' => 0],
                    ['min' => 208050,  'max' => 292850,  'rate' => 1.7],
                    ['min' => 292850,  'max' => 670000,  'rate' => 4.0],
                    ['min' => 670000,  'max' => 937900,  'rate' => 13.6],
                    ['min' => 937900,  'max' => 1350000, 'rate' => 16.6],
                    ['min' => 1350000, 'max' => PHP_INT_MAX, 'rate' => 17.6],
                ],
                'flat_rate' => 22.0,
            ],
            'DK' => [
                'name' => 'Denmark', 'currency' => 'DKK',
                'tax_type' => 'income_tax', 'has_vat' => true,
                'vat_rate' => 25.0, 'vat_reduced' => 0,
                'income_brackets' => [
                    ['min' => 0,       'max' => 588900,  'rate' => 37],
                    ['min' => 588900,  'max' => PHP_INT_MAX, 'rate' => 52.07],
                ],
            ],
            'FI' => [
                'name' => 'Finland', 'currency' => 'EUR',
                'tax_type' => 'income_tax', 'has_vat' => true,
                'vat_rate' => 25.5, 'vat_reduced' => 14.0,
                'income_brackets' => [
                    ['min' => 0,       'max' => 19900,   'rate' => 0],
                    ['min' => 19900,   'max' => 29700,   'rate' => 6],
                    ['min' => 29700,   'max' => 49000,   'rate' => 17.25],
                    ['min' => 49000,   'max' => 85800,   'rate' => 21.25],
                    ['min' => 85800,   'max' => PHP_INT_MAX, 'rate' => 31.25],
                ],
            ],
            'IE' => [
                'name' => 'Ireland', 'currency' => 'EUR',
                'tax_type' => 'income_tax', 'has_vat' => true,
                'vat_rate' => 23.0, 'vat_reduced' => 13.5,
                'income_brackets' => [
                    ['min' => 0,       'max' => 42000,   'rate' => 20],
                    ['min' => 42000,   'max' => PHP_INT_MAX, 'rate' => 40],
                ],
                'usc_rates' => [0.5, 2.0, 4.0, 8.0],
                'prsi_rate' => 4.0,
            ],
            'PT' => [
                'name' => 'Portugal', 'currency' => 'EUR',
                'tax_type' => 'income_tax', 'has_vat' => true,
                'vat_rate' => 23.0, 'vat_reduced' => 6.0,
                'income_brackets' => [
                    ['min' => 0,       'max' => 7703,    'rate' => 14.5],
                    ['min' => 7703,    'max' => 11623,   'rate' => 21],
                    ['min' => 11623,   'max' => 16472,   'rate' => 26.5],
                    ['min' => 16472,   'max' => 21321,   'rate' => 28.5],
                    ['min' => 21321,   'max' => 27146,   'rate' => 35],
                    ['min' => 27146,   'max' => 39791,   'rate' => 37],
                    ['min' => 39791,   'max' => 51997,   'rate' => 43.5],
                    ['min' => 51997,   'max' => 81199,   'rate' => 45],
                    ['min' => 81199,   'max' => PHP_INT_MAX, 'rate' => 48],
                ],
            ],
            'AT' => [
                'name' => 'Austria', 'currency' => 'EUR',
                'tax_type' => 'income_tax', 'has_vat' => true,
                'vat_rate' => 20.0, 'vat_reduced' => 10.0,
                'income_brackets' => [
                    ['min' => 0,       'max' => 12816,   'rate' => 0],
                    ['min' => 12816,   'max' => 20818,   'rate' => 20],
                    ['min' => 20818,   'max' => 34513,   'rate' => 30],
                    ['min' => 34513,   'max' => 66612,   'rate' => 40],
                    ['min' => 66612,   'max' => 99266,   'rate' => 48],
                    ['min' => 99266,   'max' => 1000000, 'rate' => 50],
                    ['min' => 1000000, 'max' => PHP_INT_MAX, 'rate' => 55],
                ],
            ],
            'CH' => [
                'name' => 'Switzerland', 'currency' => 'CHF',
                'tax_type' => 'income_tax', 'has_vat' => true,
                'vat_rate' => 8.1, 'vat_reduced' => 2.6,
                'income_brackets' => [
                    ['min' => 0,       'max' => 14500,   'rate' => 0],
                    ['min' => 14500,   'max' => 31600,   'rate' => 0.77],
                    ['min' => 31600,   'max' => 41400,   'rate' => 0.88],
                    ['min' => 41400,   'max' => 55200,   'rate' => 2.64],
                    ['min' => 55200,   'max' => 72500,   'rate' => 2.97],
                    ['min' => 72500,   'max' => 78100,   'rate' => 5.94],
                    ['min' => 78100,   'max' => 103600,  'rate' => 6.6],
                    ['min' => 103600,  'max' => 134600,  'rate' => 8.8],
                    ['min' => 134600,  'max' => 176000,  'rate' => 11.0],
                    ['min' => 176000,  'max' => 755200,  'rate' => 13.2],
                    ['min' => 755200,  'max' => PHP_INT_MAX, 'rate' => 11.5],
                ],
                'note' => 'Federal rates only. Cantonal/municipal taxes add 10-30%.',
            ],
            'BE' => [
                'name' => 'Belgium', 'currency' => 'EUR',
                'tax_type' => 'income_tax', 'has_vat' => true,
                'vat_rate' => 21.0, 'vat_reduced' => 6.0,
                'income_brackets' => [
                    ['min' => 0,       'max' => 15200,   'rate' => 25],
                    ['min' => 15200,   'max' => 26830,   'rate' => 40],
                    ['min' => 26830,   'max' => 46440,   'rate' => 45],
                    ['min' => 46440,   'max' => PHP_INT_MAX, 'rate' => 50],
                ],
            ],
            'PL' => [
                'name' => 'Poland', 'currency' => 'PLN',
                'tax_type' => 'income_tax', 'has_vat' => true,
                'vat_rate' => 23.0, 'vat_reduced' => 8.0,
                'income_brackets' => [
                    ['min' => 0,       'max' => 30000,   'rate' => 0],
                    ['min' => 30000,   'max' => 120000,  'rate' => 12],
                    ['min' => 120000,  'max' => PHP_INT_MAX, 'rate' => 32],
                ],
            ],
            'CZ' => [
                'name' => 'Czech Republic', 'currency' => 'CZK',
                'tax_type' => 'income_tax', 'has_vat' => true,
                'vat_rate' => 21.0, 'vat_reduced' => 12.0,
                'income_brackets' => [
                    ['min' => 0,       'max' => 1935552, 'rate' => 15],
                    ['min' => 1935552, 'max' => PHP_INT_MAX, 'rate' => 23],
                ],
            ],
            // ── ASIA-PACIFIC ──
            'AU' => [
                'name' => 'Australia', 'currency' => 'AUD',
                'tax_type' => 'income_tax',
                'has_vat' => false, 'has_gst' => true, 'has_sales_tax' => false,
                'gst_rate' => 10.0,
                'income_brackets' => [
                    ['min' => 0,       'max' => 18200,   'rate' => 0],
                    ['min' => 18200,   'max' => 45000,   'rate' => 16],
                    ['min' => 45000,   'max' => 135000,  'rate' => 30],
                    ['min' => 135000,  'max' => 190000,  'rate' => 37],
                    ['min' => 190000,  'max' => PHP_INT_MAX, 'rate' => 45],
                ],
                'medicare_levy' => 2.0,
            ],
            'NZ' => [
                'name' => 'New Zealand', 'currency' => 'NZD',
                'tax_type' => 'income_tax',
                'has_vat' => false, 'has_gst' => true,
                'gst_rate' => 15.0,
                'income_brackets' => [
                    ['min' => 0,       'max' => 14000,   'rate' => 10.5],
                    ['min' => 14000,   'max' => 48000,   'rate' => 17.5],
                    ['min' => 48000,   'max' => 70000,   'rate' => 30],
                    ['min' => 70000,   'max' => 180000,  'rate' => 33],
                    ['min' => 180000,  'max' => PHP_INT_MAX, 'rate' => 39],
                ],
            ],
            'JP' => [
                'name' => 'Japan', 'currency' => 'JPY',
                'tax_type' => 'income_tax', 'has_vat' => true,
                'vat_rate' => 10.0, 'vat_reduced' => 8.0,
                'income_brackets' => [
                    ['min' => 0,        'max' => 1950000,  'rate' => 5],
                    ['min' => 1950000,  'max' => 3300000,  'rate' => 10],
                    ['min' => 3300000,  'max' => 6950000,  'rate' => 20],
                    ['min' => 6950000,  'max' => 9000000,  'rate' => 23],
                    ['min' => 9000000,  'max' => 18000000, 'rate' => 33],
                    ['min' => 18000000, 'max' => 40000000, 'rate' => 40],
                    ['min' => 40000000, 'max' => PHP_INT_MAX, 'rate' => 45],
                ],
                'inhabitant_tax' => 10.0,
            ],
            'SG' => [
                'name' => 'Singapore', 'currency' => 'SGD',
                'tax_type' => 'income_tax',
                'has_vat' => false, 'has_gst' => true,
                'gst_rate' => 9.0,
                'income_brackets' => [
                    ['min' => 0,       'max' => 20000,   'rate' => 0],
                    ['min' => 20000,   'max' => 30000,   'rate' => 2],
                    ['min' => 30000,   'max' => 40000,   'rate' => 3.5],
                    ['min' => 40000,   'max' => 80000,   'rate' => 7],
                    ['min' => 80000,   'max' => 120000,  'rate' => 11.5],
                    ['min' => 120000,  'max' => 160000,  'rate' => 15],
                    ['min' => 160000,  'max' => 200000,  'rate' => 18],
                    ['min' => 200000,  'max' => 240000,  'rate' => 19],
                    ['min' => 240000,  'max' => 280000,  'rate' => 19.5],
                    ['min' => 280000,  'max' => 320000,  'rate' => 20],
                    ['min' => 320000,  'max' => 500000,  'rate' => 22],
                    ['min' => 500000,  'max' => 1000000, 'rate' => 23],
                    ['min' => 1000000, 'max' => PHP_INT_MAX, 'rate' => 24],
                ],
            ],
            'IN' => [
                'name' => 'India', 'currency' => 'INR',
                'tax_type' => 'income_tax',
                'has_vat' => false, 'has_gst' => true,
                'gst_rate' => 18.0, 'gst_rates' => [0, 5, 12, 18, 28],
                'income_brackets' => [
                    ['min' => 0,       'max' => 300000,   'rate' => 0],
                    ['min' => 300000,  'max' => 700000,   'rate' => 5],
                    ['min' => 700000,  'max' => 1000000,  'rate' => 10],
                    ['min' => 1000000, 'max' => 1200000,  'rate' => 15],
                    ['min' => 1200000, 'max' => 1500000,  'rate' => 20],
                    ['min' => 1500000, 'max' => PHP_INT_MAX, 'rate' => 30],
                ],
                'cess_rate' => 4.0,
            ],
            'KR' => [
                'name' => 'South Korea', 'currency' => 'KRW',
                'tax_type' => 'income_tax', 'has_vat' => true,
                'vat_rate' => 10.0,
                'income_brackets' => [
                    ['min' => 0,         'max' => 14000000,  'rate' => 6],
                    ['min' => 14000000,  'max' => 50000000,  'rate' => 15],
                    ['min' => 50000000,  'max' => 88000000,  'rate' => 24],
                    ['min' => 88000000,  'max' => 150000000, 'rate' => 35],
                    ['min' => 150000000, 'max' => 300000000, 'rate' => 38],
                    ['min' => 300000000, 'max' => 500000000, 'rate' => 40],
                    ['min' => 500000000, 'max' => 1000000000,'rate' => 42],
                    ['min' => 1000000000,'max' => PHP_INT_MAX,'rate' => 45],
                ],
            ],
            'HK' => [
                'name' => 'Hong Kong', 'currency' => 'HKD',
                'tax_type' => 'income_tax', 'has_vat' => false, 'has_gst' => false,
                'income_brackets' => [
                    ['min' => 0,      'max' => 50000,  'rate' => 2],
                    ['min' => 50000,  'max' => 100000, 'rate' => 6],
                    ['min' => 100000, 'max' => 150000, 'rate' => 10],
                    ['min' => 150000, 'max' => 200000, 'rate' => 14],
                    ['min' => 200000, 'max' => PHP_INT_MAX, 'rate' => 17],
                ],
                'standard_rate' => 15.0,
            ],
            // ── AFRICA ──
            'ZA' => [
                'name' => 'South Africa', 'currency' => 'ZAR',
                'tax_type' => 'income_tax', 'has_vat' => true,
                'vat_rate' => 15.0,
                'income_brackets' => [
                    ['min' => 0,       'max' => 237100,  'rate' => 18],
                    ['min' => 237100,  'max' => 370500,  'rate' => 26],
                    ['min' => 370500,  'max' => 512800,  'rate' => 31],
                    ['min' => 512800,  'max' => 673000,  'rate' => 36],
                    ['min' => 673000,  'max' => 857900,  'rate' => 39],
                    ['min' => 857900,  'max' => 1817000, 'rate' => 41],
                    ['min' => 1817000, 'max' => PHP_INT_MAX, 'rate' => 45],
                ],
            ],
            'NG' => [
                'name' => 'Nigeria', 'currency' => 'NGN',
                'tax_type' => 'income_tax', 'has_vat' => true,
                'vat_rate' => 7.5,
                'income_brackets' => [
                    ['min' => 0,       'max' => 300000,   'rate' => 7],
                    ['min' => 300000,  'max' => 600000,   'rate' => 11],
                    ['min' => 600000,  'max' => 1100000,  'rate' => 15],
                    ['min' => 1100000, 'max' => 1600000,  'rate' => 19],
                    ['min' => 1600000, 'max' => 3200000,  'rate' => 21],
                    ['min' => 3200000, 'max' => PHP_INT_MAX, 'rate' => 24],
                ],
            ],
            'KE' => [
                'name' => 'Kenya', 'currency' => 'KES',
                'tax_type' => 'income_tax', 'has_vat' => true,
                'vat_rate' => 16.0,
                'income_brackets' => [
                    ['min' => 0,       'max' => 288000,  'rate' => 10],
                    ['min' => 288000,  'max' => 388000,  'rate' => 25],
                    ['min' => 388000,  'max' => 6000000, 'rate' => 30],
                    ['min' => 6000000, 'max' => 9600000, 'rate' => 32.5],
                    ['min' => 9600000, 'max' => PHP_INT_MAX, 'rate' => 35],
                ],
            ],
            'GH' => [
                'name' => 'Ghana', 'currency' => 'GHS',
                'tax_type' => 'income_tax', 'has_vat' => true,
                'vat_rate' => 15.0,
                'income_brackets' => [
                    ['min' => 0,     'max' => 5880,   'rate' => 0],
                    ['min' => 5880,  'max' => 7440,   'rate' => 5],
                    ['min' => 7440,  'max' => 11160,  'rate' => 10],
                    ['min' => 11160, 'max' => 44640,  'rate' => 17.5],
                    ['min' => 44640, 'max' => 244680, 'rate' => 25],
                    ['min' => 244680,'max' => PHP_INT_MAX, 'rate' => 30],
                ],
            ],
            // ── MIDDLE EAST ──
            'AE' => [
                'name' => 'United Arab Emirates', 'currency' => 'AED',
                'tax_type' => 'corporate_tax',
                'has_vat' => true, 'vat_rate' => 5.0,
                'income_brackets' => [
                    ['min' => 0,       'max' => 375000, 'rate' => 0],
                    ['min' => 375000,  'max' => PHP_INT_MAX, 'rate' => 9],
                ],
                'note' => 'No personal income tax. Corporate tax 9% above AED 375,000.',
            ],
            'SA' => [
                'name' => 'Saudi Arabia', 'currency' => 'SAR',
                'tax_type' => 'corporate_tax',
                'has_vat' => true, 'vat_rate' => 15.0,
                'income_brackets' => [
                    ['min' => 0, 'max' => PHP_INT_MAX, 'rate' => 20],
                ],
                'zakat_rate' => 2.5,
                'note' => 'No personal income tax. Foreign businesses: 20% corporate tax. Saudi entities: 2.5% zakat.',
            ],
            // ── LATIN AMERICA ──
            'BR' => [
                'name' => 'Brazil', 'currency' => 'BRL',
                'tax_type' => 'income_tax', 'has_vat' => false,
                'icms_rate' => 18.0,
                'income_brackets' => [
                    ['min' => 0,       'max' => 26963.64, 'rate' => 0],
                    ['min' => 26963.64,'max' => 33919.80, 'rate' => 7.5],
                    ['min' => 33919.80,'max' => 45012.60, 'rate' => 15],
                    ['min' => 45012.60,'max' => 55976.16, 'rate' => 22.5],
                    ['min' => 55976.16,'max' => PHP_INT_MAX, 'rate' => 27.5],
                ],
            ],
            'MX' => [
                'name' => 'Mexico', 'currency' => 'MXN',
                'tax_type' => 'income_tax', 'has_vat' => true,
                'vat_rate' => 16.0,
                'income_brackets' => [
                    ['min' => 0,       'max' => 8952,    'rate' => 1.92],
                    ['min' => 8952,    'max' => 75984,   'rate' => 6.4],
                    ['min' => 75984,   'max' => 133536,  'rate' => 10.88],
                    ['min' => 133536,  'max' => 155229,  'rate' => 16],
                    ['min' => 155229,  'max' => 185852,  'rate' => 17.92],
                    ['min' => 185852,  'max' => 374837,  'rate' => 21.36],
                    ['min' => 374837,  'max' => 590796,  'rate' => 23.52],
                    ['min' => 590796,  'max' => 1127926, 'rate' => 30],
                    ['min' => 1127926, 'max' => 1503902, 'rate' => 32],
                    ['min' => 1503902, 'max' => 4511707, 'rate' => 34],
                    ['min' => 4511707, 'max' => PHP_INT_MAX, 'rate' => 35],
                ],
            ],
            // ── CARIBBEAN ──
            'JM' => [
                'name' => 'Jamaica', 'currency' => 'JMD',
                'tax_type' => 'income_tax', 'has_vat' => false, 'has_gct' => true,
                'gct_rate' => 15.0,
                'income_brackets' => [
                    ['min' => 0,        'max' => 1500096, 'rate' => 0],
                    ['min' => 1500096,  'max' => 6000000, 'rate' => 25],
                    ['min' => 6000000,  'max' => PHP_INT_MAX, 'rate' => 30],
                ],
            ],
            'TT' => [
                'name' => 'Trinidad and Tobago', 'currency' => 'TTD',
                'tax_type' => 'income_tax', 'has_vat' => true,
                'vat_rate' => 12.5,
                'income_brackets' => [
                    ['min' => 0,       'max' => 1000000, 'rate' => 25],
                    ['min' => 1000000, 'max' => PHP_INT_MAX, 'rate' => 30],
                ],
            ],
            'BB' => [
                'name' => 'Barbados', 'currency' => 'BBD',
                'tax_type' => 'income_tax', 'has_vat' => true,
                'vat_rate' => 17.5,
                'income_brackets' => [
                    ['min' => 0,       'max' => 50000,  'rate' => 12.5],
                    ['min' => 50000,   'max' => PHP_INT_MAX, 'rate' => 28.5],
                ],
            ],
        ];
    }

    // ═══════════════════════════════════════════════════════════════════
    // TAX RATE LOOKUP
    // ═══════════════════════════════════════════════════════════════════

    /**
     * Get tax rates for a specific country (+ state/province if applicable).
     */
    public function get_tax_rates(WP_REST_Request $req) {
        $p = $req->get_json_params() ?: [];
        $country_code = strtoupper(sanitize_text_field($p['country'] ?? ''));
        $state_code = strtoupper(sanitize_text_field($p['state'] ?? ''));

        $db = self::get_country_database();
        if (!isset($db[$country_code])) {
            return new WP_REST_Response(['success' => false, 'message' => 'Country not found in tax database'], 404);
        }

        $country = $db[$country_code];
        $result = [
            'country' => $country_code,
            'country_name' => $country['name'],
            'currency' => $country['currency'],
            'tax_type' => $country['tax_type'],
            'has_vat' => $country['has_vat'] ?? false,
            'has_gst' => $country['has_gst'] ?? false,
            'has_sales_tax' => $country['has_sales_tax'] ?? false,
        ];

        // VAT/GST rates
        if (!empty($country['vat_rate'])) $result['vat_rate'] = $country['vat_rate'];
        if (!empty($country['gst_rate'])) $result['gst_rate'] = $country['gst_rate'];
        if (!empty($country['gct_rate'])) $result['gct_rate'] = $country['gct_rate'];

        // Income brackets
        $brackets_key = isset($country['federal_income_brackets']) ? 'federal_income_brackets' : 'income_brackets';
        if (isset($country[$brackets_key])) {
            $result['income_brackets'] = array_map(function($b) {
                return [
                    'min' => $b['min'],
                    'max' => ($b['max'] === PHP_INT_MAX) ? 'unlimited' : $b['max'],
                    'rate' => $b['rate'],
                    'band' => $b['band'] ?? null,
                ];
            }, $country[$brackets_key]);
        }

        // US states
        if ($country_code === 'US' && !empty($country['states'])) {
            $result['has_states'] = true;
            if ($state_code && isset($country['states'][$state_code])) {
                $state = $country['states'][$state_code];
                $result['state'] = [
                    'code' => $state_code,
                    'name' => $state['name'],
                    'income_rate' => $state['income_rate'],
                    'sales_tax' => $state['sales_tax'],
                ];
            }
            $result['available_states'] = array_map(function($code, $s) {
                return ['code' => $code, 'name' => $s['name']];
            }, array_keys($country['states']), $country['states']);
            $result['self_employment_tax_rate'] = $country['self_employment_tax_rate'];
            $result['standard_deduction'] = $country['standard_deduction'];
        }

        // Canadian provinces
        if ($country_code === 'CA' && !empty($country['provinces'])) {
            $result['has_provinces'] = true;
            if ($state_code && isset($country['provinces'][$state_code])) {
                $prov = $country['provinces'][$state_code];
                $result['province'] = [
                    'code' => $state_code,
                    'name' => $prov['name'],
                    'provincial_rate' => $prov['prov_rate'],
                    'pst' => $prov['pst'],
                    'hst' => $prov['hst'],
                ];
            }
            $result['available_provinces'] = array_map(function($code, $p) {
                return ['code' => $code, 'name' => $p['name']];
            }, array_keys($country['provinces']), $country['provinces']);
        }

        // Country-specific extras
        foreach (['note', 'solidarity_surcharge', 'social_charges_rate', 'medicare_levy',
                   'inhabitant_tax', 'ni_rates', 'ni_threshold', 'cess_rate',
                   'zakat_rate', 'icms_rate'] as $key) {
            if (isset($country[$key])) $result[$key] = $country[$key];
        }

        return new WP_REST_Response(['success' => true, 'data' => $result], 200);
    }

    // ═══════════════════════════════════════════════════════════════════
    // TAX CALCULATION ENGINE
    // ═══════════════════════════════════════════════════════════════════

    /**
     * Calculate estimated tax liability based on income, expenses, country.
     * This mirrors what Stripe Tax calculates for merchants.
     */
    public function calculate_tax(WP_REST_Request $req) {
        $uid = get_current_user_id();
        $p = $req->get_json_params() ?: [];

        $country_code = strtoupper(sanitize_text_field($p['country'] ?? ''));
        $state_code = strtoupper(sanitize_text_field($p['state'] ?? ''));
        $gross_income = floatval($p['gross_income'] ?? 0);
        $declared_gross_income = $gross_income;
        $other_income = floatval($p['other_income'] ?? 0);
        $expenses = floatval($p['expenses'] ?? 0);
        $filing_status = sanitize_text_field($p['filing_status'] ?? 'single');
        $use_actual_revenue = !empty($p['use_actual_revenue']);

        // If user wants to use actual VMO Pay revenue, fetch from orders
        if ($use_actual_revenue) {
            $revenue = $this->get_actual_revenue($uid, $p['period'] ?? 'year');
            $actual_revenue = (float) ($revenue['gross_income'] ?? 0);
            if ($other_income <= 0 && $declared_gross_income > $actual_revenue) {
                $other_income = $declared_gross_income - $actual_revenue;
            }
            $gross_income = $actual_revenue + max(0, $other_income);
            if (empty($expenses)) {
                $expenses = (float) ($revenue['total_fees'] ?? 0) + (float) ($revenue['ledger_expenses'] ?? 0) + (float) ($revenue['ledger_refunds'] ?? 0);
            }
        }

        $db = self::get_country_database();
        if (!isset($db[$country_code])) {
            return new WP_REST_Response(['success' => false, 'message' => 'Country not found'], 404);
        }

        $country = $db[$country_code];
        $net_profit = max(0, $gross_income - $expenses);

        // Calculate tax based on country
        $result = $this->compute_tax($country_code, $country, $net_profit, $state_code, $filing_status, $gross_income);
        $result['gross_income'] = round($gross_income, 2);
        $result['other_income'] = round(max(0, $other_income), 2);
        if (!empty($actual_revenue)) {
            $result['actual_revenue'] = round((float) $actual_revenue, 2);
        }
        $result['total_expenses'] = round($expenses, 2);
        $result['net_profit'] = round($net_profit, 2);
        $result['country'] = $country_code;
        $result['country_name'] = $country['name'];
        $result['currency'] = $country['currency'];
        $result['state'] = $state_code;

        // Net after tax
        $result['net_after_tax'] = round($net_profit - $result['total_tax'], 2);
        $result['effective_rate'] = ($net_profit > 0) ? round(($result['total_tax'] / $net_profit) * 100, 2) : 0;

        // Save calculation to user meta for dashboard display
        $calc_history = get_user_meta($uid, 'vmo_tax_calculations', true) ?: [];
        $calc_history[] = [
            'date' => current_time('mysql'),
            'country' => $country_code,
            'state' => $state_code,
            'gross' => $gross_income,
            'expenses' => $expenses,
            'net_profit' => $net_profit,
            'total_tax' => $result['total_tax'],
            'effective_rate' => $result['effective_rate'],
        ];
        // Keep last 50 calculations
        if (count($calc_history) > 50) $calc_history = array_slice($calc_history, -50);
        update_user_meta($uid, 'vmo_tax_calculations', $calc_history);

        return new WP_REST_Response(['success' => true, 'data' => $result], 200);
    }

    /**
     * Core tax computation engine.
     * Calculates progressive income tax + additional levies per jurisdiction.
     */
    private function compute_tax($country_code, $country, $taxable_income, $state_code, $filing_status, $gross_income) {
        $breakdown = [];
        $total_tax = 0;

        // Determine which bracket set to use
        $brackets_key = isset($country['federal_income_brackets']) ? 'federal_income_brackets' : 'income_brackets';
        $brackets = $country[$brackets_key] ?? [];

        // Apply deductions before calculating
        $deductions = 0;
        if ($country_code === 'US') {
            $deductions = $country['standard_deduction'] ?? 0;
            $taxable_income = max(0, $taxable_income - $deductions);
            $breakdown[] = ['label' => 'Standard Deduction', 'amount' => -$deductions, 'note' => 'Applied before tax calculation'];
        }
        if ($country_code === 'CA') {
            $deductions = $country['basic_personal_amount'] ?? 0;
            // BPA credit at lowest rate
            $bpa_credit = $deductions * 0.15;
            $breakdown[] = ['label' => 'Basic Personal Amount Credit', 'amount' => -round($bpa_credit, 2), 'note' => "BPA of \${$deductions} × 15%"];
        }

        // Progressive income tax
        $income_tax = $this->calculate_progressive_tax($taxable_income, $brackets);
        $total_tax += $income_tax;
        $breakdown[] = [
            'label' => ($country_code === 'US' || $country_code === 'CA') ? 'Federal Income Tax' : 'Income Tax',
            'amount' => round($income_tax, 2),
            'rate_type' => 'progressive'
        ];

        // Apply BPA credit for Canada
        if ($country_code === 'CA' && $deductions > 0) {
            $bpa_credit = $deductions * 0.15;
            $total_tax = max(0, $total_tax - $bpa_credit);
        }

        // ── Country-specific additional taxes ──

        // US: Self-employment tax + state income tax
        if ($country_code === 'US') {
            $se_rate = $country['self_employment_tax_rate'] ?? 15.3;
            $se_threshold = $country['se_threshold'] ?? 400;
            if ($gross_income > $se_threshold) {
                // SE tax on 92.35% of net earnings
                $se_base = $gross_income * 0.9235;
                // Social Security cap at $168,600 (2024)
                $ss_base = min($se_base, 168600);
                $ss_tax = $ss_base * 0.124;
                $medicare_tax = $se_base * 0.029;
                $se_tax = round($ss_tax + $medicare_tax, 2);
                $total_tax += $se_tax;
                $breakdown[] = ['label' => 'Self-Employment Tax (SS + Medicare)', 'amount' => $se_tax, 'note' => 'Social Security (12.4%) + Medicare (2.9%)'];
            }

            if ($state_code && !empty($country['states'][$state_code])) {
                $state = $country['states'][$state_code];
                $state_rate = $state['income_rate'] ?? 0;
                if ($state_rate > 0) {
                    $state_tax = round($taxable_income * ($state_rate / 100), 2);
                    $total_tax += $state_tax;
                    $breakdown[] = ['label' => $state['name'] . ' State Income Tax', 'amount' => $state_tax, 'rate' => $state_rate];
                }
            }
        }

        // Canada: Provincial tax
        if ($country_code === 'CA' && $state_code && !empty($country['provinces'][$state_code])) {
            $prov = $country['provinces'][$state_code];
            $prov_rate = $prov['prov_rate'] ?? 0;
            if ($prov_rate > 0) {
                $prov_tax = round($taxable_income * ($prov_rate / 100), 2);
                $total_tax += $prov_tax;
                $breakdown[] = ['label' => $prov['name'] . ' Provincial Tax', 'amount' => $prov_tax, 'rate' => $prov_rate];
            }
        }

        // UK: National Insurance
        if ($country_code === 'GB') {
            $ni = $country['ni_rates'] ?? [];
            $ni_threshold = $country['ni_threshold'] ?? 12570;
            if ($gross_income > $ni_threshold) {
                $ni_rate = $ni['self_employed_class4'] ?? 6.0;
                $ni_tax = round(($gross_income - $ni_threshold) * ($ni_rate / 100), 2);
                $total_tax += $ni_tax;
                $breakdown[] = ['label' => 'National Insurance (Class 4)', 'amount' => $ni_tax, 'rate' => $ni_rate];
            }
        }

        // Germany: Solidarity surcharge
        if ($country_code === 'DE') {
            $soli_rate = $country['solidarity_surcharge'] ?? 5.5;
            $soli_threshold = 18130; // approx threshold where soli kicks in
            if ($income_tax > $soli_threshold) {
                $soli = round($income_tax * ($soli_rate / 100), 2);
                $total_tax += $soli;
                $breakdown[] = ['label' => 'Solidarity Surcharge', 'amount' => $soli, 'rate' => $soli_rate];
            }
        }

        // France: Social charges
        if ($country_code === 'FR') {
            $social_rate = $country['social_charges_rate'] ?? 17.2;
            $social_tax = round($gross_income * ($social_rate / 100), 2);
            $total_tax += $social_tax;
            $breakdown[] = ['label' => 'Social Charges (CSG/CRDS)', 'amount' => $social_tax, 'rate' => $social_rate];
        }

        // Australia: Medicare levy
        if ($country_code === 'AU') {
            $medicare_rate = $country['medicare_levy'] ?? 2.0;
            $medicare = round($gross_income * ($medicare_rate / 100), 2);
            $total_tax += $medicare;
            $breakdown[] = ['label' => 'Medicare Levy', 'amount' => $medicare, 'rate' => $medicare_rate];
        }

        // India: Health & Education Cess
        if ($country_code === 'IN') {
            $cess_rate = $country['cess_rate'] ?? 4.0;
            $cess = round($income_tax * ($cess_rate / 100), 2);
            $total_tax += $cess;
            $breakdown[] = ['label' => 'Health & Education Cess', 'amount' => $cess, 'rate' => $cess_rate];
        }

        // Japan: Inhabitant Tax
        if ($country_code === 'JP') {
            $inh_rate = $country['inhabitant_tax'] ?? 10.0;
            $inh_tax = round($taxable_income * ($inh_rate / 100), 2);
            $total_tax += $inh_tax;
            $breakdown[] = ['label' => 'Inhabitant Tax (local)', 'amount' => $inh_tax, 'rate' => $inh_rate];
        }

        // VAT/GST info (not part of income tax, but important context)
        $vat_info = null;
        if (!empty($country['vat_rate'])) {
            $vat_info = ['type' => 'VAT', 'standard_rate' => $country['vat_rate'], 'reduced_rate' => $country['vat_reduced'] ?? null];
        } elseif (!empty($country['gst_rate'])) {
            $vat_info = ['type' => 'GST', 'standard_rate' => $country['gst_rate']];
        } elseif (!empty($country['gct_rate'])) {
            $vat_info = ['type' => 'GCT', 'standard_rate' => $country['gct_rate']];
        }

        // Sales tax info for US
        $sales_tax_info = null;
        if ($country_code === 'US' && $state_code && !empty($country['states'][$state_code])) {
            $st_rate = $country['states'][$state_code]['sales_tax'] ?? 0;
            if ($st_rate > 0) {
                $sales_tax_info = ['state_rate' => $st_rate, 'note' => 'Collected from customers, not income tax'];
            }
        }

        return [
            'total_tax' => round(max(0, $total_tax), 2),
            'breakdown' => $breakdown,
            'indirect_taxes' => $vat_info,
            'sales_tax' => $sales_tax_info,
            'note' => $country['note'] ?? null,
            'disclaimer' => 'This is an estimate for planning purposes only. Consult a qualified tax professional for official tax filing advice.',
        ];
    }

    /**
     * Calculate progressive (marginal) tax from brackets.
     */
    private function calculate_progressive_tax($income, $brackets) {
        $tax = 0;
        foreach ($brackets as $bracket) {
            if ($income <= 0) break;
            $min = $bracket['min'];
            $max = ($bracket['max'] === PHP_INT_MAX) ? PHP_INT_MAX : $bracket['max'];
            $rate = $bracket['rate'];

            $taxable_in_bracket = min($income, $max - $min);
            if ($taxable_in_bracket > 0 && $income > $min) {
                $actual = min($taxable_in_bracket, $income - $min);
                if ($actual > 0) {
                    $tax += $actual * ($rate / 100);
                }
            }
        }
        return $tax;
    }

    private function table_exists($table) {
        global $wpdb;
        return $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->esc_like($table))) === $table;
    }

    private function get_posted_financial_ledger_summary($user_id, $date_from = '2000-01-01', $date_to = null) {
        global $wpdb;
        $ledger_table = $wpdb->prefix . 'vmo_financial_ledger';
        $zero = [
            'income' => 0.0,
            'expenses' => 0.0,
            'refunds' => 0.0,
            'fees' => 0.0,
            'taxes_collected' => 0.0,
            'net' => 0.0,
            'event_count' => 0,
            'expense_by_category' => [],
        ];
        if (!$this->table_exists($ledger_table)) {
            return $zero;
        }

        $date_to = $date_to ?: current_time('Y-m-d');
        $start = strlen($date_from) <= 10 ? $date_from . ' 00:00:00' : $date_from;
        $end = strlen($date_to) <= 10 ? $date_to . ' 23:59:59' : $date_to;
        $orders_table = $wpdb->prefix . 'vmo_store_orders';
        $order_exclusion = '';
        if ($this->table_exists($orders_table)) {
            $order_exclusion = " AND NOT EXISTS (
                SELECT 1 FROM {$orders_table} o
                WHERE o.user_id = l.user_id
                  AND o.status = 'paid'
                  AND l.source_reference IS NOT NULL
                  AND l.source_reference <> ''
                  AND (
                    o.stripe_charge_id = l.source_reference
                    OR o.stripe_payment_intent_id = l.source_reference
                    OR o.stripe_checkout_session_id = l.source_reference
                    OR o.order_reference = l.source_reference
                  )
            )";
        }

        $summary = $wpdb->get_row($wpdb->prepare(
            "SELECT
                COALESCE(SUM(CASE WHEN l.direction = 'income' THEN l.amount ELSE 0 END), 0) AS income,
                COALESCE(SUM(CASE WHEN l.direction = 'expense' THEN ABS(l.amount) ELSE 0 END), 0) AS expenses,
                COALESCE(SUM(CASE WHEN l.direction = 'refund' OR l.transaction_type = 'refund' THEN ABS(l.amount) ELSE 0 END), 0) AS refunds,
                COALESCE(SUM(CASE WHEN l.direction = 'income' THEN l.tax_amount ELSE 0 END), 0) AS taxes_collected,
                COALESCE(SUM(ABS(l.fees_amount)), 0) AS fees,
                COALESCE(SUM(CASE
                    WHEN l.direction = 'income' THEN l.net_amount
                    WHEN l.direction = 'expense' THEN -ABS(l.amount + l.fees_amount)
                    WHEN l.direction = 'refund' OR l.transaction_type = 'refund' THEN -ABS(l.amount)
                    ELSE 0
                END), 0) AS net,
                COUNT(*) AS event_count
             FROM {$ledger_table} l
             WHERE l.user_id = %d
               AND l.status = 'posted'
               AND l.transaction_date >= %s
               AND l.transaction_date <= %s{$order_exclusion}",
            $user_id,
            $start,
            $end
        ), ARRAY_A) ?: [];

        $expense_rows = $wpdb->get_results($wpdb->prepare(
            "SELECT COALESCE(NULLIF(l.category, ''), 'financial_ledger') AS category, COALESCE(SUM(ABS(l.amount)), 0) AS total
             FROM {$ledger_table} l
             WHERE l.user_id = %d
               AND l.status = 'posted'
               AND l.direction = 'expense'
               AND l.transaction_date >= %s
               AND l.transaction_date <= %s{$order_exclusion}
             GROUP BY COALESCE(NULLIF(l.category, ''), 'financial_ledger')",
            $user_id,
            $start,
            $end
        ), ARRAY_A) ?: [];

        $expense_by_category = [];
        foreach ($expense_rows as $row) {
            $expense_by_category[sanitize_key($row['category'] ?: 'financial_ledger')] = round((float) $row['total'], 2);
        }

        return [
            'income' => round((float) ($summary['income'] ?? 0), 2),
            'expenses' => round((float) ($summary['expenses'] ?? 0), 2),
            'refunds' => round((float) ($summary['refunds'] ?? 0), 2),
            'fees' => round((float) ($summary['fees'] ?? 0), 2),
            'taxes_collected' => round((float) ($summary['taxes_collected'] ?? 0), 2),
            'net' => round((float) ($summary['net'] ?? 0), 2),
            'event_count' => (int) ($summary['event_count'] ?? 0),
            'expense_by_category' => $expense_by_category,
        ];
    }

    /**
     * Get actual revenue from VMO Pay orders plus approved CFO ledger events.
     */
    private function get_actual_revenue($user_id, $period = 'year') {
        global $wpdb;
        $orders_table = $wpdb->prefix . 'vmo_store_orders';

        // Period filter
        $since = match($period) {
            'month' => date('Y-m-d', strtotime('-30 days')),
            'quarter' => date('Y-m-d', strtotime('-90 days')),
            'year' => date('Y-01-01'),
            'all' => '2000-01-01',
            default => date('Y-01-01'),
        };

        $rows = [];
        if ($this->table_exists($orders_table)) {
            $rows = $wpdb->get_results($wpdb->prepare(
                "SELECT amount_total, metadata FROM {$orders_table} WHERE user_id = %d AND status = 'paid' AND created_at >= %s",
                $user_id, $since
            ), ARRAY_A) ?: [];
        }

        $gross = 0;
        $stripe_fees = 0;
        $platform_fees = 0;
        $taxes_collected = 0;

        foreach ($rows as $r) {
            $gross += (int)$r['amount_total'];
            $meta = json_decode($r['metadata'] ?: '{}', true);
            $stripe_fees += (int)($meta['stripe_fee_cents'] ?? 0);
            $platform_fees += (int)($meta['platform_fee_cents'] ?? 0);
            $taxes_collected += (int)($meta['tax_cents'] ?? 0);
        }

        $ledger = $this->get_posted_financial_ledger_summary($user_id, $since, current_time('Y-m-d'));

        $order_gross = round($gross / 100, 2);
        $order_fees = round(($stripe_fees + $platform_fees) / 100, 2);
        $order_net = round(($gross - $stripe_fees - $platform_fees) / 100, 2);
        $order_taxes = round($taxes_collected / 100, 2);

        // Convert cents to currency units
        return [
            'gross_income' => round($order_gross + $ledger['income'], 2),
            'total_fees' => round($order_fees + $ledger['fees'], 2),
            'stripe_fees' => round($stripe_fees / 100, 2),
            'platform_fees' => round($platform_fees / 100, 2),
            'ledger_fees' => $ledger['fees'],
            'taxes_collected' => round($order_taxes + $ledger['taxes_collected'], 2),
            'net_revenue' => round($order_net + $ledger['net'], 2),
            'ledger_income' => $ledger['income'],
            'ledger_expenses' => $ledger['expenses'],
            'ledger_refunds' => $ledger['refunds'],
            'ledger_event_count' => $ledger['event_count'],
            'order_count' => count($rows),
        ];
    }

    // ═══════════════════════════════════════════════════════════════════
    // TAX SUMMARY (Dashboard data)
    // ═══════════════════════════════════════════════════════════════════

    /**
     * Get comprehensive tax summary for the dashboard.
     * Pulls from actual revenue + saved settings.
     */
    public function get_tax_summary(WP_REST_Request $req) {
        $uid = get_current_user_id();
        $period = sanitize_text_field($req->get_param('period') ?? 'year');

        // Get user's tax settings
        $settings = get_user_meta($uid, 'vmo_tax_settings', true) ?: [];
        $country = $settings['country'] ?? '';
        $state = $settings['state'] ?? '';

        // Get actual revenue
        $revenue = $this->get_actual_revenue($uid, $period);

        // Get saved expenses
        $expenses_data = get_user_meta($uid, 'vmo_business_expenses', true) ?: [];
        $total_expenses = 0;
        foreach ($expenses_data as $exp) {
            $total_expenses += floatval($exp['amount'] ?? 0);
        }

        // Include fees as deductible expenses
        $total_expenses += $revenue['total_fees'];

        // Calculate tax if country is set
        $tax_estimate = null;
        if ($country) {
            $db = self::get_country_database();
            if (isset($db[$country])) {
                $net_profit = max(0, $revenue['gross_income'] - $total_expenses);
                $tax_estimate = $this->compute_tax($country, $db[$country], $net_profit, $state, 'single', $revenue['gross_income']);
                $tax_estimate['gross_income'] = $revenue['gross_income'];
                $tax_estimate['total_expenses'] = round($total_expenses, 2);
                $tax_estimate['net_profit'] = round($net_profit, 2);
                $tax_estimate['net_after_tax'] = round($net_profit - $tax_estimate['total_tax'], 2);
                $tax_estimate['effective_rate'] = ($net_profit > 0) ? round(($tax_estimate['total_tax'] / $net_profit) * 100, 2) : 0;
            }
        }

        // Recent calculations
        $calc_history = get_user_meta($uid, 'vmo_tax_calculations', true) ?: [];
        $recent_calcs = array_slice(array_reverse($calc_history), 0, 5);

        return new WP_REST_Response([
            'success' => true,
            'data' => [
                'settings' => $settings,
                'revenue' => $revenue,
                'expenses' => $expenses_data,
                'total_expenses' => round($total_expenses, 2),
                'tax_estimate' => $tax_estimate,
                'recent_calculations' => $recent_calcs,
                'period' => $period,
            ]
        ], 200);
    }

    // ═══════════════════════════════════════════════════════════════════
    // TAX SETTINGS
    // ═══════════════════════════════════════════════════════════════════

    public function get_tax_settings(WP_REST_Request $req) {
        $uid = get_current_user_id();
        $settings = get_user_meta($uid, 'vmo_tax_settings', true) ?: [];
        $settings += [
            'country' => '',
            'state' => '',
            'filing_status' => 'single',
            'business_type' => 'sole_proprietor',
            'fiscal_year_start' => 'january',
        ];
        return new WP_REST_Response(['success' => true, 'settings' => $settings], 200);
    }

    public function save_tax_settings(WP_REST_Request $req) {
        $uid = get_current_user_id();
        $p = $req->get_json_params() ?: [];
        $settings = [
            'country' => strtoupper(sanitize_text_field($p['country'] ?? '')),
            'state' => strtoupper(sanitize_text_field($p['state'] ?? '')),
            'filing_status' => sanitize_text_field($p['filing_status'] ?? 'single'),
            'business_type' => sanitize_text_field($p['business_type'] ?? 'sole_proprietor'),
            'fiscal_year_start' => sanitize_text_field($p['fiscal_year_start'] ?? 'january'),
        ];
        update_user_meta($uid, 'vmo_tax_settings', $settings);
        return new WP_REST_Response(['success' => true], 200);
    }

    // ═══════════════════════════════════════════════════════════════════
    // EXPENSE TRACKING
    // ═══════════════════════════════════════════════════════════════════

    public function save_expenses(WP_REST_Request $req) {
        $uid = get_current_user_id();
        $p = $req->get_json_params() ?: [];
        $expenses = [];
        if (is_array($p['expenses'] ?? null)) {
            foreach ($p['expenses'] as $exp) {
                $expenses[] = [
                    'category' => sanitize_text_field($exp['category'] ?? 'other'),
                    'description' => sanitize_text_field($exp['description'] ?? ''),
                    'amount' => floatval($exp['amount'] ?? 0),
                    'date' => sanitize_text_field($exp['date'] ?? date('Y-m-d')),
                    'recurring' => !empty($exp['recurring']),
                ];
            }
        }
        update_user_meta($uid, 'vmo_business_expenses', $expenses);
        return new WP_REST_Response(['success' => true, 'saved' => count($expenses)], 200);
    }

    public function get_expenses(WP_REST_Request $req) {
        $uid = get_current_user_id();
        $expenses = get_user_meta($uid, 'vmo_business_expenses', true) ?: [];
        return new WP_REST_Response(['success' => true, 'expenses' => $expenses], 200);
    }

    // ═══════════════════════════════════════════════════════════════════
    // AI-POWERED TAX ANALYSIS
    // Uses GPT to interpret complex tax situations
    // ═══════════════════════════════════════════════════════════════════

    /**
     * AI-powered tax analysis for complex scenarios.
     * Charges tokens like any other AI operation.
     */
    public function ai_tax_analysis(WP_REST_Request $req) {
        $uid = get_current_user_id();

        // Token check
        $cost = vmo_get_token_cost('tax_calculation');
        if (!vmo_check_token_balance($uid, 'tax_calculation')) {
            return new WP_REST_Response([
                'success' => false,
                'message' => "Insufficient tokens. This analysis requires {$cost} tokens."
            ], 402);
        }

        $p = $req->get_json_params() ?: [];
        $country_code = strtoupper(sanitize_text_field($p['country'] ?? ''));
        $state_code = strtoupper(sanitize_text_field($p['state'] ?? ''));
        $gross_income = floatval($p['gross_income'] ?? 0);
        $expenses = floatval($p['expenses'] ?? 0);
        $question = sanitize_textarea_field($p['question'] ?? '');

        $db = self::get_country_database();
        $country = $db[$country_code] ?? null;
        $country_name = $country ? $country['name'] : $country_code;
        $currency = $country['currency'] ?? 'USD';

        // Get actual revenue context
        $revenue = $this->get_actual_revenue($uid);

        // Build context for AI
        $context = "Business Tax Context:
- Country: {$country_name}" . ($state_code ? " (State/Province: {$state_code})" : "") . "
- Currency: {$currency}
- Gross Income: {$currency} " . number_format($gross_income ?: $revenue['gross_income'], 2) . "
- Declared Expenses: {$currency} " . number_format($expenses, 2) . "
- Net Profit: {$currency} " . number_format(max(0, ($gross_income ?: $revenue['gross_income']) - $expenses), 2) . "
- VMO Pay Revenue (actual): {$currency} " . number_format($revenue['gross_income'], 2) . "
- Processing Fees Paid: {$currency} " . number_format($revenue['total_fees'], 2) . "
- Taxes Collected from Customers: {$currency} " . number_format($revenue['taxes_collected'], 2) . "
- Total Orders: {$revenue['order_count']}";

        if ($country) {
            $context .= "\n\nApplicable Tax Law Summary:";
            if (!empty($country['vat_rate'])) $context .= "\n- VAT Rate: {$country['vat_rate']}%";
            if (!empty($country['gst_rate'])) $context .= "\n- GST Rate: {$country['gst_rate']}%";
            $brackets_key = isset($country['federal_income_brackets']) ? 'federal_income_brackets' : 'income_brackets';
            if (!empty($country[$brackets_key])) {
                $context .= "\n- Income Tax Brackets:";
                foreach ($country[$brackets_key] as $b) {
                    $max_display = ($b['max'] === PHP_INT_MAX) ? '+' : number_format($b['max']);
                    $context .= "\n  " . number_format($b['min']) . " - {$max_display}: {$b['rate']}%";
                }
            }
        }

        $prompt = "You are an expert tax advisor providing guidance for a small business owner.

{$context}

" . ($question ? "User's Question: {$question}" : "Provide a comprehensive tax planning summary including:
1. Estimated tax liability breakdown
2. Key deductions they should consider
3. Tax filing deadlines for their jurisdiction
4. Strategies to minimize tax burden legally
5. Any tax credits they may be eligible for") . "

Important: Provide actionable, specific advice. Always end with a disclaimer that this is AI-generated guidance and they should consult a certified tax professional for official advice.";

        $api_key = get_option('vmo_openai_api_key') ?: (defined('VMO_OPENAI_API_KEY') ? VMO_OPENAI_API_KEY : '');
        if (!$api_key) {
            return new WP_REST_Response(['success' => false, 'message' => 'AI not configured'], 500);
        }

        // ✅ FIX: Use centralized model registry
        $_tc_model = function_exists('vmo_get_model') ? vmo_get_model('nano') : (defined('VMO_OPENAI_MODEL') ? VMO_OPENAI_MODEL : 'gpt-5.5-nano');
        $_tc_body = array_merge([
            'model' => $_tc_model,
            'messages' => [
                ['role' => 'system', 'content' => "You are an expert tax advisor specializing in {$country_name} tax law. Provide accurate, actionable tax guidance for small business owners. Include specific numbers and calculations where possible."],
                ['role' => 'user', 'content' => $prompt],
            ],
            'temperature' => 0.4,
        ], function_exists('vmo_get_token_param') ? vmo_get_token_param($_tc_model, 1200) : ['max_tokens' => 1200]);

        $response = wp_remote_post('https://api.openai.com/v1/chat/completions', [
            'timeout' => 90,
            'headers' => [
                'Authorization' => 'Bearer ' . $api_key,
                'Content-Type' => 'application/json',
            ],
            'body' => json_encode($_tc_body),
        ]);

        if (is_wp_error($response)) {
            return new WP_REST_Response(['success' => false, 'message' => 'AI request failed'], 500);
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);
        $analysis = $body['choices'][0]['message']['content'] ?? '';

        if (!$analysis) {
            return new WP_REST_Response(['success' => false, 'message' => 'No analysis generated'], 500);
        }

        // ✅ Deduct tokens AFTER successful generation (consistent with existing pattern)
        vmo_deduct_tokens($uid, $cost, 'tax_calculation', 'AI tax analysis for ' . $country_name);

        return new WP_REST_Response([
            'success' => true,
            'data' => [
                'analysis' => $analysis,
                'tokens_charged' => $cost,
            ]
        ], 200);
    }

    // ═══════════════════════════════════════════════════════════════════
    // CFO BRIEFING — Auto-populated financial snapshot
    // The CEO/user doesn't need to input anything; the AI CFO already
    // knows everything from the consultation and transaction history.
    // ═══════════════════════════════════════════════════════════════════

    /**
     * Build a comprehensive CFO briefing with auto-detected location,
     * business type, revenue, expenses, and tax estimates.
     */
    public function get_cfo_briefing(WP_REST_Request $req) {
        $uid = get_current_user_id();

        // 1. Derive business location from consultation profile
        $profile  = function_exists('vmo_get_consultation_profile') ? vmo_get_consultation_profile($uid) : [];
        $location = $this->resolve_business_location($profile);

        // 2. Get revenue from actual VMO Pay transactions (fiscal year)
        $revenue = $this->get_actual_revenue($uid, 'year');

        // 3. Get saved expenses
        $expenses_data = get_user_meta($uid, 'vmo_business_expenses', true) ?: [];
        $tracked_expenses = 0;
        foreach ($expenses_data as $exp) {
            $tracked_expenses += floatval($exp['amount'] ?? 0);
        }
        // Include processing fees as deductible expense
        $processing_fees = $revenue['total_fees'];
        $auto_expenses = $processing_fees;

        // 4. Get saved tax settings (may have been manually corrected)
        $tax_settings = get_user_meta($uid, 'vmo_tax_settings', true) ?: [];
        // Consultation-derived location is the default; saved settings override
        $country_code = !empty($tax_settings['country']) ? $tax_settings['country'] : $location['country_code'];
        $state_code   = !empty($tax_settings['state'])   ? $tax_settings['state']   : $location['state_code'];
        $filing_status = $tax_settings['filing_status'] ?? 'single';

        // 5. Derive business type from consultation
        $business_type = $this->resolve_business_type($profile);

        // 6. Auto-calculate tax estimate with known data
        $db = self::get_country_database();
        $country = $db[$country_code] ?? null;
        $country_name = $country ? $country['name'] : ($location['country_name'] ?: 'Unknown');
        $state_name   = '';
        $currency     = $country ? $country['currency'] : 'USD';

        // Resolve state name
        if ($country && $state_code) {
            $states_key = isset($country['states']) ? 'states' : (isset($country['provinces']) ? 'provinces' : '');
            if ($states_key && isset($country[$states_key][$state_code])) {
                $state_name = $country[$states_key][$state_code]['name'] ?? $state_code;
            }
        }

        // Tax regime info for display
        $tax_regime = null;
        if ($country) {
            $brackets_key = isset($country['federal_income_brackets']) ? 'federal_income_brackets' : 'income_brackets';
            $tax_regime = [
                'country_name' => $country_name,
                'currency' => $currency,
                'brackets' => $country[$brackets_key] ?? [],
                'has_vat' => !empty($country['has_vat']),
                'vat_rate' => $country['vat_rate'] ?? null,
                'has_gst' => !empty($country['has_gst']),
                'gst_rate' => $country['gst_rate'] ?? null,
                'has_sales_tax' => !empty($country['has_sales_tax']),
                'self_employment_tax_rate' => $country['self_employment_tax_rate'] ?? null,
            ];
        }

        // 7. Get other income declared by user (stored in user meta)
        $other_income = floatval(get_user_meta($uid, 'vmo_other_taxable_income', true) ?: 0);

        // 8. User declared overhead (stored in user meta)
        $declared_overhead = floatval(get_user_meta($uid, 'vmo_declared_overhead', true) ?: 0);
        $total_expenses = $tracked_expenses + $auto_expenses + $declared_overhead;

        // Combined gross
        $vmo_gross = $revenue['gross_income'];
        $combined_gross = $vmo_gross + $other_income;
        $net_profit = max(0, $combined_gross - $total_expenses);

        // Sales tax collected from transactions
        $sales_tax_collected = $revenue['taxes_collected'];

        return new WP_REST_Response([
            'success' => true,
            'data' => [
                // Auto-detected from consultation
                'location' => [
                    'country_code' => $country_code,
                    'country_name' => $country_name,
                    'state_code'   => $state_code,
                    'state_name'   => $state_name,
                    'source'       => !empty($tax_settings['country']) ? 'saved_settings' : ($location['country_code'] ? 'consultation' : 'unknown'),
                    'raw_location' => $location['raw'],
                ],
                'business' => [
                    'type' => $business_type,
                    'name' => $profile['extracted_information']['businessName']
                              ?? $profile['business_profile']['identity']['business_name']
                              ?? $profile['businessName'] ?? '',
                    'industry' => $profile['extracted_information']['industry']
                                  ?? $profile['industry'] ?? '',
                    'filing_status' => $filing_status,
                ],
                // Auto-calculated from VMO Pay transactions
                'revenue' => [
                    'vmo_gross' => $vmo_gross,
                    'other_income' => $other_income,
                    'combined_gross' => $combined_gross,
                    'processing_fees' => $processing_fees,
                    'stripe_fees' => $revenue['stripe_fees'],
                    'platform_fees' => $revenue['platform_fees'],
                    'net_revenue' => $revenue['net_revenue'],
                    'order_count' => $revenue['order_count'],
                    'sales_tax_collected' => $sales_tax_collected,
                ],
                // Expenses
                'expenses' => [
                    'tracked_expenses' => round($tracked_expenses, 2),
                    'processing_fees' => round($processing_fees, 2),
                    'declared_overhead' => round($declared_overhead, 2),
                    'total' => round($total_expenses, 2),
                ],
                // Bottom line
                'summary' => [
                    'combined_gross' => round($combined_gross, 2),
                    'total_expenses' => round($total_expenses, 2),
                    'net_profit' => round($net_profit, 2),
                    'sales_tax_collected' => round($sales_tax_collected, 2),
                ],
                // Tax regime
                'tax_regime' => $tax_regime,
                'currency' => $currency,
            ],
        ], 200);
    }

    /**
     * Parse the free-text location from the consultation into country/state codes.
     */
    private function resolve_business_location($profile) {
        $raw = '';

        // Try extracted_information.location first
        $ei = $profile['extracted_information'] ?? $profile;
        if (!empty($ei['location'])) $raw = $ei['location'];

        // Try business_profile.identity.hq_location
        if (!$raw) {
            $bp = $profile['business_profile'] ?? [];
            if (!empty($bp['identity']['hq_location'])) $raw = $bp['identity']['hq_location'];
        }

        // Try geographies
        if (!$raw) {
            $geos = $profile['business_profile']['audience']['geographies'] ?? [];
            if (!empty($geos) && is_array($geos)) $raw = $geos[0];
        }

        $raw = strtolower(trim($raw));
        if (!$raw) return ['country_code' => '', 'state_code' => '', 'country_name' => '', 'raw' => ''];

        // Build a lookup of known countries by name/alias
        $db = self::get_country_database();
        $country_aliases = [];
        foreach ($db as $code => $c) {
            $country_aliases[strtolower($c['name'])] = $code;
        }
        // Add common aliases
        $country_aliases['usa']    = 'US'; $country_aliases['u.s.a.'] = 'US';
        $country_aliases['uk']     = 'GB'; $country_aliases['u.k.']   = 'GB';
        $country_aliases['england']= 'GB'; $country_aliases['britain']= 'GB';

        $found_country = '';
        $found_state   = '';

        // Try to find country in the location string
        foreach ($country_aliases as $alias => $code) {
            if (stripos($raw, $alias) !== false) {
                $found_country = $code;
                break;
            }
        }

        // If we matched US, try to find a state
        if ($found_country === 'US' && isset($db['US']['states'])) {
            foreach ($db['US']['states'] as $sc => $st) {
                $sn = strtolower($st['name']);
                if (stripos($raw, $sn) !== false || preg_match('/\b' . preg_quote(strtolower($sc), '/') . '\b/', $raw)) {
                    $found_state = $sc;
                    break;
                }
            }
        }
        // Canada provinces
        if ($found_country === 'CA' && isset($db['CA']['provinces'])) {
            foreach ($db['CA']['provinces'] as $pc => $prov) {
                $pn = strtolower($prov['name']);
                if (stripos($raw, $pn) !== false || preg_match('/\b' . preg_quote(strtolower($pc), '/') . '\b/', $raw)) {
                    $found_state = $pc;
                    break;
                }
            }
        }

        return [
            'country_code' => $found_country,
            'state_code'   => $found_state,
            'country_name' => $found_country ? ($db[$found_country]['name'] ?? '') : '',
            'raw'          => $raw,
        ];
    }

    /**
     * Derive business type from consultation profile.
     */
    private function resolve_business_type($profile) {
        $ei = $profile['extracted_information'] ?? $profile;
        $bp = $profile['business_profile'] ?? [];

        // Check offering type
        $offering = $ei['offeringType'] ?? $ei['offerings'] ?? '';
        if (is_array($offering)) $offering = implode(', ', $offering);

        // Check identity
        $structure = $bp['identity']['legal_structure'] ?? '';
        $industry  = $ei['industry'] ?? '';

        if ($structure) return $structure;
        if ($industry) return $industry;
        if ($offering) return $offering;
        return 'Business';
    }

    // ═══════════════════════════════════════════════════════════════════
    // BALANCE SHEET GENERATOR
    // ═══════════════════════════════════════════════════════════════════

    /**
     * Generate a balance sheet for a given date range.
     */
    public function generate_balance_sheet(WP_REST_Request $req) {
        $uid = get_current_user_id();
        $p = $req->get_json_params() ?: [];

        $date_from = sanitize_text_field($p['date_from'] ?? date('Y-01-01'));
        $date_to   = sanitize_text_field($p['date_to'] ?? date('Y-m-d'));
        $label     = sanitize_text_field($p['label'] ?? 'Custom Period');

        global $wpdb;
        $orders_table = $wpdb->prefix . 'vmo_store_orders';
        $table_exists = ($wpdb->get_var("SHOW TABLES LIKE '{$orders_table}'") === $orders_table);

        // --- REVENUE ---
        $total_revenue = 0;
        $total_stripe_fees = 0;
        $total_platform_fees = 0;
        $total_tax_collected = 0;
        $order_count = 0;
        $refund_total = 0;

        if ($table_exists) {
            $rows = $wpdb->get_results($wpdb->prepare(
                "SELECT amount_total, metadata, status FROM {$orders_table}
                 WHERE user_id = %d AND created_at >= %s AND created_at <= %s",
                $uid, $date_from . ' 00:00:00', $date_to . ' 23:59:59'
            ), ARRAY_A);

            foreach ($rows as $r) {
                $meta = json_decode($r['metadata'] ?: '{}', true);
                if ($r['status'] === 'paid') {
                    $total_revenue += (int)$r['amount_total'];
                    $total_stripe_fees += (int)($meta['stripe_fee_cents'] ?? 0);
                    $total_platform_fees += (int)($meta['platform_fee_cents'] ?? 0);
                    $total_tax_collected += (int)($meta['tax_cents'] ?? 0);
                    $order_count++;
                } elseif ($r['status'] === 'refunded') {
                    $refund_total += (int)$r['amount_total'];
                }
            }
        }

        $ledger = $this->get_posted_financial_ledger_summary($uid, $date_from, $date_to);

        $revenue_dollars   = round(($total_revenue / 100) + $ledger['income'], 2);
        $refund_dollars    = round(($refund_total / 100) + $ledger['refunds'], 2);
        $stripe_fees       = round($total_stripe_fees / 100, 2);
        $platform_fees     = round($total_platform_fees / 100, 2);
        $ledger_fees       = round($ledger['fees'], 2);
        $processing_fees   = round($stripe_fees + $platform_fees + $ledger_fees, 2);
        $tax_collected     = round(($total_tax_collected / 100) + $ledger['taxes_collected'], 2);
        $net_revenue       = round($revenue_dollars - $processing_fees - $refund_dollars, 2);

        // --- EXPENSES (from tracked expenses within date range) ---
        $all_expenses = get_user_meta($uid, 'vmo_business_expenses', true) ?: [];
        $period_expenses = [];
        $expense_by_category = [];
        $total_tracked_expenses = 0;

        foreach ($all_expenses as $exp) {
            $exp_date = $exp['date'] ?? '';
            if ($exp_date >= $date_from && $exp_date <= $date_to) {
                $amt = floatval($exp['amount'] ?? 0);
                $cat = $exp['category'] ?? 'other';
                $period_expenses[] = $exp;
                $total_tracked_expenses += $amt;
                $expense_by_category[$cat] = ($expense_by_category[$cat] ?? 0) + $amt;
            }
        }

        foreach ($ledger['expense_by_category'] as $cat => $amt) {
            $expense_by_category[$cat] = ($expense_by_category[$cat] ?? 0) + $amt;
            $total_tracked_expenses += $amt;
        }

        // Declared overhead (static total — proportioned by period length)
        $declared_overhead = floatval(get_user_meta($uid, 'vmo_declared_overhead', true) ?: 0);
        $days_in_period = max(1, (strtotime($date_to) - strtotime($date_from)) / 86400);
        $days_in_year = 365;
        $prorated_overhead = round($declared_overhead * ($days_in_period / $days_in_year), 2);

        $total_expenses = round($total_tracked_expenses + $processing_fees + $prorated_overhead, 2);
        $gross_profit   = round($net_revenue - $total_tracked_expenses - $prorated_overhead, 2);

        // --- OTHER INCOME ---
        $other_income = floatval(get_user_meta($uid, 'vmo_other_taxable_income', true) ?: 0);
        $prorated_other = round($other_income * ($days_in_period / $days_in_year), 2);

        // --- BOTTOM LINE ---
        $total_income = round($net_revenue + $prorated_other, 2);
        $net_income   = round($total_income - $total_tracked_expenses - $prorated_overhead, 2);

        // --- ASSETS & LIABILITIES (external) ---
        $al = get_user_meta($uid, 'vmo_assets_liabilities', true) ?: ['assets' => [], 'liabilities' => []];

        // Cash & cash equivalents = cumulative net revenue (simplified)
        $all_time_revenue = $this->get_actual_revenue($uid, 'all');
        $cash_position = round($all_time_revenue['net_revenue'], 2);

        $profile = function_exists('vmo_get_consultation_profile') ? vmo_get_consultation_profile($uid) : [];
        $biz_name = $profile['extracted_information']['businessName']
                    ?? $profile['business_profile']['identity']['business_name']
                    ?? $profile['businessName'] ?? 'Your Business';

        // Currency
        $tax_settings = get_user_meta($uid, 'vmo_tax_settings', true) ?: [];
        $loc = $this->resolve_business_location($profile);
        $cc = !empty($tax_settings['country']) ? $tax_settings['country'] : $loc['country_code'];
        $db = self::get_country_database();
        $currency = isset($db[$cc]) ? $db[$cc]['currency'] : 'USD';

        return new WP_REST_Response([
            'success' => true,
            'data' => [
                'business_name' => $biz_name,
                'period' => ['from' => $date_from, 'to' => $date_to, 'label' => $label, 'days' => round($days_in_period)],
                'currency' => $currency,
                'income' => [
                    'gross_revenue' => $revenue_dollars,
                    'refunds' => $refund_dollars,
                    'processing_fees' => $processing_fees,
                    'net_revenue' => $net_revenue,
                    'other_income' => $prorated_other,
                    'total_income' => $total_income,
                    'order_count' => $order_count,
                    'ledger_event_count' => (int) $ledger['event_count'],
                ],
                'expenses' => [
                    'tracked_expenses' => round($total_tracked_expenses, 2),
                    'processing_fees' => $processing_fees,
                    'overhead' => $prorated_overhead,
                    'total' => $total_expenses,
                    'by_category' => $expense_by_category,
                ],
                'profit' => [
                    'gross_profit' => $gross_profit,
                    'net_income' => $net_income,
                ],
                'tax' => [
                    'sales_tax_collected' => $tax_collected,
                ],
                'generated_at' => current_time('mysql'),
            ],
        ], 200);
    }

    // ═══════════════════════════════════════════════════════════════════
    // NET WORTH ESTIMATOR
    // Total Assets − Total Liabilities
    // ═══════════════════════════════════════════════════════════════════

    public function calculate_net_worth(WP_REST_Request $req) {
        $uid = get_current_user_id();

        // Cash: cumulative net revenue
        $revenue = $this->get_actual_revenue($uid, 'all');
        $cash = round($revenue['net_revenue'], 2);

        // Accounts receivable (unpaid orders)
        global $wpdb;
        $orders_table = $wpdb->prefix . 'vmo_store_orders';
        $ar = 0;
        if ($wpdb->get_var("SHOW TABLES LIKE '{$orders_table}'") === $orders_table) {
            $ar_cents = (int)$wpdb->get_var($wpdb->prepare(
                "SELECT COALESCE(SUM(amount_total),0) FROM {$orders_table} WHERE user_id = %d AND status = 'created'", $uid
            ));
            $ar = round($ar_cents / 100, 2);
        }

        // External assets & liabilities
        $al = get_user_meta($uid, 'vmo_assets_liabilities', true) ?: ['assets' => [], 'liabilities' => []];
        $ext_assets = 0;
        foreach (($al['assets'] ?? []) as $a) $ext_assets += floatval($a['value'] ?? 0);
        $ext_liabilities = 0;
        foreach (($al['liabilities'] ?? []) as $l) $ext_liabilities += floatval($l['value'] ?? 0);

        // Total assets = Cash + Accounts Receivable + External Assets
        $total_assets = round($cash + $ar + $ext_assets, 2);

        // Liabilities: sales tax owed (collected but not yet remitted)
        $tax_owed = round($revenue['taxes_collected'], 2);
        $total_liabilities = round($tax_owed + $ext_liabilities, 2);

        // Net worth
        $net_worth = round($total_assets - $total_liabilities, 2);

        // Year-over-year growth (compare to last year's net revenue)
        $last_year_rev = $this->get_actual_revenue($uid, 'year');
        $prev_year_start = date('Y-01-01', strtotime('-1 year'));
        $prev_year_end = date('Y-12-31', strtotime('-1 year'));

        $profile = function_exists('vmo_get_consultation_profile') ? vmo_get_consultation_profile($uid) : [];
        $biz_name = $profile['extracted_information']['businessName']
                    ?? $profile['business_profile']['identity']['business_name']
                    ?? 'Your Business';

        $tax_settings = get_user_meta($uid, 'vmo_tax_settings', true) ?: [];
        $loc = $this->resolve_business_location($profile);
        $cc = !empty($tax_settings['country']) ? $tax_settings['country'] : $loc['country_code'];
        $db = self::get_country_database();
        $currency = isset($db[$cc]) ? $db[$cc]['currency'] : 'USD';

        return new WP_REST_Response([
            'success' => true,
            'data' => [
                'business_name' => $biz_name,
                'currency' => $currency,
                'assets' => [
                    'cash' => $cash,
                    'accounts_receivable' => $ar,
                    'external' => $al['assets'] ?? [],
                    'external_total' => round($ext_assets, 2),
                    'total' => $total_assets,
                ],
                'liabilities' => [
                    'sales_tax_owed' => $tax_owed,
                    'external' => $al['liabilities'] ?? [],
                    'external_total' => round($ext_liabilities, 2),
                    'total' => $total_liabilities,
                ],
                'net_worth' => $net_worth,
                'health' => $net_worth > 0 ? 'positive' : ($net_worth === 0.0 ? 'neutral' : 'negative'),
                'ytd_revenue' => round($last_year_rev['gross_income'], 2),
                'calculated_at' => current_time('mysql'),
            ],
        ], 200);
    }

    // ═══════════════════════════════════════════════════════════════════
    // EXTERNAL ASSETS & LIABILITIES
    // ═══════════════════════════════════════════════════════════════════

    public function save_assets_liabilities(WP_REST_Request $req) {
        $uid = get_current_user_id();
        $p = $req->get_json_params() ?: [];

        $data = ['assets' => [], 'liabilities' => []];

        foreach (['assets', 'liabilities'] as $type) {
            if (is_array($p[$type] ?? null)) {
                foreach ($p[$type] as $item) {
                    $data[$type][] = [
                        'name' => sanitize_text_field($item['name'] ?? ''),
                        'category' => sanitize_text_field($item['category'] ?? 'other'),
                        'value' => floatval($item['value'] ?? 0),
                        'note' => sanitize_text_field($item['note'] ?? ''),
                        'date' => sanitize_text_field($item['date'] ?? date('Y-m-d')),
                    ];
                }
            }
        }

        // Also save declared overhead and other income if provided
        if (isset($p['declared_overhead'])) {
            update_user_meta($uid, 'vmo_declared_overhead', floatval($p['declared_overhead']));
        }
        if (isset($p['other_income'])) {
            update_user_meta($uid, 'vmo_other_taxable_income', floatval($p['other_income']));
        }

        update_user_meta($uid, 'vmo_assets_liabilities', $data);
        return new WP_REST_Response(['success' => true, 'saved' => count($data['assets']) + count($data['liabilities'])], 200);
    }

    public function get_assets_liabilities(WP_REST_Request $req) {
        $uid = get_current_user_id();
        $al = get_user_meta($uid, 'vmo_assets_liabilities', true) ?: ['assets' => [], 'liabilities' => []];
        return new WP_REST_Response([
            'success' => true,
            'data' => $al,
            'declared_overhead' => floatval(get_user_meta($uid, 'vmo_declared_overhead', true) ?: 0),
            'other_income' => floatval(get_user_meta($uid, 'vmo_other_taxable_income', true) ?: 0),
        ], 200);
    }
}
