<?php
namespace ComptaFlowPro\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-by-meetempo'));
        }
    
        self::handleActions();
    
        echo '<div class="wrap">';
        echo '<h1>' . esc_html__('ComptaFlow Settings', 'comptaflow-by-meetempo') . '</h1>';
    
        self::showMessages();
    
        echo '<h2 class="nav-tab-wrapper"><a href="#" class="nav-tab nav-tab-active">' . esc_html__('Company & Tax', 'comptaflow-by-meetempo') . '</a></h2>';
        
        self::renderCompanySettings();
            
        echo '</div>';
    }
    
    private static function renderCompanySettings(): void {
        $company_data = get_option('comptaflow_company_settings', []);
        
        echo '<form method="post">';
        wp_nonce_field('comptaflow_company_settings');
        echo '<input type="hidden" name="action" value="save_company">';
        
        echo '<h3>' . esc_html__('Company Information', 'comptaflow-by-meetempo') . '</h3>';
        echo '<table class="form-table">';
        
        // Company name
        echo '<tr>';
        echo '<th><label for="company_name">' . esc_html__('Company Name', 'comptaflow-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 legal name (e.g., MY LLC, ACME Corp, etc.)', 'comptaflow-by-meetempo') . '</p>';
        echo '</td>';
        echo '</tr>';
        
        // SIRET (French business ID)
        echo '<tr>';
        echo '<th><label for="siret">' . esc_html__('SIRET', 'comptaflow-by-meetempo') . ' *</label></th>';
        echo '<td><input type="text" id="siret" name="siret" value="' . esc_attr($company_data['siret'] ?? '') . '" class="regular-text" maxlength="14" pattern="[0-9]{14}" required>';
        echo '<p class="description">' . esc_html__('14 digits without spaces (required for FEC and Tax Return)', 'comptaflow-by-meetempo') . '</p>';
        echo '</td>';
        echo '</tr>';
        
        // Address
        echo '<tr>';
        echo '<th><label for="address">' . esc_html__('Address', 'comptaflow-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-by-meetempo') . '</p>';
        echo '</td>';
        echo '</tr>';
        
        echo '<tr>';
        echo '<th><label for="postal_code">' . esc_html__('Postal Code', 'comptaflow-by-meetempo') . ' *</label></th>';
        echo '<td><input type="text" id="postal_code" name="postal_code" value="' . esc_attr($company_data['postal_code'] ?? '') . '" maxlength="5" pattern="[0-9]{5}" required style="width: 100px;">';
        echo '</td>';
        echo '</tr>';
        
        echo '<tr>';
        echo '<th><label for="city">' . esc_html__('City', 'comptaflow-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>';
        
        // NAF Code (optional)
        echo '<tr>';
        echo '<th><label for="naf_code">' . esc_html__('NAF/APE Code', 'comptaflow-by-meetempo') . '</label></th>';
        echo '<td><input type="text" id="naf_code" name="naf_code" value="' . esc_attr($company_data['naf_code'] ?? '') . '" maxlength="6" style="width: 100px;">';
        echo '<p class="description">' . esc_html__('Optional - Format: 6201Z', 'comptaflow-by-meetempo') . '</p>';
        echo '</td>';
        echo '</tr>';
        
        // Legal status
        echo '<tr><th><label for="company_status">' . esc_html__('Legal Status', 'comptaflow-by-meetempo') . ' *</label></th><td>';
        echo '<select id="company_status" name="company_status" required>';
        $selected = $company_data['status'] ?? '';
        $statuses = [
            'AE' => __('Sole Proprietor', 'comptaflow-by-meetempo'), 
            'EURL' => __('EURL (Single-member LLC)', 'comptaflow-by-meetempo'), 
            'SARL' => __('SARL (LLC)', 'comptaflow-by-meetempo'), 
            'SAS' => __('SAS (Simplified Joint-Stock)', 'comptaflow-by-meetempo'), 
            'SASU' => __('SASU (Single-member SAS)', 'comptaflow-by-meetempo')
        ];
        foreach ($statuses as $key => $label) {
            echo '<option value="' . esc_attr($key) . '"' . selected($selected, $key, false) . '>' . esc_html($label) . '</option>';
        }
        echo '</select></td></tr>';
        
        // VAT Number
        echo '<tr>';
        echo '<th><label for="vat_number">' . esc_html__('VAT Number (EU)', 'comptaflow-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: FR12345678901 (optional if VAT exempt)', 'comptaflow-by-meetempo') . '</p>';
        echo '</td>';
        echo '</tr>';
        
        // VAT Regime
        echo '<tr><th><label for="vat_regime">' . esc_html__('VAT Regime', 'comptaflow-by-meetempo') . ' *</label></th><td>';
        echo '<select id="vat_regime_selector" name="vat_regime" required>';
        $selected_regime = $company_data['vat_regime'] ?? 'FRANCHISE';
        $regimes = [
            'FRANCHISE' => __('VAT Exempt (Franchise)', 'comptaflow-by-meetempo'), 
            'REEL' => __('Standard VAT (CA3 - Monthly/Quarterly)', 'comptaflow-by-meetempo'), 
            'SIMPLIFIE' => __('Simplified VAT (CA12 - Annual)', 'comptaflow-by-meetempo')
        ];
        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 simplified regime CA12
        $style_ca12 = ($selected_regime === 'SIMPLIFIE') ? '' : 'style="display:none;"';
        
        echo '<tr class="ca12-fields-row" ' . $style_ca12 . '>';
        echo '<th><label for="ca12_base_n1">' . esc_html__('Installment Base (Y-1)', 'comptaflow-by-meetempo') . '</label></th>';
        echo '<td>';
        echo '<input type="number" step="0.01" id="ca12_base_n1" name="ca12_base_n1" value="' . esc_attr($company_data['ca12_base_n1'] ?? '0') . '" class="regular-text"> €';
        echo '<p class="description">' . esc_html__('Line 57 from your CA12 declaration last year (VAT due). Leave 0 if first year.', 'comptaflow-by-meetempo') . '</p>';
        echo '</td>';
        echo '</tr>';
        
        echo '<tr class="ca12-fields-row" ' . $style_ca12 . '>';
        echo '<th><label for="ca12_advances_paid_n1">' . esc_html__('Installments Paid (Y-1)', 'comptaflow-by-meetempo') . '</label></th>';
        echo '<td>';
        echo '<input type="number" step="0.01" id="ca12_advances_paid_n1" name="ca12_advances_paid_n1" value="' . esc_attr($company_data['ca12_advances_paid_n1'] ?? '0') . '" class="regular-text"> €';
        echo '<p class="description">' . esc_html__('Total of the 2 semi-annual installments paid last year. Leave 0 if first year.', 'comptaflow-by-meetempo') . '</p>';
        echo '</td>';
        echo '</tr>';
        
        echo '</table>';
        
        echo '<h3>' . esc_html__('Fiscal Year', 'comptaflow-by-meetempo') . '</h3>';
        echo '<table class="form-table">';
        
        echo '<tr><th>' . esc_html__('Year Type', 'comptaflow-by-meetempo') . '</th><td>';
        $exercise_type = $company_data['exercise_type'] ?? 'civil';
        echo '<label><input type="radio" name="exercise_type" value="civil" ' . checked($exercise_type, 'civil', false) . '> ' . esc_html__('Calendar year (January 1 to December 31)', 'comptaflow-by-meetempo') . '</label><br>';
        echo '<label><input type="radio" name="exercise_type" value="custom" ' . checked($exercise_type, 'custom', false) . '> ' . esc_html__('Custom fiscal year', 'comptaflow-by-meetempo') . '</label>';
        echo '</td></tr>';
        
        $style_custom = ($exercise_type === 'custom') ? '' : 'style="display:none;"';
        echo '<tr class="custom-exercise-row" ' . $style_custom . '>';
        echo '<th>' . esc_html__('Closing Month', 'comptaflow-by-meetempo') . '</th><td>';
        echo '<select name="exercise_end_month">';
        $selected_month = $company_data['exercise_end_month'] ?? '12';
        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(__('Save Settings', 'comptaflow-by-meetempo'));
        echo '</form>';
    }
    
    private static function handleActions(): void {
        if (!isset($_POST['action']) || $_POST['action'] !== 'save_company') {
            return;
        }
        
        $nonce = isset($_POST['_wpnonce']) ? sanitize_text_field(wp_unslash($_POST['_wpnonce'])) : '';
        if (!wp_verify_nonce($nonce, 'comptaflow_company_settings')) {
            return;
        }
        
        $current_settings = get_option('comptaflow_company_settings', []);
        
        $data = [
            'company_name' => isset($_POST['company_name']) ? sanitize_text_field(wp_unslash($_POST['company_name'])) : '',
            'siret' => isset($_POST['siret']) ? preg_replace('/[^0-9]/', '', sanitize_text_field(wp_unslash($_POST['siret']))) : '',
            'address' => isset($_POST['address']) ? sanitize_text_field(wp_unslash($_POST['address'])) : '',
            'postal_code' => isset($_POST['postal_code']) ? sanitize_text_field(wp_unslash($_POST['postal_code'])) : '',
            'city' => isset($_POST['city']) ? sanitize_text_field(wp_unslash($_POST['city'])) : '',
            'naf_code' => isset($_POST['naf_code']) ? sanitize_text_field(wp_unslash($_POST['naf_code'])) : '',
            'status' => isset($_POST['company_status']) ? sanitize_text_field(wp_unslash($_POST['company_status'])) : '',
            'vat_number' => isset($_POST['vat_number']) ? sanitize_text_field(wp_unslash($_POST['vat_number'])) : '',
            'vat_regime' => isset($_POST['vat_regime']) ? sanitize_text_field(wp_unslash($_POST['vat_regime'])) : '',
            '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'])) : '12',
            'ca12_base_n1' => isset($_POST['ca12_base_n1']) ? floatval($_POST['ca12_base_n1']) : 0,
            'ca12_advances_paid_n1' => isset($_POST['ca12_advances_paid_n1']) ? floatval($_POST['ca12_advances_paid_n1']) : 0,
        ];
        
        // Validate SIRET
        if (strlen($data['siret']) !== 14) {
            add_settings_error('comptaflow_settings', 'error', __('SIRET must contain exactly 14 digits.', 'comptaflow-by-meetempo'));
            return;
        }
        
        update_option('comptaflow_company_settings', array_merge($current_settings, $data));
        add_settings_error('comptaflow_settings', 'saved', __('Company settings saved!', 'comptaflow-by-meetempo'), 'updated');
    }
    
    private static function showMessages(): void {
        settings_errors('comptaflow_settings');
    }
}
