<?php
namespace ComptaFlowPro\Admin\Screens;

use ComptaFlowPro\Services\JournalEntryGenerator;
use ComptaFlowPro\Services\ChartOfAccounts;
use ComptaFlowPro\Services\DB;
use ComptaFlowPro\Admin\Tables\TransactionsTable;

defined('ABSPATH') || exit;

class SalesScreen {
    
    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__('Sales (Revenue)', 'comptaflow-by-meetempo') . '</h1>';
        echo '<a href="' . esc_url(admin_url('admin.php?page=comptaflow-sales&action=new')) . '" class="page-title-action">' . esc_html__('Add New', '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']) && !isset($_GET['action'])) {
            return;
        }
        
        $nonce_post = isset($_POST['_wpnonce']) ? sanitize_text_field(wp_unslash($_POST['_wpnonce'])) : '';
        if ($nonce_post && wp_verify_nonce($nonce_post, 'comptaflow_sales_action')) {
            if (isset($_POST['action']) && ($_POST['action'] === 'create' || $_POST['action'] === 'update')) {
                self::saveSale();
            }
        }
        
        if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
            $nonce_get = isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : '';
            if (wp_verify_nonce($nonce_get, 'comptaflow_delete_sale')) {
                self::deleteSale();
            }
        }
    }

    private static function saveSale(): void {
        global $wpdb;
        $p = $wpdb->prefix . 'cfp_';
        
        $is_manual = isset($_POST['manual_amounts']) && $_POST['manual_amounts'] === 'on';
        
        if ($is_manual) {
            $amount_ht = floatval($_POST['amount_ht_manual'] ?? 0);
            $amount_tva = floatval($_POST['amount_tva_manual'] ?? 0);
            $amount_ttc = floatval($_POST['amount_ttc_manual'] ?? 0);
            $vat_rate = floatval($_POST['vat_rate'] ?? 0);
        } else {
            $vat_rate = floatval($_POST['vat_rate'] ?? 20);
            $amount_ttc = floatval($_POST['amount_ttc_auto'] ?? 0);
            $amount_ht = $amount_ttc / (1 + ($vat_rate / 100));
            $amount_tva = $amount_ttc - $amount_ht;
        }
        
        $data = [
            'type' => 'SALE',
            'date_txn' => isset($_POST['date_txn']) ? sanitize_text_field(wp_unslash($_POST['date_txn'])) : '',
            'label' => isset($_POST['label']) ? sanitize_text_field(wp_unslash($_POST['label'])) : '',
            'amount_ttc' => $amount_ttc,
            'amount_ht' => $amount_ht,
            'amount_tva' => $amount_tva,
            'vat_rate' => $vat_rate,
            'vat_code' => isset($_POST['vat_code']) ? sanitize_text_field(wp_unslash($_POST['vat_code'])) : '',
            'payment_method' => isset($_POST['payment_method']) ? sanitize_text_field(wp_unslash($_POST['payment_method'])) : '',
            'payment_status' => isset($_POST['payment_status']) ? sanitize_text_field(wp_unslash($_POST['payment_status'])) : '',
            'partner_name' => isset($_POST['partner_name']) ? sanitize_text_field(wp_unslash($_POST['partner_name'])) : '',
            'piece_ref' => isset($_POST['piece_ref']) ? sanitize_text_field(wp_unslash($_POST['piece_ref'])) : '',
            'journal_code' => 'VE',
            'created_by' => get_current_user_id(),
            'account_code' => isset($_POST['account_code']) ? sanitize_text_field(wp_unslash($_POST['account_code'])) : '706',
        ];

        try {
            $wpdb->query('START TRANSACTION');
            
            $id = intval($_POST['id'] ?? 0);
            $transaction_id = 0;
            
            if ($id) {
                $transaction_id = $id;
                $wpdb->delete($p . 'journal_entries', ['transaction_id' => $transaction_id]);
                $wpdb->update($p . 'transactions', $data, ['id' => $transaction_id]);
                $message = __('Sale updated with journal entries regenerated!', 'comptaflow-by-meetempo');
            } else {
                $data['uuid'] = wp_generate_uuid4();
                $data['created_at'] = current_time('mysql');
                $result = $wpdb->insert($p . 'transactions', $data);
                if (!$result) {
                    throw new \Exception(__('Error inserting transaction.', 'comptaflow-by-meetempo'));
                }
                $transaction_id = $wpdb->insert_id;
                $message = __('Sale saved with journal entries generated!', 'comptaflow-by-meetempo');
            }
            
            $data['id'] = $transaction_id;
            
            JournalEntryGenerator::generateSaleEntries($data, $transaction_id);
            
            $wpdb->query('COMMIT');
            
            add_settings_error('comptaflow_sales', 'saved', $message, 'updated');
            
        } catch (\Exception $e) {
            $wpdb->query('ROLLBACK');
            add_settings_error('comptaflow_sales', 'error', __('Error:', 'comptaflow-by-meetempo') . ' ' . $e->getMessage());
        }
    }
    
    private static function deleteSale(): void {
        $id = intval($_GET['id'] ?? 0);
        if (!$id) return;
        
        global $wpdb;
        $p = $wpdb->prefix . 'cfp_';
        
        try {
            $wpdb->query('START TRANSACTION');
            $wpdb->delete($p . 'journal_entries', ['transaction_id' => $id]);
            $wpdb->delete($p . 'transactions', ['id' => $id, 'type' => 'SALE']);
            $wpdb->query('COMMIT');
            add_settings_error('comptaflow_sales', 'deleted', __('Sale deleted with all journal entries.', 'comptaflow-by-meetempo'), 'updated');
        } catch (\Exception $e) {
            $wpdb->query('ROLLBACK');
            add_settings_error('comptaflow_sales', 'error', __('Error deleting:', 'comptaflow-by-meetempo') . ' ' . $e->getMessage());
        }
    }
    
    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}transactions WHERE id = %d AND type = 'SALE'", $id), ARRAY_A) ?? [];
            }
        }
        
        echo '<h2>' . ($action === 'edit' ? esc_html__('Edit Sale', 'comptaflow-by-meetempo') : esc_html__('New Sale', 'comptaflow-by-meetempo')) . '</h2>';
        echo '<form method="post">';
        wp_nonce_field('comptaflow_sales_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__('Date', 'comptaflow-by-meetempo') . ' *</th><td><input type="date" name="date_txn" value="' . esc_attr($item['date_txn'] ?? gmdate('Y-m-d')) . '" required></td></tr>';
        
        echo '<tr><th>' . esc_html__('Label', 'comptaflow-by-meetempo') . ' *</th><td><input type="text" name="label" value="' . esc_attr($item['label'] ?? '') . '" required class="regular-text"></td></tr>';
        
        echo '<tr><th>' . esc_html__('Revenue Account', 'comptaflow-by-meetempo') . ' *</th><td>';
        self::renderAccountSelector($item['account_code'] ?? '706');
        echo '</td></tr>';
        
        echo '<tr><th>' . esc_html__('Entry Mode', 'comptaflow-by-meetempo') . '</th><td>';
        echo '<label><input type="checkbox" name="manual_amounts" id="manual_amounts"> ' . esc_html__('Manual entry for Net/VAT/Gross', 'comptaflow-by-meetempo') . '</label>';
        echo '<p class="description">' . esc_html__('Check for special cases: exempt export, EU services, foreign royalties...', 'comptaflow-by-meetempo') . '</p>';
        echo '</td></tr>';
        
        echo '<tr id="auto_mode_row"><th>' . esc_html__('Gross Amount', 'comptaflow-by-meetempo') . ' *</th><td>';
        echo '<input type="number" name="amount_ttc_auto" id="amount_ttc_auto" value="' . esc_attr($item['amount_ttc'] ?? '') . '" step="0.01" min="0" required> €';
        echo '<p class="description">' . esc_html__('Net and VAT will be calculated automatically based on the rate', 'comptaflow-by-meetempo') . '</p>';
        echo '</td></tr>';
        
        echo '<tr id="manual_mode_row" style="display: none;"><th>' . esc_html__('Manual Amounts', 'comptaflow-by-meetempo') . ' *</th><td>';
        echo '<table style="width: 100%; border-collapse: collapse;">';
        echo '<tr>';
        echo '<td style="width: 30%; padding: 5px;">' . esc_html__('Net:', 'comptaflow-by-meetempo') . ' <input type="number" name="amount_ht_manual" id="amount_ht_manual" value="' . esc_attr($item['amount_ht'] ?? '') . '" step="0.01" min="0" style="width: 100px;"> €</td>';
        echo '<td style="width: 30%; padding: 5px;">' . esc_html__('VAT:', 'comptaflow-by-meetempo') . ' <input type="number" name="amount_tva_manual" id="amount_tva_manual" value="' . esc_attr($item['amount_tva'] ?? '') . '" step="0.01" min="0" style="width: 100px;"> €</td>';
        echo '<td style="width: 40%; padding: 5px;">' . esc_html__('Gross:', 'comptaflow-by-meetempo') . ' <input type="number" name="amount_ttc_manual" id="amount_ttc_manual" value="' . esc_attr($item['amount_ttc'] ?? '') . '" step="0.01" min="0" style="width: 100px;"> €</td>';
        echo '</tr>';
        echo '</table>';
        echo '<p class="description">' . esc_html__('Enter all 3 amounts independently (no automatic calculation)', 'comptaflow-by-meetempo') . '</p>';
        echo '</td></tr>';
        
        echo '<tr><th>' . esc_html__('VAT Rate', 'comptaflow-by-meetempo') . '</th><td>';
        self::renderVATSelector($item);
        echo '</td></tr>';
        
        echo '<tr><th>' . esc_html__('Payment Method', 'comptaflow-by-meetempo') . '</th><td>';
        echo '<select name="payment_method">';
        $selected_method = $item['payment_method'] ?? 'CB';
        $methods = [
            'CB' => __('Credit Card', 'comptaflow-by-meetempo'), 
            'VIREMENT' => __('Bank Transfer', 'comptaflow-by-meetempo'), 
            'ESPECES' => __('Cash', 'comptaflow-by-meetempo'), 
            'CHEQUE' => __('Check', 'comptaflow-by-meetempo')
        ];
        foreach ($methods as $key => $label) {
            echo '<option value="' . esc_attr($key) . '"' . selected($selected_method, $key, false) . '>' . esc_html($label) . '</option>';
        }
        echo '</select>';
        echo '</td></tr>';
        
        echo '<tr><th>' . esc_html__('Payment Status', 'comptaflow-by-meetempo') . ' *</th><td>';
        echo '<select name="payment_status">';
        $selected_status = $item['payment_status'] ?? 'PAID';
        $statuses = [
            'PAID' => __('Collected immediately (generates settlement 512/411)', 'comptaflow-by-meetempo'), 
            'PENDING' => __('To collect later (creates customer receivable 411)', 'comptaflow-by-meetempo')
        ];
        foreach ($statuses as $key => $label) {
            echo '<option value="' . esc_attr($key) . '"' . selected($selected_status, $key, false) . '>' . esc_html($label) . '</option>';
        }
        echo '</select>';
        echo '<p class="description">' . esc_html__('This choice determines the journal entries generated.', 'comptaflow-by-meetempo') . '</p>';
        echo '</td></tr>';
        
        echo '<tr><th>' . esc_html__('Customer', 'comptaflow-by-meetempo') . '</th><td><input type="text" name="partner_name" value="' . esc_attr($item['partner_name'] ?? '') . '" class="regular-text"></td></tr>';
        
        echo '<tr><th>' . esc_html__('Invoice #', 'comptaflow-by-meetempo') . '</th><td><input type="text" name="piece_ref" value="' . esc_attr($item['piece_ref'] ?? '') . '" class="regular-text"></td></tr>';
        
        echo '</table>';
        
        submit_button($action === 'edit' ? __('Update', 'comptaflow-by-meetempo') : __('Save', 'comptaflow-by-meetempo'));
        echo '</form>';
    }
    
    private static function renderVATSelector(array $item): void {
        $vat_rates = DB::getActiveVATRates('FR');
        
        $selected_rate = $item['vat_rate'] ?? 20;
        $selected_code = $item['vat_code'] ?? '';
        
        echo '<input type="hidden" name="vat_code" id="vat_code">';
        echo '<select name="vat_rate" id="vat_rate_select" data-initial-code="' . esc_attr($selected_code) . '">';
        
        if (empty($vat_rates)) {
            $vat_rates = [
                ['rate_value' => 20.00, 'rate_code' => 'FR-20', 'rate_name' => __('Standard rate', 'comptaflow-by-meetempo')],
                ['rate_value' => 10.00, 'rate_code' => 'FR-10', 'rate_name' => __('Reduced rate', 'comptaflow-by-meetempo')],
                ['rate_value' => 5.50, 'rate_code' => 'FR-5_5', 'rate_name' => __('Super reduced rate', 'comptaflow-by-meetempo')],
                ['rate_value' => 0.00, 'rate_code' => 'FR-0', 'rate_name' => __('Exempt', 'comptaflow-by-meetempo')]
            ];
        }
        
        foreach ($vat_rates as $rate) {
            $is_selected = (abs(floatval($rate['rate_value']) - floatval($selected_rate)) < 0.01);
            echo '<option value="' . esc_attr($rate['rate_value']) . '" data-code="' . esc_attr($rate['rate_code']) . '"';
            if ($is_selected) echo ' selected';
            echo '>' . esc_html(number_format($rate['rate_value'], 2)) . '% - ' . esc_html($rate['rate_name']) . '</option>';
        }
        
        echo '</select>';
    }
    
    private static function renderAccountSelector(string $selectedCode = '706'): void {
        echo '<input type="hidden" name="account_code" id="account_code" value="' . esc_attr($selectedCode) . '" required>';
        echo '<div id="account-selector">';
        echo '<input type="text" id="account_search" data-class-filter="7" placeholder="' . esc_attr__('Type service, sale, commission...', 'comptaflow-by-meetempo') . '" style="width: 300px; padding: 8px; margin-bottom: 10px;">';
        
        $selectedAccount = ChartOfAccounts::getAccount($selectedCode);
        echo '<div id="selected-account" style="padding: 10px; background: #f0f0f1; border-left: 4px solid #0073aa; margin-bottom: 10px;">';
        if ($selectedAccount) {
            echo '<strong>' . esc_html($selectedAccount['code']) . '</strong> - ' . esc_html($selectedAccount['label']);
        } else {
            echo '<strong>706</strong> - ' . esc_html__('Service revenue', 'comptaflow-by-meetempo');
        }
        echo '</div>';
        
        echo '<div id="favorite-accounts" style="margin-bottom: 15px;">';
        echo '<p style="margin-bottom: 8px;"><strong>' . esc_html__('Common revenue accounts:', 'comptaflow-by-meetempo') . '</strong></p>';
        $favoriteAccounts = [
            '706' => __('Service revenue (Consulting, Training)', 'comptaflow-by-meetempo'),
            '707' => __('Merchandise sales (E-commerce)', 'comptaflow-by-meetempo'),
            '7082' => __('Commissions and brokerage (Rideshare, Affiliate)', 'comptaflow-by-meetempo')
        ];
        
        foreach ($favoriteAccounts as $code => $label) {
            $is_active = ($code === $selectedCode);
            $style = $is_active 
                ? 'margin: 2px; padding: 5px 10px; border: 1px solid #ccc; background: #0073aa; color: white; cursor: pointer; border-radius: 3px;'
                : 'margin: 2px; padding: 5px 10px; border: 1px solid #ccc; background: #f8f9fa; cursor: pointer; border-radius: 3px;';
            echo '<button type="button" class="account-quick-select" data-code="' . esc_attr($code) . '" data-label="' . esc_attr($label) . '" style="' . esc_attr($style) . '">';
            echo esc_html($code) . ' - ' . esc_html($label);
            echo '</button>';
        }
        echo '</div>';
        
        echo '<div id="search-results" style="max-height: 200px; overflow-y: auto; border: 1px solid #ddd; background: white; display: none;"></div>';
        echo '</div>';
    }
    
    private static function renderList(): void {
        $table = new TransactionsTable('SALE');
        $table->prepare_items();
        
        if (empty($table->items)) {
            echo '<p>' . esc_html__('No sales recorded.', 'comptaflow-by-meetempo') . '</p>';
            return;
        }
        
        $table->display();
    }
    
    private static function showMessages(): void {
        settings_errors('comptaflow_sales');
    }
}
