<?php
// File: src/Admin/Screens/ExpensesScreen.php
// Version 2.1 - UK Adaptation - Expenses Screen

namespace ComptaFlowUK\Admin\Screens;

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

defined('ABSPATH') || exit;

class ExpensesScreen {
    
    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 class="wp-heading-inline">' . esc_html__('Expenses', 'comptaflow-uk-by-meetempo') . '</h1>';
        echo '<a href="?page=comptaflow-uk-expenses&action=new" class="page-title-action">' . esc_html__('Add New', '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 {
        $get_action = isset($_GET['action']) ? sanitize_key($_GET['action']) : '';
        if (!isset($_POST['_wpnonce']) && empty($get_action)) {
            return;
        }
        
        // Handle create and update
        $nonce_post = isset($_POST['_wpnonce']) ? sanitize_text_field(wp_unslash($_POST['_wpnonce'])) : '';
        if ($nonce_post && wp_verify_nonce($nonce_post, 'comptaflow_uk_expenses_action')) {
            $post_action = isset($_POST['action']) ? sanitize_text_field(wp_unslash($_POST['action'])) : '';
            if ($post_action === 'create' || $post_action === 'update') {
                self::saveExpense();
            }
        }
        
        // Handle delete
        if ($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_uk_delete_expense')) {
                self::deleteExpense();
            }
        }
    }

    private static function saveExpense(): void {
        global $wpdb;
        $p = $wpdb->prefix . 'cfuk_';
        
        $is_manual = isset($_POST['manual_amounts']) && sanitize_text_field(wp_unslash($_POST['manual_amounts'])) === 'on';
        
        if ($is_manual) {
            $amount_net = floatval(wp_unslash($_POST['amount_net_manual'] ?? 0));
            $amount_vat = floatval(wp_unslash($_POST['amount_vat_manual'] ?? 0));
            $amount_gross = floatval(wp_unslash($_POST['amount_gross_manual'] ?? 0));
            $vat_rate = floatval(wp_unslash($_POST['vat_rate'] ?? 0));
        } else {
            $vat_rate = floatval(wp_unslash($_POST['vat_rate'] ?? 20));
            $amount_gross = floatval(wp_unslash($_POST['amount_gross_auto']));
            $amount_net = $amount_gross / (1 + ($vat_rate / 100));
            $amount_vat = $amount_gross - $amount_net;
        }
        
        $data = [
            'type' => 'EXPENSE',
            '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_gross,
            'amount_ht' => $amount_net,
            'amount_tva' => $amount_vat,
            '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' => 'PL',
            'created_by' => get_current_user_id(),
            'account_code' => isset($_POST['account_code']) ? sanitize_text_field(wp_unslash($_POST['account_code'])) : '5030',
        ];

        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 = __('Expense updated with journal entries regenerated!', 'comptaflow-uk-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-uk-by-meetempo'));
                $transaction_id = $wpdb->insert_id;
                $message = __('Expense recorded with journal entries generated!', 'comptaflow-uk-by-meetempo');
            }
            
            $data['id'] = $transaction_id;

            JournalEntryGenerator::generateExpenseEntries($data, $transaction_id);
            
            $wpdb->query('COMMIT');
            
            add_settings_error('comptaflow_uk_expenses', 'saved', $message, 'updated');
            
        } catch (\Exception $e) {
            $wpdb->query('ROLLBACK');
            add_settings_error('comptaflow_uk_expenses', 'error', __('Error:', 'comptaflow-uk-by-meetempo') . ' ' . $e->getMessage());
        }
    }
    
    private static function deleteExpense(): void {
        $id = intval($_GET['id'] ?? 0);
        if (!$id) return;
        
        global $wpdb;
        $p = $wpdb->prefix . 'cfuk_';
        
        try {
            $wpdb->query('START TRANSACTION');
            $wpdb->delete($p . 'journal_entries', ['transaction_id' => $id]);
            $wpdb->delete($p . 'transactions', ['id' => $id, 'type' => 'EXPENSE']);
            $wpdb->query('COMMIT');
            add_settings_error('comptaflow_uk_expenses', 'deleted', __('Expense deleted with all journal entries.', 'comptaflow-uk-by-meetempo'), 'updated');
        } catch (\Exception $e) {
            $wpdb->query('ROLLBACK');
            add_settings_error('comptaflow_uk_expenses', 'error', __('Error deleting:', 'comptaflow-uk-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 . 'cfuk_';
                $item = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$p}transactions WHERE id = %d AND type = 'EXPENSE'", $id), ARRAY_A) ?? [];
            }
        }
        
        echo '<h2>' . ($action === 'edit' ? esc_html__('Edit Expense', 'comptaflow-uk-by-meetempo') : esc_html__('New Expense', 'comptaflow-uk-by-meetempo')) . '</h2>';
        echo '<form method="post">';
        wp_nonce_field('comptaflow_uk_expenses_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-uk-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__('Description *', 'comptaflow-uk-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__('Expense Account *', 'comptaflow-uk-by-meetempo') . '</th><td>';
        self::renderAccountSelector($item['account_code'] ?? '5030');
        echo '</td></tr>';
        
        echo '<tr><th>' . esc_html__('Entry Mode', 'comptaflow-uk-by-meetempo') . '</th><td>';
        echo '<label><input type="checkbox" name="manual_amounts" id="manual_amounts"> ' . esc_html__('Manual entry Net/VAT/Gross', 'comptaflow-uk-by-meetempo') . '</label>';
        echo '<p class="description">' . esc_html__('Tick for special cases: zero-rated, reverse charge, overseas services, insurance...', 'comptaflow-uk-by-meetempo') . '</p>';
        echo '</td></tr>';
        
        echo '<tr id="auto_mode_row"><th>' . esc_html__('Gross Amount *', 'comptaflow-uk-by-meetempo') . '</th><td>';
        echo '<input type="number" name="amount_gross_auto" id="amount_gross_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 from the rate', 'comptaflow-uk-by-meetempo') . '</p>';
        echo '</td></tr>';
        
        echo '<tr id="manual_mode_row" style="display: none;"><th>' . esc_html__('Manual Amounts *', 'comptaflow-uk-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-uk-by-meetempo') . ' <input type="number" name="amount_net_manual" id="amount_net_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-uk-by-meetempo') . ' <input type="number" name="amount_vat_manual" id="amount_vat_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-uk-by-meetempo') . ' <input type="number" name="amount_gross_manual" id="amount_gross_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-uk-by-meetempo') . '</p>';
        echo '</td></tr>';
        
        echo '<tr><th>' . esc_html__('VAT Rate', 'comptaflow-uk-by-meetempo') . '</th><td>';
        self::renderVATSelector($item);
        echo '</td></tr>';
        
        echo '<tr><th>' . esc_html__('Payment Method', 'comptaflow-uk-by-meetempo') . '</th><td>';
        echo '<select name="payment_method">';
        $selected_method = $item['payment_method'] ?? 'CARD';
        $methods = [
            'CARD' => __('Debit/Credit Card', 'comptaflow-uk-by-meetempo'),
            'BANK_TRANSFER' => __('Bank Transfer', 'comptaflow-uk-by-meetempo'),
            'CASH' => __('Cash', 'comptaflow-uk-by-meetempo'),
            'CHEQUE' => __('Cheque', 'comptaflow-uk-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-uk-by-meetempo') . '</th><td>';
        echo '<select name="payment_status">';
        $selected_status = $item['payment_status'] ?? 'PAID';
        $statuses = [
            'PAID' => __('Paid immediately (generates payment entry 2100/1200)', 'comptaflow-uk-by-meetempo'), 
            'PENDING' => __('To pay later (creates trade creditor 2100)', 'comptaflow-uk-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 determines which journal entries are generated.', 'comptaflow-uk-by-meetempo') . '</p>';
        echo '</td></tr>';
        
        echo '<tr><th>' . esc_html__('Supplier', 'comptaflow-uk-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 No.', 'comptaflow-uk-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' ? esc_html__('Update', 'comptaflow-uk-by-meetempo') : esc_html__('Save', 'comptaflow-uk-by-meetempo'));
        echo '</form>';
        
        }
    
    private static function renderVATSelector(array $item): void {
    $vat_rates = DB::getActiveVATRates('GB');
    
    $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' => 'GB-20', 'rate_name' => __('Standard rate', 'comptaflow-uk-by-meetempo')],
                ['rate_value' => 5.00, 'rate_code' => 'GB-5', 'rate_name' => __('Reduced rate', 'comptaflow-uk-by-meetempo')],
                ['rate_value' => 0.00, 'rate_code' => 'GB-0', 'rate_name' => __('Zero rate', 'comptaflow-uk-by-meetempo')],
                ['rate_value' => 0.00, 'rate_code' => 'GB-EXEMPT', 'rate_name' => __('Exempt', 'comptaflow-uk-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 = '5030'): 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="5" placeholder="' . esc_attr__('Type fuel, stationery, legal...', 'comptaflow-uk-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 #d63638; margin-bottom: 10px;">';
        if ($selectedAccount) {
            echo '<strong>' . esc_html($selectedAccount['code']) . '</strong> - ' . esc_html($selectedAccount['label']);
        } else {
            echo '<strong>5030</strong> - ' . esc_html__('General Expenses', 'comptaflow-uk-by-meetempo');
        }
        echo '</div>';
        
        echo '<div id="favorite-accounts" style="margin-bottom: 15px;">';
        echo '<p style="margin-bottom: 8px;"><strong>' . esc_html__('Common expense accounts:', 'comptaflow-uk-by-meetempo') . '</strong></p>';
        $favoriteAccounts = [
            '5030' => __('General Expenses (Utilities, Fuel)', 'comptaflow-uk-by-meetempo'),
            '5010' => __('Cost of Sales (Goods purchased)', 'comptaflow-uk-by-meetempo'),
            '7430' => __('Professional Fees (Accountants, Solicitors)', 'comptaflow-uk-by-meetempo'), 
            '7500' => __('Motor Expenses (Garage, Repairs)', 'comptaflow-uk-by-meetempo'),
            '7400' => __('Bank Charges (Card fees, Commissions)', 'comptaflow-uk-by-meetempo')
        ];
        
        foreach ($favoriteAccounts as $code => $label) {
            $active_style = ($code === $selectedCode) ? 'background: #d63638; color: white;' : '';
            echo '<button type="button" class="account-quick-select" data-code="' . esc_attr($code) . '" data-label="' . esc_attr($label) . '" style="' . esc_attr($active_style) . ' margin: 2px; padding: 5px 10px; border: 1px solid #ccc; background: #f8f9fa; cursor: pointer; border-radius: 3px;">';
            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('EXPENSE');
        $table->prepare_items();
        
        $table->display();
    }
    
    private static function showMessages(): void {
        settings_errors('comptaflow_uk_expenses');
    }
}
