<?php
namespace ComptaFlowUK\Admin\Screens;

defined('ABSPATH') || exit;

class SettingsScreen {
    public static function render(): void {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have sufficient permissions.', 'comptaflow-uk-by-meetempo'));
        }
    
        self::handleActions();
    
        echo '<div class="wrap">';
        echo '<h1>' . esc_html__('ComptaFlow UK Settings', 'comptaflow-uk-by-meetempo') . '</h1>';
    
        self::showMessages();
        self::renderCompanySettings();
            
        echo '</div>';
    }
    
    private static function renderCompanySettings(): void {
        $company_data = get_option('comptaflow_uk_company_settings', []);
        
        echo '<form method="post">';
        wp_nonce_field('comptaflow_uk_company_settings');
        echo '<input type="hidden" name="action" value="save_company">';
        
        echo '<h3>' . esc_html__('Company Information', 'comptaflow-uk-by-meetempo') . '</h3>';
        echo '<table class="form-table">';
        
        // Company name
        echo '<tr>';
        echo '<th><label for="company_name">' . esc_html__('Company Name *', 'comptaflow-uk-by-meetempo') . '</label></th>';
        echo '<td><input type="text" id="company_name" name="company_name" value="' . esc_attr($company_data['company_name'] ?? '') . '" class="regular-text" required>';
        echo '<p class="description">' . esc_html__('Full registered name (e.g. Acme Trading Ltd, Smith & Co LLP)', 'comptaflow-uk-by-meetempo') . '</p>';
        echo '</td>';
        echo '</tr>';
        
        // Company Number with Companies House lookup
        echo '<tr>';
        echo '<th><label for="company_number">' . esc_html__('Company Number *', 'comptaflow-uk-by-meetempo') . '</label></th>';
        echo '<td>';
        echo '<input type="text" id="company_number" name="company_number" value="' . esc_attr($company_data['company_number'] ?? '') . '" style="width: 200px;" maxlength="8" pattern="[0-9A-Z]{8}" required>';
        echo ' <button type="button" id="search-company-btn" class="button">🔍 Look up</button>';
        echo '<span id="company-loader" style="display:none; margin-left: 10px;">⏳ Searching...</span>';
        echo '<p class="description">8 characters — Click Look up to auto-fill from Companies House</p>';
        echo '<div id="company-result" style="display:none; margin-top: 10px; padding: 10px; background: #f0f9e8; border-left: 4px solid #46b450;"></div>';
        echo '<div id="company-error" style="display:none; margin-top: 10px; padding: 10px; background: #fef7f1; border-left: 4px solid #dc3232;"></div>';
        echo '</td>';
        echo '</tr>';
        
        // Address
        echo '<tr>';
        echo '<th><label for="address">' . esc_html__('Address *', 'comptaflow-uk-by-meetempo') . '</label></th>';
        echo '<td><input type="text" id="address" name="address" value="' . esc_attr($company_data['address'] ?? '') . '" class="regular-text" required>';
        echo '<p class="description">' . esc_html__('Street number and name', 'comptaflow-uk-by-meetempo') . '</p>';
        echo '</td>';
        echo '</tr>';
        
        echo '<tr>';
        echo '<th><label for="city">' . esc_html__('City / Town *', 'comptaflow-uk-by-meetempo') . '</label></th>';
        echo '<td><input type="text" id="city" name="city" value="' . esc_attr($company_data['city'] ?? '') . '" class="regular-text" required>';
        echo '</td>';
        echo '</tr>';
        
        echo '<tr>';
        echo '<th><label for="postcode">' . esc_html__('Postcode *', 'comptaflow-uk-by-meetempo') . '</label></th>';
        echo '<td><input type="text" id="postcode" name="postcode" value="' . esc_attr($company_data['postcode'] ?? '') . '" maxlength="8" required style="width: 120px;">';
        echo '</td>';
        echo '</tr>';
        
        // SIC Code (optional)
        echo '<tr>';
        echo '<th><label for="sic_code">' . esc_html__('SIC Code', 'comptaflow-uk-by-meetempo') . '</label></th>';
        echo '<td><input type="text" id="sic_code" name="sic_code" value="' . esc_attr($company_data['sic_code'] ?? '') . '" maxlength="5" style="width: 100px;">';
        echo '<p class="description">' . esc_html__('Optional — Standard Industrial Classification code (e.g. 62012)', 'comptaflow-uk-by-meetempo') . '</p>';
        echo '</td>';
        echo '</tr>';

        // Company email
        echo '<tr>';
        echo '<th><label for="company_email">' . esc_html__('Company Email *', 'comptaflow-uk-by-meetempo') . '</label></th>';
        echo '<td><input type="email" id="company_email" name="company_email" value="' . esc_attr($company_data['company_email'] ?? '') . '" class="regular-text" required>';
        echo '<p class="description">' . esc_html__('Main company contact email', 'comptaflow-uk-by-meetempo') . '</p>';
        echo '</td>';
        echo '</tr>';
        
        // Phone
        echo '<tr>';
        echo '<th><label for="company_phone">' . esc_html__('Phone', 'comptaflow-uk-by-meetempo') . '</label></th>';
        echo '<td><input type="tel" id="company_phone" name="company_phone" value="' . esc_attr($company_data['company_phone'] ?? '') . '" class="regular-text">';
        echo '</td>';
        echo '</tr>';
        
        // Website
        echo '<tr>';
        echo '<th><label for="company_website">' . esc_html__('Website', 'comptaflow-uk-by-meetempo') . '</label></th>';
        echo '<td><input type="url" id="company_website" name="company_website" value="' . esc_attr($company_data['company_website'] ?? '') . '" class="regular-text" placeholder="https://">';
        echo '</td>';
        echo '</tr>';
        
        // Company logo
        echo '<tr>';
        echo '<th><label for="company_logo">' . esc_html__('Company Logo', 'comptaflow-uk-by-meetempo') . '</label></th>';
        echo '<td>';
        $logo_id = $company_data['company_logo_id'] ?? '';
        $logo_url = $logo_id ? wp_get_attachment_image_url($logo_id, 'medium') : '';
        echo '<div id="logo-preview" style="margin-bottom: 10px;">';
        if ($logo_url) {
            echo '<img src="' . esc_url($logo_url) . '" style="max-width: 200px; max-height: 100px;">';
        }
        echo '</div>';
        echo '<input type="hidden" id="company_logo_id" name="company_logo_id" value="' . esc_attr($logo_id) . '">';
        echo '<button type="button" class="button" id="upload-logo-btn">Choose a logo</button>';
        if ($logo_id) {
            echo ' <button type="button" class="button" id="remove-logo-btn">Remove</button>';
        }
        echo '<p class="description">' . esc_html__('Recommended format: PNG or JPG, 300x100 px max', 'comptaflow-uk-by-meetempo') . '</p>';
        echo '</td>';
        echo '</tr>';
        
        // Legal structure
        echo '<tr><th><label for="company_status">Legal Structure *</label></th><td>';
        echo '<select id="company_status" name="company_status" required>';
        $selected = $company_data['status'] ?? '';
        $statuses = ['SOLE_TRADER' => 'Sole Trader', 'PARTNERSHIP' => 'Partnership', 'LLP' => 'LLP', 'LTD' => 'Limited Company (Ltd)', 'PLC' => 'PLC'];
        foreach ($statuses as $key => $label) {
            echo '<option value="' . esc_attr($key) . '"' . selected($selected, $key, false) . '>' . esc_html($label) . '</option>';
        }
        echo '</select></td></tr>';

        // Share capital (conditional — not for Sole Trader/Partnership)
        $show_capital = in_array($selected, ['LLP', 'LTD', 'PLC']);
        echo '<tr class="capital-row"' . ($show_capital ? '' : ' style="display:none;"') . '>';
        echo '<th><label for="share_capital">' . esc_html__('Share Capital', 'comptaflow-uk-by-meetempo') . '</label></th>';
        echo '<td>£ <input type="number" step="0.01" id="share_capital" name="share_capital" value="' . esc_attr($company_data['share_capital'] ?? '') . '" style="width: 150px;">';
        echo '<p class="description">' . esc_html__('Required for statutory filing and invoice legal mentions', 'comptaflow-uk-by-meetempo') . '</p>';
        echo '</td>';
        echo '</tr>';

        // Registered office (conditional — not for Sole Trader)
        echo '<tr class="capital-row"' . ($show_capital ? '' : ' style="display:none;"') . '>';
        echo '<th><label for="registered_office">' . esc_html__('Registered Office', 'comptaflow-uk-by-meetempo') . '</label></th>';
        echo '<td><input type="text" id="registered_office" name="registered_office" value="' . esc_attr($company_data['registered_office'] ?? '') . '" class="regular-text">';
        echo '<p class="description">e.g. Registered in England and Wales</p>';
        echo '</td>';
        echo '</tr>';
        
        // VAT Registration Number
        echo '<tr>';
        echo '<th><label for="vat_number">' . esc_html__('VAT Registration Number', 'comptaflow-uk-by-meetempo') . '</label></th>';
        echo '<td><input type="text" id="vat_number" name="vat_number" value="' . esc_attr($company_data['vat_number'] ?? '') . '" class="regular-text">';
        echo '<p class="description">' . esc_html__('Format: GB123456789 (leave blank if not VAT registered)', 'comptaflow-uk-by-meetempo') . '</p>';
        echo '</td>';
        echo '</tr>';
        
        // VAT Scheme
        echo '<tr><th><label for="vat_regime">VAT Scheme *</label></th><td>';
        echo '<select id="vat_regime_selector" name="vat_scheme" required>';
        $selected_regime = $company_data['vat_scheme'] ?? 'NOT_REGISTERED';
        $regimes = ['NOT_REGISTERED' => 'Not VAT Registered', 'STANDARD' => 'Standard VAT (quarterly returns)', 'FLAT_RATE' => 'Flat Rate Scheme', 'ANNUAL' => 'Annual Accounting Scheme'];
        foreach ($regimes as $key => $label) {
            echo '<option value="' . esc_attr($key) . '"' . selected($selected_regime, $key, false) . '>' . esc_html($label) . '</option>';
        }
        echo '</select></td></tr>';

        // Conditional fields for Annual Accounting Scheme
        $show_annual = ($selected_regime === 'ANNUAL');

        echo '<tr class="annual-fields-row"' . ($show_annual ? '' : ' style="display:none;"') . '>';
        echo '<th><label for="annual_base_n1">' . esc_html__('Estimated VAT liability (previous year)', 'comptaflow-uk-by-meetempo') . '</label></th>';
        echo '<td>';
        echo '£ <input type="number" step="0.01" id="annual_base_n1" name="annual_base_n1" value="' . esc_attr($company_data['annual_base_n1'] ?? '0') . '" class="regular-text">';
        echo '<p class="description">' . esc_html__('Total VAT due from last year. Used to calculate interim payments. Leave 0 if first year.', 'comptaflow-uk-by-meetempo') . '</p>';
        echo '</td>';
        echo '</tr>';
        
        echo '<tr class="annual-fields-row"' . ($show_annual ? '' : ' style="display:none;"') . '>';
        echo '<th><label for="annual_payments_made_n1">' . esc_html__('Interim payments already made', 'comptaflow-uk-by-meetempo') . '</label></th>';
        echo '<td>';
        echo '£ <input type="number" step="0.01" id="annual_payments_made_n1" name="annual_payments_made_n1" value="' . esc_attr($company_data['annual_payments_made_n1'] ?? '0') . '" class="regular-text">';
        echo '<p class="description">' . esc_html__('Total interim payments made last year. Leave 0 if first year.', 'comptaflow-uk-by-meetempo') . '</p>';
        echo '</td>';
        echo '</tr>';
        
        echo '</table>';
        
        // Bank details section
        echo '<h3>' . esc_html__('Bank Details', 'comptaflow-uk-by-meetempo') . '</h3>';
        echo '<table class="form-table">';
        
        echo '<tr>';
        echo '<th><label for="sort_code">' . esc_html__('Sort Code', 'comptaflow-uk-by-meetempo') . '</label></th>';
        echo '<td><input type="text" id="sort_code" name="sort_code" value="' . esc_attr($company_data['sort_code'] ?? '') . '" style="width: 120px;" placeholder="00-00-00" maxlength="8">';
        echo '</td>';
        echo '</tr>';
        
        echo '<tr>';
        echo '<th><label for="account_number">' . esc_html__('Account Number', 'comptaflow-uk-by-meetempo') . '</label></th>';
        echo '<td><input type="text" id="account_number" name="account_number" value="' . esc_attr($company_data['account_number'] ?? '') . '" style="width: 150px;" placeholder="12345678" maxlength="8">';
        echo '<p class="description">' . esc_html__('Displayed on your invoices to facilitate payment', 'comptaflow-uk-by-meetempo') . '</p>';
        echo '</td>';
        echo '</tr>';
        
        echo '<tr>';
        echo '<th><label for="iban">' . esc_html__('IBAN (optional)', 'comptaflow-uk-by-meetempo') . '</label></th>';
        echo '<td><input type="text" id="iban" name="iban" value="' . esc_attr($company_data['iban'] ?? '') . '" class="regular-text" placeholder="GB00 XXXX XXXX XXXX XXXX XX">';
        echo '<p class="description">' . esc_html__('For international payments', 'comptaflow-uk-by-meetempo') . '</p>';
        echo '</td>';
        echo '</tr>';
        
        echo '</table>';
        
        echo '<h3>' . esc_html__('Invoicing Settings', 'comptaflow-uk-by-meetempo') . '</h3>';
        echo '<table class="form-table">';

        echo '<tr>';
        echo '<th><label for="invoice_prefix">' . esc_html__('Invoice Prefix', 'comptaflow-uk-by-meetempo') . '</label></th>';
        echo '<td><input type="text" id="invoice_prefix" name="invoice_prefix" value="' . esc_attr($company_data['invoice_prefix'] ?? 'INV') . '" style="width: 100px;">';
        echo '<p class="description">' . esc_html__('Prefix for invoice numbers (e.g. INV, FA)', 'comptaflow-uk-by-meetempo') . '</p>';
        echo '</td>';
        echo '</tr>';

        echo '<tr>';
        echo '<th><label for="default_payment_terms">' . esc_html__('Default Payment Terms (days)', 'comptaflow-uk-by-meetempo') . '</label></th>';
        echo '<td><input type="number" id="default_payment_terms" name="default_payment_terms" value="' . esc_attr($company_data['default_payment_terms'] ?? 30) . '" min="0" style="width: 80px;">';
        echo '</td>';
        echo '</tr>';

        echo '<tr>';
        echo '<th><label for="invoice_terms">' . esc_html__('Default Terms & Conditions', 'comptaflow-uk-by-meetempo') . '</label></th>';
        echo '<td><textarea id="invoice_terms" name="invoice_terms" rows="3" class="large-text">' . esc_textarea($company_data['invoice_terms'] ?? __('Payment due within the terms stated. Late payment interest may apply under the Late Payment of Commercial Debts Act 1998.', 'comptaflow-uk-by-meetempo')) . '</textarea>';
        echo '</td>';
        echo '</tr>';

        echo '</table>';

        echo '<h3>' . esc_html__('Accounting Year', 'comptaflow-uk-by-meetempo') . '</h3>';
        echo '<table class="form-table">';
        
        echo '<tr><th>' . esc_html__('Year End Type', 'comptaflow-uk-by-meetempo') . '</th><td>';
        $exercise_type = $company_data['exercise_type'] ?? 'standard';
        echo '<label><input type="radio" name="exercise_type" value="standard" ' . checked($exercise_type, 'standard', false) . '> Standard year end (1 April to 31 March)</label><br>';
        echo '<label><input type="radio" name="exercise_type" value="custom" ' . checked($exercise_type, 'custom', false) . '> Custom year end</label>';
        echo '</td></tr>';
        
        $show_custom = ($exercise_type === 'custom');
        echo '<tr class="custom-exercise-row"' . ($show_custom ? '' : ' style="display:none;"') . '>';
        echo '<th>Year End Month</th><td>';
        echo '<select name="exercise_end_month">';
        $selected_month = $company_data['exercise_end_month'] ?? '3';
        for ($i = 1; $i <= 12; $i++) {
            $month_name = date_i18n('F', mktime(0, 0, 0, $i, 10));
            echo '<option value="' . esc_attr($i) . '"' . selected($selected_month, $i, false) . '>' . esc_html($month_name) . '</option>';
        }
        echo '</select></td></tr>';
        
        echo '</table>';
        
        submit_button(esc_html__('Save Settings', 'comptaflow-uk-by-meetempo'));
        echo '</form>';
        
        // JavaScript for Companies House lookup
        self::renderCompanySearchScript();
    }

    private static function renderCompanySearchScript(): void {
        $nonce = wp_create_nonce('comptaflow_uk_company_search');
        $inline_js = "jQuery(document).ready(function(\$) {"
            . "\$('#search-company-btn').on('click', function() {"
            . "var companyNumber = \$('#company_number').val().replace(/\\s/g, '');"
            . "if (companyNumber.length !== 8) {"
            . "\$('#company-error').html('Company number must be 8 characters.').show();"
            . "\$('#company-result').hide();"
            . "return;"
            . "}"
            . "\$('#company-loader').show();"
            . "\$('#company-error, #company-result').hide();"
            . "\$.ajax({"
            . "url: ajaxurl,"
            . "type: 'POST',"
            . "data: {"
            . "action: 'comptaflow_uk_search_company',"
            . "company_number: companyNumber,"
            . "_wpnonce: '" . esc_js($nonce) . "'"
            . "},"
            . "success: function(response) {"
            . "\$('#company-loader').hide();"
            . "if (response.success && response.data) {"
            . "var d = response.data;"
            . "if (d.company_name) \$('#company_name').val(d.company_name);"
            . "if (d.address) \$('#address').val(d.address);"
            . "if (d.locality) \$('#city').val(d.locality);"
            . "if (d.postcode) \$('#postcode').val(d.postcode);"
            . "if (d.sic_code) \$('#sic_code').val(d.sic_code);"
            . "\$('#company-result').html('<strong>' + d.company_name + '</strong><br>' + d.address + ', ' + d.locality + ' ' + d.postcode + (d.sic_code ? '<br>SIC: ' + d.sic_code : '')).show();"
            . "\$('#company-error').hide();"
            . "} else {"
            . "\$('#company-error').html(response.data || 'Company not found.').show();"
            . "\$('#company-result').hide();"
            . "}"
            . "},"
            . "error: function() {"
            . "\$('#company-loader').hide();"
            . "\$('#company-error').html('Error connecting to Companies House API.').show();"
            . "}"
            . "});"
            . "});"
            . "\$('#company_number').on('keypress', function(e) {"
            . "if (e.which === 13) { e.preventDefault(); \$('#search-company-btn').click(); }"
            . "});"
            . "\$('#company_status').on('change', function() {"
            . "var val = \$(this).val();"
            . "if (['LLP', 'LTD', 'PLC'].indexOf(val) !== -1) { \$('.capital-row').show(); } else { \$('.capital-row').hide(); }"
            . "});"
            . "\$('#vat_regime_selector').on('change', function() {"
            . "if (\$(this).val() === 'ANNUAL') { \$('.annual-fields-row').show(); } else { \$('.annual-fields-row').hide(); }"
            . "});"
            . "\$('input[name=\"exercise_type\"]').on('change', function() {"
            . "if (\$(this).val() === 'custom') { \$('.custom-exercise-row').show(); } else { \$('.custom-exercise-row').hide(); }"
            . "});"
            . "});";
        wp_add_inline_script('comptaflow-uk-admin', $inline_js);
    }
    
    private static function handleActions(): void {
        $post_action = isset($_POST['action']) ? sanitize_text_field(wp_unslash($_POST['action'])) : '';
        if ($post_action !== 'save_company') {
            return;
        }
        
        $nonce = isset($_POST['_wpnonce']) ? sanitize_text_field(wp_unslash($_POST['_wpnonce'])) : '';
        if (!wp_verify_nonce($nonce, 'comptaflow_uk_company_settings')) {
            return;
        }
        
        $current_settings = get_option('comptaflow_uk_company_settings', []);
        
        $data = [
            // COMPANY INFORMATION
            'company_name' => isset($_POST['company_name']) ? sanitize_text_field(wp_unslash($_POST['company_name'])) : '',
            'company_number' => isset($_POST['company_number']) ? preg_replace('/[^0-9A-Z]/', '', strtoupper(sanitize_text_field(wp_unslash($_POST['company_number'])))) : '',
            'address' => isset($_POST['address']) ? sanitize_text_field(wp_unslash($_POST['address'])) : '',
            'postcode' => isset($_POST['postcode']) ? sanitize_text_field(wp_unslash($_POST['postcode'])) : '',
            'city' => isset($_POST['city']) ? sanitize_text_field(wp_unslash($_POST['city'])) : '',
            'sic_code' => isset($_POST['sic_code']) ? sanitize_text_field(wp_unslash($_POST['sic_code'])) : '',
            'company_email' => isset($_POST['company_email']) ? sanitize_email(wp_unslash($_POST['company_email'])) : '',
            'company_phone' => isset($_POST['company_phone']) ? sanitize_text_field(wp_unslash($_POST['company_phone'])) : '',
            'company_website' => isset($_POST['company_website']) ? esc_url_raw(wp_unslash($_POST['company_website'])) : '',
            'company_logo_id' => isset($_POST['company_logo_id']) ? absint($_POST['company_logo_id']) : '',
            
            // LEGAL STRUCTURE AND CAPITAL
            'status' => isset($_POST['company_status']) ? sanitize_text_field(wp_unslash($_POST['company_status'])) : '',
            'share_capital' => isset($_POST['share_capital']) ? floatval(wp_unslash($_POST['share_capital'])) : '',
            'registered_office' => isset($_POST['registered_office']) ? sanitize_text_field(wp_unslash($_POST['registered_office'])) : '',
            
            // VAT
            'vat_number' => isset($_POST['vat_number']) ? sanitize_text_field(wp_unslash($_POST['vat_number'])) : '',
            'vat_scheme' => isset($_POST['vat_scheme']) ? sanitize_text_field(wp_unslash($_POST['vat_scheme'])) : '',
            
            // ACCOUNTING YEAR
            'exercise_type' => isset($_POST['exercise_type']) ? sanitize_text_field(wp_unslash($_POST['exercise_type'])) : '',
            'exercise_end_month' => isset($_POST['exercise_end_month']) ? sanitize_text_field(wp_unslash($_POST['exercise_end_month'])) : '3',
            'annual_base_n1' => isset($_POST['annual_base_n1']) ? floatval(wp_unslash($_POST['annual_base_n1'])) : 0,
            'annual_payments_made_n1' => isset($_POST['annual_payments_made_n1']) ? floatval(wp_unslash($_POST['annual_payments_made_n1'])) : 0,
            
            // BANK DETAILS
            'sort_code' => isset($_POST['sort_code']) ? sanitize_text_field(wp_unslash($_POST['sort_code'])) : '',
            'account_number' => isset($_POST['account_number']) ? sanitize_text_field(wp_unslash($_POST['account_number'])) : '',
            'iban' => isset($_POST['iban']) ? sanitize_text_field(wp_unslash($_POST['iban'])) : '',

            // INVOICING
            'invoice_prefix' => isset($_POST['invoice_prefix']) ? sanitize_text_field(wp_unslash($_POST['invoice_prefix'])) : 'INV',
            'default_payment_terms' => isset($_POST['default_payment_terms']) ? absint($_POST['default_payment_terms']) : 30,
            'invoice_terms' => isset($_POST['invoice_terms']) ? sanitize_textarea_field(wp_unslash($_POST['invoice_terms'])) : '',
        ];
        
        // Validate Company Number
        if (strlen($data['company_number']) !== 8) {
            add_settings_error('comptaflow_uk_settings', 'error', __('Company number must be exactly 8 characters.', 'comptaflow-uk-by-meetempo'));
            return;
        }
        
        update_option('comptaflow_uk_company_settings', array_merge($current_settings, $data));
        add_settings_error('comptaflow_uk_settings', 'saved', __('Company settings saved successfully!', 'comptaflow-uk-by-meetempo'), 'updated');
    }
    
    private static function showMessages(): void {
        settings_errors('comptaflow_uk_settings');
    }
}
