<?php
namespace ComptaFlowPro\Admin\Screens;

use ComptaFlowPro\Services\DB;

defined('ABSPATH') || exit;

class VATSettingsScreen {
    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 class="wp-heading-inline">' . esc_html__('VAT Settings', 'comptaflow-by-meetempo') . '</h1>';
        echo '<a href="' . esc_url(admin_url('admin.php?page=comptaflow-vat-settings&action=new')) . '" class="page-title-action">' . esc_html__('Add Rate', 'comptaflow-by-meetempo') . '</a>';
        
        self::showMessages();
        
        $action = isset($_GET['action']) ? sanitize_key($_GET['action']) : 'list';
        
        if ($action === 'new' || $action === 'edit') {
            self::renderForm($action);
        } else {
            self::renderList();
        }
        
        echo '</div>';
    }
    
    private static function handleActions(): void {
        if (!isset($_POST['_wpnonce'])) {
            // Check for GET actions
            if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
                $nonce_delete = isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : '';
                if (wp_verify_nonce($nonce_delete, 'comptaflow_delete_vat')) {
                    self::deleteVATRate();
                }
            }
            
            if (isset($_GET['action']) && $_GET['action'] === 'toggle' && isset($_GET['id'])) {
                $nonce_toggle = isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : '';
                if (wp_verify_nonce($nonce_toggle, 'comptaflow_toggle_vat')) {
                    self::toggleVATRate();
                }
            }
            return;
        }
        
        $nonce_post = isset($_POST['_wpnonce']) ? sanitize_text_field(wp_unslash($_POST['_wpnonce'])) : '';
        if (wp_verify_nonce($nonce_post, 'comptaflow_vat_action')) {
            if (isset($_POST['action']) && ($_POST['action'] === 'create' || $_POST['action'] === 'update')) {
                self::saveVATRate();
            }
        }
    }
    
    private static function saveVATRate(): void {
        global $wpdb;
        $p = $wpdb->prefix . 'cfp_';
        
        // Validate required fields
        if (empty($_POST['rate_code']) || empty($_POST['rate_name']) || !isset($_POST['rate_value'])) {
            add_settings_error('comptaflow_vat', 'error', __('All required fields must be filled.', 'comptaflow-by-meetempo'));
            return;
        }
        
        $data = [
            'country_code' => isset($_POST['country_code']) ? sanitize_text_field(wp_unslash($_POST['country_code'])) : 'FR',
            'rate_code' => isset($_POST['rate_code']) ? sanitize_text_field(wp_unslash($_POST['rate_code'])) : '',
            'rate_value' => isset($_POST['rate_value']) ? floatval($_POST['rate_value']) : 0,
            'rate_name' => isset($_POST['rate_name']) ? sanitize_text_field(wp_unslash($_POST['rate_name'])) : '',
            'is_active' => isset($_POST['is_active']) ? 1 : 0,
            'valid_from' => !empty($_POST['valid_from']) ? sanitize_text_field(wp_unslash($_POST['valid_from'])) : null,
            'valid_to' => !empty($_POST['valid_to']) ? sanitize_text_field(wp_unslash($_POST['valid_to'])) : null,
        ];
        
        $id = intval($_POST['id'] ?? 0);
        
        try {
            if ($id) {
                // Update
                $data['updated_at'] = current_time('mysql');
                $result = $wpdb->update($p . 'vat_rates', $data, ['id' => $id]);
                
                if ($result === false) {
                    throw new \Exception(__('Database error during update:', 'comptaflow-by-meetempo') . ' ' . $wpdb->last_error);
                }
                
                $message = __('VAT rate updated successfully.', 'comptaflow-by-meetempo');
            } else {
                // Check if code already exists
                $existing = $wpdb->get_var($wpdb->prepare(
                    "SELECT id FROM {$p}vat_rates WHERE country_code = %s AND rate_code = %s",
                    $data['country_code'], $data['rate_code']
                ));
                
                if ($existing) {
                    throw new \Exception(__('A rate with this code already exists for this country.', 'comptaflow-by-meetempo'));
                }
                
                // Create
                $data['created_by'] = get_current_user_id();
                $data['created_at'] = current_time('mysql');
                
                $result = $wpdb->insert($p . 'vat_rates', $data);
                
                if ($result === false) {
                    throw new \Exception(__('Database error during creation:', 'comptaflow-by-meetempo') . ' ' . $wpdb->last_error);
                }
                
                $message = __('VAT rate created successfully.', 'comptaflow-by-meetempo');
            }
            
            add_settings_error('comptaflow_vat', 'saved', $message, 'updated');
            
        } catch (\Exception $e) {
            add_settings_error('comptaflow_vat', 'error', __('Error:', 'comptaflow-by-meetempo') . ' ' . $e->getMessage());
        }
    }
    
    private static function deleteVATRate(): void {
        $id = intval($_GET['id'] ?? 0);
        if (!$id) return;
        
        global $wpdb;
        $p = $wpdb->prefix . 'cfp_';
        
        // Check if rate is used in transactions
        $usage = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$p}transactions WHERE vat_code = (SELECT rate_code FROM {$p}vat_rates WHERE id = %d)",
            $id
        ));
        
        if ($usage > 0) {
            add_settings_error('comptaflow_vat', 'error', sprintf(
                /* translators: %d: number of transactions */
                __('Cannot delete this rate: it is used in %d transaction(s).', 'comptaflow-by-meetempo'),
                $usage
            ));
            return;
        }
        
        $wpdb->delete($p . 'vat_rates', ['id' => $id]);
        add_settings_error('comptaflow_vat', 'deleted', __('VAT rate deleted successfully.', 'comptaflow-by-meetempo'), 'updated');
    }
    
    private static function toggleVATRate(): void {
        $id = intval($_GET['id'] ?? 0);
        if (!$id) return;
        
        global $wpdb;
        $p = $wpdb->prefix . 'cfp_';
        
        $current_status = $wpdb->get_var($wpdb->prepare(
            "SELECT is_active FROM {$p}vat_rates WHERE id = %d",
            $id
        ));
        
        $new_status = $current_status ? 0 : 1;
        
        $wpdb->update($p . 'vat_rates', [
            'is_active' => $new_status,
            'updated_at' => current_time('mysql')
        ], ['id' => $id]);
        
        $message = $new_status ? __('VAT rate activated.', 'comptaflow-by-meetempo') : __('VAT rate deactivated.', 'comptaflow-by-meetempo');
        add_settings_error('comptaflow_vat', 'toggled', $message, 'updated');
    }
    
    private static function renderForm(string $action): void {
        $item = [];
        
        if ($action === 'edit') {
            $id = intval($_GET['id'] ?? 0);
            if ($id) {
                global $wpdb;
                $p = $wpdb->prefix . 'cfp_';
                $item = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$p}vat_rates WHERE id = %d", $id), ARRAY_A) ?? [];
            }
        }
        
        echo '<div style="max-width: 600px;">';
        echo '<h2>' . ($action === 'edit' ? esc_html__('Edit VAT Rate', 'comptaflow-by-meetempo') : esc_html__('New VAT Rate', 'comptaflow-by-meetempo')) . '</h2>';
        echo '<form method="post">';
        wp_nonce_field('comptaflow_vat_action');
        echo '<input type="hidden" name="action" value="' . ($action === 'edit' ? 'update' : 'create') . '">';
        
        if ($action === 'edit') {
            echo '<input type="hidden" name="id" value="' . esc_attr($item['id'] ?? '') . '">';
        }
        
        echo '<table class="form-table">';
        
        echo '<tr><th>' . esc_html__('Country', 'comptaflow-by-meetempo') . '</th><td>';
        echo '<select name="country_code" required>';
        $selected_country = $item['country_code'] ?? 'FR';
        $countries = [
            'FR' => __('France', 'comptaflow-by-meetempo'),
            'BE' => __('Belgium', 'comptaflow-by-meetempo'), 
            'CH' => __('Switzerland', 'comptaflow-by-meetempo'),
            'LU' => __('Luxembourg', 'comptaflow-by-meetempo'),
            'MC' => __('Monaco', 'comptaflow-by-meetempo'),
            'AD' => __('Andorra', 'comptaflow-by-meetempo'),
            'NC' => __('New Caledonia', 'comptaflow-by-meetempo'),
            'PF' => __('French Polynesia', 'comptaflow-by-meetempo'),
            'GP' => __('Guadeloupe', 'comptaflow-by-meetempo'),
            'MQ' => __('Martinique', 'comptaflow-by-meetempo'),
            'GF' => __('French Guiana', 'comptaflow-by-meetempo'),
            'RE' => __('Réunion', 'comptaflow-by-meetempo'),
            'YT' => __('Mayotte', 'comptaflow-by-meetempo'),
            'PM' => __('Saint Pierre and Miquelon', 'comptaflow-by-meetempo'),
            'WF' => __('Wallis and Futuna', 'comptaflow-by-meetempo'),
            'MA' => __('Morocco', 'comptaflow-by-meetempo'),
            'TN' => __('Tunisia', 'comptaflow-by-meetempo'),
            'SN' => __('Senegal', 'comptaflow-by-meetempo'),
            'CI' => __('Ivory Coast', 'comptaflow-by-meetempo'),
            'CM' => __('Cameroon', 'comptaflow-by-meetempo'),
            'BF' => __('Burkina Faso', 'comptaflow-by-meetempo'),
            'ML' => __('Mali', 'comptaflow-by-meetempo'),
            'NE' => __('Niger', 'comptaflow-by-meetempo'),
            'TD' => __('Chad', 'comptaflow-by-meetempo'),
            'CF' => __('Central African Republic', 'comptaflow-by-meetempo'),
            'CG' => __('Republic of the Congo', 'comptaflow-by-meetempo'),
            'GA' => __('Gabon', 'comptaflow-by-meetempo'),
            'MG' => __('Madagascar', 'comptaflow-by-meetempo'),
            'MU' => __('Mauritius', 'comptaflow-by-meetempo'),
            'SC' => __('Seychelles', 'comptaflow-by-meetempo'),
            'DJ' => __('Djibouti', 'comptaflow-by-meetempo'),
            'KM' => __('Comoros', 'comptaflow-by-meetempo'),
            'VU' => __('Vanuatu', 'comptaflow-by-meetempo')
        ];
        foreach ($countries as $code => $name) {
            echo '<option value="' . esc_attr($code) . '"' . selected($selected_country, $code, false) . '>' . esc_html($name) . '</option>';
        }
        echo '</select>';
        echo '<p class="description">' . esc_html__('Select the country for this VAT rate', 'comptaflow-by-meetempo') . '</p>';
        echo '</td></tr>';
        
        echo '<tr><th>' . esc_html__('Rate Code', 'comptaflow-by-meetempo') . ' *</th><td>';
        echo '<input type="text" name="rate_code" value="' . esc_attr($item['rate_code'] ?? '') . '" required class="regular-text" placeholder="' . esc_attr__('e.g., FR-20', 'comptaflow-by-meetempo') . '">';
        echo '<p class="description">' . esc_html__('Unique code to identify the rate (e.g., FR-20, FR-10)', 'comptaflow-by-meetempo') . '</p>';
        echo '</td></tr>';
        
        echo '<tr><th>' . esc_html__('Rate (%)', 'comptaflow-by-meetempo') . ' *</th><td>';
        echo '<input type="number" name="rate_value" value="' . esc_attr($item['rate_value'] ?? '') . '" step="0.01" min="0" max="100" required>';
        echo '<p class="description">' . esc_html__('VAT rate as percentage (e.g., 20.00)', 'comptaflow-by-meetempo') . '</p>';
        echo '</td></tr>';
        
        echo '<tr><th>' . esc_html__('Label', 'comptaflow-by-meetempo') . ' *</th><td>';
        echo '<input type="text" name="rate_name" value="' . esc_attr($item['rate_name'] ?? '') . '" required class="regular-text" placeholder="' . esc_attr__('e.g., Standard rate', 'comptaflow-by-meetempo') . '">';
        echo '<p class="description">' . esc_html__('Description that will appear in forms', 'comptaflow-by-meetempo') . '</p>';
        echo '</td></tr>';
        
        echo '<tr><th>' . esc_html__('Validity Period', 'comptaflow-by-meetempo') . '</th><td>';
        echo '<label>' . esc_html__('From:', 'comptaflow-by-meetempo') . ' <input type="date" name="valid_from" value="' . esc_attr($item['valid_from'] ?? '') . '"></label><br>';
        echo '<label style="margin-top: 5px; display: inline-block;">' . esc_html__('To:', 'comptaflow-by-meetempo') . ' <input type="date" name="valid_to" value="' . esc_attr($item['valid_to'] ?? '') . '"></label>';
        echo '<p class="description">' . esc_html__('Leave empty for permanent validity', 'comptaflow-by-meetempo') . '</p>';
        echo '</td></tr>';
        
        echo '<tr><th>' . esc_html__('Status', 'comptaflow-by-meetempo') . '</th><td>';
        echo '<label><input type="checkbox" name="is_active" value="1"' . checked($item['is_active'] ?? 1, 1, false) . '> ' . esc_html__('Active', 'comptaflow-by-meetempo') . '</label>';
        echo '<p class="description">' . esc_html__('Only active rates appear in forms', 'comptaflow-by-meetempo') . '</p>';
        echo '</td></tr>';
        
        echo '</table>';
        
        submit_button($action === 'edit' ? __('Update', 'comptaflow-by-meetempo') : __('Create', 'comptaflow-by-meetempo'));
        echo '</form>';
        echo '</div>';
    }
    
    private static function renderList(): void {
        global $wpdb;
        $p = $wpdb->prefix . 'cfp_';
        
        $rates = $wpdb->get_results("SELECT * FROM {$p}vat_rates ORDER BY country_code, rate_value DESC");
        
        if (empty($rates)) {
            echo '<p>' . esc_html__('No VAT rates configured.', 'comptaflow-by-meetempo') . '</p>';
            return;
        }
        
        echo '<table class="wp-list-table widefat fixed striped">';
        echo '<thead><tr>';
        echo '<th style="width: 60px;">' . esc_html__('Country', 'comptaflow-by-meetempo') . '</th>';
        echo '<th style="width: 80px;">' . esc_html__('Code', 'comptaflow-by-meetempo') . '</th>';
        echo '<th style="width: 60px;">' . esc_html__('Rate', 'comptaflow-by-meetempo') . '</th>';
        echo '<th>' . esc_html__('Label', 'comptaflow-by-meetempo') . '</th>';
        echo '<th style="width: 100px;">' . esc_html__('Validity', 'comptaflow-by-meetempo') . '</th>';
        echo '<th style="width: 70px;">' . esc_html__('Status', 'comptaflow-by-meetempo') . '</th>';
        echo '<th style="width: 100px;">' . esc_html__('Actions', 'comptaflow-by-meetempo') . '</th>';
        echo '</tr></thead>';
        echo '<tbody>';
        
        foreach ($rates as $rate) {
            $edit_url = add_query_arg(['page' => 'comptaflow-vat-settings', 'action' => 'edit', 'id' => $rate->id], admin_url('admin.php'));
            $delete_url = wp_nonce_url(
                add_query_arg(['page' => 'comptaflow-vat-settings', 'action' => 'delete', 'id' => $rate->id], admin_url('admin.php')),
                'comptaflow_delete_vat'
            );
            $toggle_url = wp_nonce_url(
                add_query_arg(['page' => 'comptaflow-vat-settings', 'action' => 'toggle', 'id' => $rate->id], admin_url('admin.php')),
                'comptaflow_toggle_vat'
            );
            
            $validity = '';
            if ($rate->valid_from) {
                $validity .= __('From', 'comptaflow-by-meetempo') . ' ' . date_i18n('d/m/Y', strtotime($rate->valid_from));
            }
            if ($rate->valid_to) {
                $validity .= ' ' . __('to', 'comptaflow-by-meetempo') . ' ' . date_i18n('d/m/Y', strtotime($rate->valid_to));
            }
            if (!$validity) {
                $validity = __('Permanent', 'comptaflow-by-meetempo');
            }
            
            $status_text = $rate->is_active ? __('Active', 'comptaflow-by-meetempo') : __('Inactive', 'comptaflow-by-meetempo');
            $status_class = $rate->is_active ? 'active' : 'inactive';
            
            echo '<tr>';
            echo '<td>' . esc_html($rate->country_code) . '</td>';
            echo '<td><code>' . esc_html($rate->rate_code) . '</code></td>';
            echo '<td><strong>' . esc_html(number_format($rate->rate_value, 2)) . '%</strong></td>';
            echo '<td>' . esc_html($rate->rate_name) . '</td>';
            echo '<td><small>' . esc_html($validity) . '</small></td>';
            echo '<td><span class="status-' . esc_attr($status_class) . '">' . esc_html($status_text) . '</span></td>';
            echo '<td>';
            echo '<a href="' . esc_url($edit_url) . '" class="button button-small">' . esc_html__('Edit', 'comptaflow-by-meetempo') . '</a> ';
            echo '<a href="' . esc_url($toggle_url) . '" class="button button-small">' . ($rate->is_active ? esc_html__('Deactivate', 'comptaflow-by-meetempo') : esc_html__('Activate', 'comptaflow-by-meetempo')) . '</a> ';
            if (!$rate->is_active) {
                echo '<a href="' . esc_url($delete_url) . '" class="button button-small" onclick="return confirm(\'' . esc_js(__('Delete this VAT rate?', 'comptaflow-by-meetempo')) . '\')">' . esc_html__('Delete', 'comptaflow-by-meetempo') . '</a>';
            }
            echo '</td>';
            echo '</tr>';
        }
        
        echo '</tbody></table>';
    }
    
    private static function showMessages(): void {
        settings_errors('comptaflow_vat');
    }
}
