<?php
namespace ComptaFlowUK\Admin\Screens;

use ComptaFlowUK\Services\DB;

defined('ABSPATH') || exit;

class VATSettingsScreen {
    public static function render(): void {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('Insufficient permissions.', 'comptaflow-uk-by-meetempo'));
        }
        
        self::handleActions();
        
        echo '<div class="wrap">';
        echo '<h1 class="wp-heading-inline">' . esc_html__('VAT Settings', 'comptaflow-uk-by-meetempo') . '</h1>';
        echo '<a href="?page=comptaflow-uk-vat&action=new" class="page-title-action">' . esc_html__('Add a rate', 'comptaflow-uk-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'])) {
            return;
        }
        
        $nonce_post = isset($_POST['_wpnonce']) ? sanitize_text_field(wp_unslash($_POST['_wpnonce'])) : '';
        if (wp_verify_nonce($nonce_post, 'comptaflow_uk_vat_action')) {
            $post_action = isset($_POST['action']) ? sanitize_text_field(wp_unslash($_POST['action'])) : '';
            if ($post_action === 'create' || $post_action === 'update') {
                self::saveVATRate();
            }
        }
        
        if (isset($_GET['action']) && sanitize_key($_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_uk_delete_vat')) {
                self::deleteVATRate();
            }
        }
        
        if (isset($_GET['action']) && sanitize_key($_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_uk_toggle_vat')) {
                self::toggleVATRate();
            }
        }
    }
    
    private static function saveVATRate(): void {
        global $wpdb;

        $rate_code = isset($_POST['rate_code']) ? sanitize_text_field(wp_unslash($_POST['rate_code'])) : '';
        $rate_name = isset($_POST['rate_name']) ? sanitize_text_field(wp_unslash($_POST['rate_name'])) : '';
        if (empty($rate_code) || empty($rate_name) || !isset($_POST['rate_value'])) {
            add_settings_error('comptaflow_uk_vat', 'error', __('All required fields must be completed.', 'comptaflow-uk-by-meetempo'));
            return;
        }
        
        $data = [
            'country_code' => isset($_POST['country_code']) ? sanitize_text_field(wp_unslash($_POST['country_code'])) : 'GB',
            'rate_code' => $rate_code,
            'rate_value' => isset($_POST['rate_value']) ? floatval(wp_unslash($_POST['rate_value'])) : 0,
            'rate_name' => $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 = absint($_POST['id'] ?? 0);
        
        try {
            if ($id) {
                // Update
                $data['updated_at'] = current_time('mysql');
                $result = $wpdb->update($wpdb->prefix . 'cfuk_vat_rates', $data, ['id' => $id]);
                
                if ($result === false) {
                    throw new \Exception('Database error during update: ' . $wpdb->last_error);
                }
                
                $message = 'VAT rate updated successfully.';
            } else {
                // Check if code already exists
                $existing = $wpdb->get_var($wpdb->prepare(
                    "SELECT id FROM {$wpdb->prefix}cfuk_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.');
                }
                
                // Creation
                $data['created_by'] = get_current_user_id();
                $data['created_at'] = current_time('mysql');
                
                $result = $wpdb->insert($wpdb->prefix . 'cfuk_vat_rates', $data);
                
                if ($result === false) {
                    throw new \Exception('Database error during creation: ' . $wpdb->last_error);
                }
                
                $message = 'VAT rate created successfully.';
            }
            
            add_settings_error('comptaflow_uk_vat', 'saved', $message, 'updated');
            
        } catch (\Exception $e) {
            add_settings_error('comptaflow_uk_vat', 'error', __('Error: ', 'comptaflow-uk-by-meetempo') . $e->getMessage());
        }
    }
    
    private static function deleteVATRate(): void {
        $id = intval($_GET['id'] ?? 0);
        if (!$id) return;
        
        global $wpdb;

        // Check if rate is used in transactions
        $usage = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$wpdb->prefix}cfuk_transactions WHERE vat_code = (SELECT rate_code FROM {$wpdb->prefix}cfuk_vat_rates WHERE id = %d)",
            $id
        ));
        
        if ($usage > 0) {
            add_settings_error('comptaflow_uk_vat', 'error', __('Cannot delete this rate: it is used in ', 'comptaflow-uk-by-meetempo') . $usage . ' transaction(s).');
            return;
        }
        
        $wpdb->delete($wpdb->prefix . 'cfuk_vat_rates', ['id' => $id]);
        add_settings_error('comptaflow_uk_vat', 'deleted', __('VAT rate deleted successfully.', 'comptaflow-uk-by-meetempo'), 'updated');
    }
    
    private static function toggleVATRate(): void {
        $id = intval($_GET['id'] ?? 0);
        if (!$id) return;
        
        global $wpdb;

        $current_status = $wpdb->get_var($wpdb->prepare(
            "SELECT is_active FROM {$wpdb->prefix}cfuk_vat_rates WHERE id = %d",
            $id
        ));
        
        $new_status = $current_status ? 0 : 1;
        
        $wpdb->update($wpdb->prefix . 'cfuk_vat_rates', [
            'is_active' => $new_status,
            'updated_at' => current_time('mysql')
        ], ['id' => $id]);
        
        $message = $new_status ? 'VAT rate enabled.' : 'VAT rate disabled.';
        add_settings_error('comptaflow_uk_vat', 'toggled', $message, 'updated');
    }
    
    private static function renderForm(string $action): void {
        $item = [];
        
        if ($action === 'edit') {
            $id = intval($_GET['id'] ?? 0);
            if ($id) {
                global $wpdb;
                $item = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->prefix}cfuk_vat_rates WHERE id = %d", $id), ARRAY_A) ?? [];
            }
        }
        
        echo '<div style="max-width: 600px;">';
        echo '<h2>' . ($action === 'edit' ? esc_html__('Edit VAT rate', 'comptaflow-uk-by-meetempo') : esc_html__('New VAT rate', 'comptaflow-uk-by-meetempo')) . '</h2>';
        echo '<form method="post">';
        wp_nonce_field('comptaflow_uk_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-uk-by-meetempo') . '</th><td>';
        echo '<select name="country_code" required>';
        $selected_country = $item['country_code'] ?? 'GB';
        $countries = [
            'GB' => 'United Kingdom',
            'IE' => 'Ireland', 
            'GB' => 'France',
            'DE' => 'Germany',
            'NL' => 'Netherlands',
            'BE' => 'Belgium',
            'ES' => 'Spain',
            'IT' => 'Italy',
            'US' => 'United States',
            'AU' => 'Australia',
            'CA' => 'Canada',
            'JE' => 'Jersey',
            'GG' => 'Guernsey',
            'IM' => 'Isle of Man',
            'GI' => 'Gibraltar',

        ];
        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-uk-by-meetempo') . '</p>';
        echo '</td></tr>';
        
        echo '<tr><th>' . esc_html__('Rate code *', 'comptaflow-uk-by-meetempo') . '</th><td>';
        echo '<input type="text" name="rate_code" value="' . esc_attr($item['rate_code'] ?? '') . '" required class="regular-text" placeholder="e.g. GB-20">';
        echo '<p class="description">' . esc_html__('Unique code to identify the rate (e.g. GB-20, GB-5)', 'comptaflow-uk-by-meetempo') . '</p>';
        echo '</td></tr>';
        
        echo '<tr><th>' . esc_html__('Rate (%) *', 'comptaflow-uk-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-uk-by-meetempo') . '</p>';
        echo '</td></tr>';
        
        echo '<tr><th>' . esc_html__('Label *', 'comptaflow-uk-by-meetempo') . '</th><td>';
        echo '<input type="text" name="rate_name" value="' . esc_attr($item['rate_name'] ?? '') . '" required class="regular-text" placeholder="e.g. Standard Rate">';
        echo '<p class="description">' . esc_html__('Description shown in forms', 'comptaflow-uk-by-meetempo') . '</p>';
        echo '</td></tr>';
        
        echo '<tr><th>' . esc_html__('Validity period', 'comptaflow-uk-by-meetempo') . '</th><td>';
        echo '<label>From : <input type="date" name="valid_from" value="' . esc_attr($item['valid_from'] ?? '') . '"></label><br>';
        echo '<label style="margin-top: 5px; display: inline-block;">Au : <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-uk-by-meetempo') . '</p>';
        echo '</td></tr>';
        
        echo '<tr><th>' . esc_html__('Status', 'comptaflow-uk-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-uk-by-meetempo') . '</label>';
        echo '<p class="description">' . esc_html__('Only active rates appear in forms', 'comptaflow-uk-by-meetempo') . '</p>';
        echo '</td></tr>';
        
        echo '</table>';
        
        submit_button($action === 'edit' ? 'Update' : 'Create');
        echo '</form>';
        echo '</div>';
    }
    
    private static function renderList(): void {
        global $wpdb;

        $rates = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}cfuk_vat_rates ORDER BY country_code, rate_value DESC");
        
        if (empty($rates)) {
            echo '<p>' . esc_html__('No VAT rates configured.', 'comptaflow-uk-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-uk-by-meetempo') . '</th>';
        echo '<th style="width: 80px;">' . esc_html__('Code', 'comptaflow-uk-by-meetempo') . '</th>';
        echo '<th style="width: 60px;">' . esc_html__('Rate', 'comptaflow-uk-by-meetempo') . '</th>';
        echo '<th>' . esc_html__('Label', 'comptaflow-uk-by-meetempo') . '</th>';
        echo '<th style="width: 100px;">' . esc_html__('Validity', 'comptaflow-uk-by-meetempo') . '</th>';
        echo '<th style="width: 70px;">' . esc_html__('Status', 'comptaflow-uk-by-meetempo') . '</th>';
        echo '<th style="width: 100px;">' . esc_html__('Actions', 'comptaflow-uk-by-meetempo') . '</th>';
        echo '</tr></thead>';
        echo '<tbody>';
        
        foreach ($rates as $rate) {
            $edit_url = add_query_arg(['page' => 'comptaflow-uk-vat', 'action' => 'edit', 'id' => $rate->id], admin_url('admin.php'));
            $delete_url = wp_nonce_url(
                add_query_arg(['page' => 'comptaflow-uk-vat', 'action' => 'delete', 'id' => $rate->id], admin_url('admin.php')),
                'comptaflow_uk_delete_vat'
            );
            $toggle_url = wp_nonce_url(
                add_query_arg(['page' => 'comptaflow-uk-vat', 'action' => 'toggle', 'id' => $rate->id], admin_url('admin.php')),
                'comptaflow_uk_toggle_vat'            );
            
            $validity = '';
            if ($rate->valid_from) {
                $validity .= esc_html__('From', 'comptaflow-uk-by-meetempo') . ' ' . date_i18n('d/m/Y', strtotime($rate->valid_from));
            }
            if ($rate->valid_to) {
                $validity .= ' ' . esc_html__('to', 'comptaflow-uk-by-meetempo') . ' ' . date_i18n('d/m/Y', strtotime($rate->valid_to));
            }
            if (!$validity) {
                $validity = esc_html__('Permanent', 'comptaflow-uk-by-meetempo');
            }
            
            $status_text = $rate->is_active ? esc_html__('Active', 'comptaflow-uk-by-meetempo') : esc_html__('Inactive', 'comptaflow-uk-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-uk-by-meetempo') . '</a> ';
            echo '<a href="' . esc_url($toggle_url) . '" class="button button-small">' . ($rate->is_active ? esc_html__('Disable', 'comptaflow-uk-by-meetempo') : esc_html__('Enable', 'comptaflow-uk-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-uk-by-meetempo')) . '\')">' . esc_html__('Delete', 'comptaflow-uk-by-meetempo') . '</a>';
            }
            echo '</td>';
            echo '</tr>';
        }
        
        echo '</tbody></table>';
        
    }
    
    private static function showMessages(): void {
        settings_errors('comptaflow_uk_vat');
    }
}