<?php
namespace ComptaFlowUK\Admin\Screens;

use ComptaFlowUK\Services\CreditNoteService;
use ComptaFlowUK\Services\InvoiceService;
use ComptaFlowUK\Services\ClientService;
use ComptaFlowUK\Services\DB;

defined('ABSPATH') || exit;

class CreditNotesScreen {

    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();

        $action = isset($_GET['action']) ? sanitize_key($_GET['action']) : 'list';

        echo '<div class="wrap">';
        echo '<h1 class="wp-heading-inline">' . esc_html__('Credit Notes', 'comptaflow-uk-by-meetempo') . '</h1>';

        if ($action === 'list') {
            echo '<a href="?page=comptaflow-uk-credit-notes&action=new" class="page-title-action">' . esc_html__('New Credit Note', 'comptaflow-uk-by-meetempo') . '</a>';
        }

        settings_errors('comptaflow_uk_credit_notes');

        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 ($get_action === 'delete' && isset($_GET['id'])) {
            $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : '';
            if (wp_verify_nonce($nonce, 'comptaflow_uk_delete_credit_note')) {
                CreditNoteService::delete(absint($_GET['id']));
                add_settings_error('comptaflow_uk_credit_notes', 'deleted', __('Credit note deleted.', 'comptaflow-uk-by-meetempo'), 'updated');
            }
            return;
        }

        if ($get_action === 'from_invoice' && isset($_GET['invoice_id'])) {
            $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : '';
            if (wp_verify_nonce($nonce, 'comptaflow_uk_cn_from_invoice')) {
                $cn_id = CreditNoteService::createFromInvoice(absint($_GET['invoice_id']));
                if ($cn_id) {
                    add_settings_error('comptaflow_uk_credit_notes', 'created', __('Credit note created from invoice. Journal entries generated.', 'comptaflow-uk-by-meetempo'), 'updated');
                }
            }
            return;
        }

        if (!isset($_POST['_wpnonce'])) {
            return;
        }

        $nonce = sanitize_text_field(wp_unslash($_POST['_wpnonce']));
        if (!wp_verify_nonce($nonce, 'comptaflow_uk_credit_note_save')) {
            return;
        }

        $data = [
            'client_id' => isset($_POST['client_id']) ? absint($_POST['client_id']) : null,
            'issue_date' => isset($_POST['issue_date']) ? sanitize_text_field(wp_unslash($_POST['issue_date'])) : gmdate('Y-m-d'),
            'currency' => 'GBP',
            'notes' => isset($_POST['notes']) ? sanitize_textarea_field(wp_unslash($_POST['notes'])) : '',
            'converted_from' => isset($_POST['converted_from']) ? absint($_POST['converted_from']) : null,
        ];

        $lines = self::parseLines();

        $id = isset($_POST['cn_id']) ? absint($_POST['cn_id']) : 0;
        if ($id) {
            CreditNoteService::update($id, $data, $lines);
            add_settings_error('comptaflow_uk_credit_notes', 'updated', __('Credit note updated.', 'comptaflow-uk-by-meetempo'), 'updated');
        } else {
            CreditNoteService::create($data, $lines);
            add_settings_error('comptaflow_uk_credit_notes', 'created', __('Credit note created. Journal entries generated.', 'comptaflow-uk-by-meetempo'), 'updated');
        }
    }

    // phpcs:disable WordPress.Security.NonceVerification.Missing -- nonce verified in handleActions() before calling this method
    private static function parseLines(): array {
        $lines = [];
        if (!isset($_POST['line_description']) || !is_array($_POST['line_description'])) {
            return $lines;
        }

        $descriptions = array_map('sanitize_text_field', wp_unslash($_POST['line_description']));
        $quantities = isset($_POST['line_quantity']) ? array_map('floatval', wp_unslash($_POST['line_quantity'])) : [];
        $prices = isset($_POST['line_unit_price']) ? array_map('floatval', wp_unslash($_POST['line_unit_price'])) : [];
        $vat_rates = isset($_POST['line_vat_rate']) ? array_map('floatval', wp_unslash($_POST['line_vat_rate'])) : [];
        $vat_codes = isset($_POST['line_vat_code']) ? array_map('sanitize_text_field', wp_unslash($_POST['line_vat_code'])) : [];
        $account_codes = isset($_POST['line_account_code']) ? array_map('sanitize_text_field', wp_unslash($_POST['line_account_code'])) : [];

        foreach ($descriptions as $i => $desc) {
            if (empty($desc)) {
                continue;
            }
            $lines[] = [
                'description' => $desc,
                'quantity' => $quantities[$i] ?? 1,
                'unit_price' => $prices[$i] ?? 0,
                'vat_rate' => $vat_rates[$i] ?? 20,
                'vat_code' => $vat_codes[$i] ?? 'GB-20',
                'account_code' => $account_codes[$i] ?? '4010',
            ];
        }

        return $lines;
    }
    // phpcs:enable WordPress.Security.NonceVerification.Missing

    private static function renderForm(string $action): void {
        $cn = [];
        $lines = [];
        if ($action === 'edit' && isset($_GET['id'])) {
            $cn = CreditNoteService::getById(absint($_GET['id']));
            $lines = CreditNoteService::getLines(absint($_GET['id']));
        }

        $clients = ClientService::getAll(0, '', 200, 0);
        $vat_rates = DB::getActiveVATRates('GB');
        if (empty($vat_rates)) {
            $vat_rates = [
                ['rate_value' => 20.00, 'rate_code' => 'GB-20', 'rate_name' => 'Standard 20%'],
                ['rate_value' => 5.00, 'rate_code' => 'GB-5', 'rate_name' => 'Reduced 5%'],
                ['rate_value' => 0.00, 'rate_code' => 'GB-0', 'rate_name' => 'Zero 0%'],
            ];
        }

        echo '<h2>' . ($action === 'edit' ? esc_html__('Edit Credit Note', 'comptaflow-uk-by-meetempo') : esc_html__('New Credit Note', 'comptaflow-uk-by-meetempo')) . '</h2>';
        echo '<form method="post" id="invoice-form">';
        wp_nonce_field('comptaflow_uk_credit_note_save');
        if (!empty($cn['id'])) {
            echo '<input type="hidden" name="cn_id" value="' . esc_attr($cn['id']) . '">';
        }

        echo '<table class="form-table">';
        echo '<tr><th>' . esc_html__('Client', 'comptaflow-uk-by-meetempo') . '</th><td>';
        echo '<select name="client_id">';
        echo '<option value="">' . esc_html__('-- Select a client --', 'comptaflow-uk-by-meetempo') . '</option>';
        foreach ($clients as $c) {
            echo '<option value="' . esc_attr($c['id']) . '"' . selected($cn['client_id'] ?? '', $c['id'], false) . '>' . esc_html(ClientService::getDisplayName($c)) . '</option>';
        }
        echo '</select></td></tr>';

        echo '<tr><th>' . esc_html__('Date', 'comptaflow-uk-by-meetempo') . '</th>';
        echo '<td><input type="date" name="issue_date" value="' . esc_attr($cn['issue_date'] ?? gmdate('Y-m-d')) . '" required></td></tr>';

        echo '<tr><th>' . esc_html__('Notes', 'comptaflow-uk-by-meetempo') . '</th>';
        echo '<td><textarea name="notes" rows="2" class="large-text">' . esc_textarea($cn['notes'] ?? '') . '</textarea></td></tr>';
        echo '</table>';

        echo '<h3>' . esc_html__('Credit Note Lines', 'comptaflow-uk-by-meetempo') . '</h3>';
        echo '<table class="wp-list-table widefat" id="invoice-lines-table">';
        echo '<thead><tr>';
        echo '<th style="width:35%">' . esc_html__('Description', 'comptaflow-uk-by-meetempo') . '</th>';
        echo '<th style="width:8%">' . esc_html__('Qty', 'comptaflow-uk-by-meetempo') . '</th>';
        echo '<th style="width:12%">' . esc_html__('Unit Price', 'comptaflow-uk-by-meetempo') . '</th>';
        echo '<th style="width:12%">' . esc_html__('VAT Rate', 'comptaflow-uk-by-meetempo') . '</th>';
        echo '<th style="width:10%">' . esc_html__('Account', 'comptaflow-uk-by-meetempo') . '</th>';
        echo '<th style="width:10%" class="right">' . esc_html__('Net', 'comptaflow-uk-by-meetempo') . '</th>';
        echo '<th style="width:10%" class="right">' . esc_html__('VAT', 'comptaflow-uk-by-meetempo') . '</th>';
        echo '<th style="width:4%"></th>';
        echo '</tr></thead><tbody id="invoice-lines-body">';

        if (empty($lines)) {
            $lines = [['description' => '', 'quantity' => 1, 'unit_price' => 0, 'vat_rate' => 20, 'vat_code' => 'GB-20', 'account_code' => '4010', 'line_total' => 0, 'vat_amount' => 0]];
        }

        foreach ($lines as $i => $line) {
            echo '<tr class="invoice-line-row">';
            echo '<td><input type="text" name="line_description[]" value="' . esc_attr($line['description']) . '" class="regular-text" style="width:100%"></td>';
            echo '<td><input type="number" name="line_quantity[]" value="' . esc_attr($line['quantity']) . '" step="0.001" min="0" style="width:100%" class="line-qty"></td>';
            echo '<td><input type="number" name="line_unit_price[]" value="' . esc_attr($line['unit_price']) . '" step="0.01" min="0" style="width:100%" class="line-price"></td>';
            echo '<td><select name="line_vat_rate[]" class="line-vat-rate" style="width:100%">';
            foreach ($vat_rates as $rate) {
                $is_selected = (abs(floatval($rate['rate_value']) - floatval($line['vat_rate'])) < 0.01);
                echo '<option value="' . esc_attr($rate['rate_value']) . '" data-code="' . esc_attr($rate['rate_code']) . '"' . ($is_selected ? ' selected' : '') . '>' . esc_html(number_format($rate['rate_value'], 0) . '%') . '</option>';
            }
            echo '</select><input type="hidden" name="line_vat_code[]" value="' . esc_attr($line['vat_code'] ?? 'GB-20') . '" class="line-vat-code"></td>';
            echo '<td><input type="text" name="line_account_code[]" value="' . esc_attr($line['account_code'] ?? '4010') . '" style="width:100%"></td>';
            echo '<td class="right line-net">&pound;' . esc_html(number_format(floatval($line['line_total'] ?? 0), 2)) . '</td>';
            echo '<td class="right line-vat-amount">&pound;' . esc_html(number_format(floatval($line['vat_amount'] ?? 0), 2)) . '</td>';
            echo '<td><button type="button" class="button remove-invoice-line">&times;</button></td>';
            echo '</tr>';
        }

        echo '</tbody></table>';
        echo '<p><button type="button" id="add-invoice-line" class="button">' . esc_html__('+ Add Line', 'comptaflow-uk-by-meetempo') . '</button></p>';

        echo '<div style="max-width:350px; margin-left:auto; background:#f8f9fa; padding:15px; border:1px solid #ddd; border-radius:4px;">';
        echo '<table style="width:100%">';
        echo '<tr><td>' . esc_html__('Subtotal:', 'comptaflow-uk-by-meetempo') . '</td><td class="right" id="inv-subtotal">&pound;0.00</td></tr>';
        echo '<tr><td>' . esc_html__('Total VAT:', 'comptaflow-uk-by-meetempo') . '</td><td class="right" id="inv-totalvat">&pound;0.00</td></tr>';
        echo '<tr style="font-size:16px;font-weight:bold;"><td>' . esc_html__('Total Credit:', 'comptaflow-uk-by-meetempo') . '</td><td class="right" id="inv-total">&pound;0.00</td></tr>';
        echo '</table></div>';

        submit_button($action === 'edit' ? esc_html__('Update Credit Note', 'comptaflow-uk-by-meetempo') : esc_html__('Create Credit Note', 'comptaflow-uk-by-meetempo'));
        echo '</form>';

        wp_localize_script('comptaflow-uk-invoices', 'comptaflow_uk_invoice_data', ['vat_rates' => $vat_rates]);
    }

    private static function renderList(): void {
        $search = isset($_GET['s']) ? sanitize_text_field(wp_unslash($_GET['s'])) : '';
        $page_num = isset($_GET['paged']) ? absint($_GET['paged']) : 1;
        $per_page = 20;
        $offset = ($page_num - 1) * $per_page;

        $items = CreditNoteService::getAll($search, '', $per_page, $offset);
        $total = CreditNoteService::count($search);

        echo '<table class="wp-list-table widefat fixed striped">';
        echo '<thead><tr>';
        echo '<th>' . esc_html__('Number', 'comptaflow-uk-by-meetempo') . '</th>';
        echo '<th>' . esc_html__('Client', 'comptaflow-uk-by-meetempo') . '</th>';
        echo '<th>' . esc_html__('Date', 'comptaflow-uk-by-meetempo') . '</th>';
        echo '<th>' . esc_html__('Total', 'comptaflow-uk-by-meetempo') . '</th>';
        echo '<th>' . esc_html__('Actions', 'comptaflow-uk-by-meetempo') . '</th>';
        echo '</tr></thead><tbody>';

        if (empty($items)) {
            echo '<tr><td colspan="5">' . esc_html__('No credit notes found.', 'comptaflow-uk-by-meetempo') . '</td></tr>';
        }

        foreach ($items as $cn) {
            $edit_url = admin_url('admin.php?page=comptaflow-uk-credit-notes&action=edit&id=' . $cn['id']);
            $delete_url = wp_nonce_url(admin_url('admin.php?page=comptaflow-uk-credit-notes&action=delete&id=' . $cn['id']), 'comptaflow_uk_delete_credit_note');
            $pdf_url = wp_nonce_url(admin_url('admin-post.php?action=comptaflow_uk_pdf_view&id=' . $cn['id']), 'comptaflow_uk_pdf');

            $client_name = $cn['company_name'] ?? ($cn['contact_name'] ?? '');

            echo '<tr>';
            echo '<td><strong><a href="' . esc_url($edit_url) . '">' . esc_html($cn['invoice_number']) . '</a></strong></td>';
            echo '<td>' . esc_html($client_name) . '</td>';
            echo '<td>' . esc_html(date_i18n('d/m/Y', strtotime($cn['issue_date']))) . '</td>';
            echo '<td>&pound;' . esc_html(number_format(floatval($cn['total']), 2)) . '</td>';
            echo '<td>';
            echo '<a href="' . esc_url($pdf_url) . '" target="_blank">' . esc_html__('PDF', 'comptaflow-uk-by-meetempo') . '</a> | ';
            echo '<a href="' . esc_url($edit_url) . '">' . esc_html__('Edit', 'comptaflow-uk-by-meetempo') . '</a> | ';
            echo '<a href="' . esc_url($delete_url) . '" onclick="return confirm(\'' . esc_js(__('Delete?', 'comptaflow-uk-by-meetempo')) . '\')">' . esc_html__('Delete', 'comptaflow-uk-by-meetempo') . '</a>';
            echo '</td>';
            echo '</tr>';
        }

        echo '</tbody></table>';
    }
}
