<?php
namespace ComptaFlowUK\Admin\Screens;

defined('ABSPATH') || exit;

class JournalEntriesScreen {
    
    public static function render(): void {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('Insufficient permissions.', 'comptaflow-uk-by-meetempo'));
        }
        
        echo '<div class="wrap">';
        echo '<h1>' . esc_html__('Journal Entries', 'comptaflow-uk-by-meetempo') . '</h1>';
        
        // Search filters
        self::renderFilters();
        
        // Entries list
        self::renderEntriesList();
        
        echo '</div>';
    }
    
    private static function renderFilters(): void {
        $from = isset($_GET['from']) ? sanitize_text_field(wp_unslash($_GET['from'])) : gmdate('Y-m-01');
        $to = isset($_GET['to']) ? sanitize_text_field(wp_unslash($_GET['to'])) : gmdate('Y-m-t');
        $journal = isset($_GET['journal']) ? sanitize_text_field(wp_unslash($_GET['journal'])) : '';
        $source = isset($_GET['source']) ? sanitize_text_field(wp_unslash($_GET['source'])) : '';
        
        echo '<div class="cfuk-journal-filters" style="background: white; padding: 15px; margin: 20px 0; border: 1px solid #ddd; border-radius: 4px;">';
        echo '<form method="GET" style="display: flex; align-items: center; gap: 15px; flex-wrap: wrap;">';
        echo '<input type="hidden" name="page" value="comptaflow-uk-journal">';
        
        echo '<label>' . esc_html__('From:', 'comptaflow-uk-by-meetempo') . ' <input type="date" name="from" value="' . esc_attr($from) . '"></label>';
        echo '<label>' . esc_html__('To:', 'comptaflow-uk-by-meetempo') . ' <input type="date" name="to" value="' . esc_attr($to) . '"></label>';
        
        echo '<label>' . esc_html__('Journal:', 'comptaflow-uk-by-meetempo') . ' 
        <select name="journal">
            <option value="">' . esc_html__('All', 'comptaflow-uk-by-meetempo') . '</option>
            <option value="SL"' . selected($journal, 'SL', false) . '>' . esc_html__('SL - Sales Ledger', 'comptaflow-uk-by-meetempo') . '</option>
            <option value="PL"' . selected($journal, 'PL', false) . '>' . esc_html__('PL - Purchase Ledger', 'comptaflow-uk-by-meetempo') . '</option>
            <option value="CB"' . selected($journal, 'CB', false) . '>' . esc_html__('CB - Cash Book', 'comptaflow-uk-by-meetempo') . '</option>
            <option value="TR"' . selected($journal, 'TR', false) . '>' . esc_html__('TR - Treasury', 'comptaflow-uk-by-meetempo') . '</option>
            <option value="NL"' . selected($journal, 'NL', false) . '>' . esc_html__('NL - Nominal Ledger', 'comptaflow-uk-by-meetempo') . '</option>
        </select></label>';
        
        echo '<label>' . esc_html__('Source:', 'comptaflow-uk-by-meetempo') . ' 
        <select name="source">
            <option value="">' . esc_html__('All', 'comptaflow-uk-by-meetempo') . '</option>
            <option value="SALE"' . selected($source, 'SALE', false) . '>' . esc_html__('Sales (manual entry)', 'comptaflow-uk-by-meetempo') . '</option>
            <option value="EXPENSE"' . selected($source, 'EXPENSE', false) . '>' . esc_html__('Purchases', 'comptaflow-uk-by-meetempo') . '</option>
            <option value="FINANCIAL"' . selected($source, 'FINANCIAL', false) . '>' . esc_html__('Financial operations', 'comptaflow-uk-by-meetempo') . '</option>
            <option value="VAT_DECLARATION"' . selected($source, 'VAT_DECLARATION', false) . '>' . esc_html__('VAT Returns', 'comptaflow-uk-by-meetempo') . '</option>
        </select></label>';
        
        echo '<input type="submit" value="' . esc_attr__('Filter', 'comptaflow-uk-by-meetempo') . '" class="button button-primary">';
        echo '</form>';
        echo '</div>';
    }
    
    private static function renderEntriesList(): void {
        global $wpdb;
        $prefix = $wpdb->prefix . 'cfuk_';
        $user_id = get_current_user_id();
        
        // Build query with filters
        $where_conditions = ['created_by = %d'];
        $where_values = [$user_id];
        
        if (!empty($_GET['from'])) {
            $where_conditions[] = 'date_ecriture >= %s';
            $where_values[] = sanitize_text_field(wp_unslash($_GET['from']));
        }

        if (!empty($_GET['to'])) {
            $where_conditions[] = 'date_ecriture <= %s';
            $where_values[] = sanitize_text_field(wp_unslash($_GET['to']));
        }

        if (!empty($_GET['journal'])) {
            $where_conditions[] = 'journal_code = %s';
            $where_values[] = sanitize_text_field(wp_unslash($_GET['journal']));
        }

        if (!empty($_GET['source'])) {
            $where_conditions[] = 'source = %s';
            $where_values[] = sanitize_text_field(wp_unslash($_GET['source']));
        }
        
        $where_clause = implode(' AND ', $where_conditions);
        
        $entries = $wpdb->get_results($wpdb->prepare(
            "SELECT * FROM {$prefix}journal_entries 
             WHERE $where_clause 
             ORDER BY date_ecriture DESC, ecriture_num DESC, line_no ASC 
             LIMIT 500",
            ...$where_values
        ));
        
        if (empty($entries)) {
            echo '<div class="notice notice-info"><p>' . esc_html__('No entries found for the selected criteria.', 'comptaflow-uk-by-meetempo') . '</p></div>';
            return;
        }
        
        echo '<div class="cfuk-entries-count" style="margin: 20px 0;">';
        echo '<p><strong>' . esc_html(count($entries)) . ' ' . esc_html__('entries found', 'comptaflow-uk-by-meetempo') . '</strong> (' . esc_html__('limited to 500 results', 'comptaflow-uk-by-meetempo') . ')</p>';
        echo '</div>';
        
        echo '<table class="wp-list-table widefat fixed striped">';
        echo '<thead>';
        echo '<tr>';
        echo '<th style="width: 80px;">' . esc_html__('Date', 'comptaflow-uk-by-meetempo') . '</th>';
        echo '<th style="width: 50px;">' . esc_html__('Journal', 'comptaflow-uk-by-meetempo') . '</th>';
        echo '<th style="width: 80px;">' . esc_html__('Reference', 'comptaflow-uk-by-meetempo') . '</th>';
        echo '<th style="width: 80px;">' . esc_html__('Account', 'comptaflow-uk-by-meetempo') . '</th>';
        echo '<th>' . esc_html__('Description', 'comptaflow-uk-by-meetempo') . '</th>';
        echo '<th style="width: 100px;">' . esc_html__('Debit', 'comptaflow-uk-by-meetempo') . '</th>';
        echo '<th style="width: 100px;">' . esc_html__('Credit', 'comptaflow-uk-by-meetempo') . '</th>';
        echo '<th style="width: 100px;">' . esc_html__('Source', 'comptaflow-uk-by-meetempo') . '</th>';
        echo '</tr>';
        echo '</thead>';
        echo '<tbody>';
        
        $current_entry = null;
        $total_debit = 0;
        $total_credit = 0;
        
        foreach ($entries as $entry) {
            // Separator between different entries
            if ($current_entry !== $entry->ecriture_num) {
                if ($current_entry !== null) {
                    echo '<tr style="border-top: 2px solid #ddd;"><td colspan="8"></td></tr>';
                }
                $current_entry = $entry->ecriture_num;
            }
            
            $total_debit += floatval($entry->debit);
            $total_credit += floatval($entry->credit);
            
            echo '<tr>';
            echo '<td>' . esc_html(date_i18n('d/m/Y', strtotime($entry->date_ecriture))) . '</td>';
            echo '<td><strong>' . esc_html($entry->journal_code) . '</strong></td>';
            echo '<td>' . esc_html($entry->piece_ref) . '</td>';
            echo '<td><strong>' . esc_html($entry->compte_num) . '</strong></td>';
            echo '<td>' . esc_html($entry->libelle) . '</td>';
            echo '<td>' . ($entry->debit > 0 ? '£' . esc_html(number_format($entry->debit, 2, '.', ',')) : '') . '</td>';
            echo '<td>' . ($entry->credit > 0 ? '£' . esc_html(number_format($entry->credit, 2, '.', ',')) : '') . '</td>';
            echo '<td><span class="badge">' . esc_html($entry->source ?? '') . '</span></td>';
            echo '</tr>';
        }
        
        echo '</tbody>';
        echo '<tfoot>';
        echo '<tr style="background: #f0f0f1; font-weight: bold;">';
        echo '<td colspan="5">' . esc_html__('TOTALS', 'comptaflow-uk-by-meetempo') . '</td>';
        echo '<td>£' . esc_html(number_format($total_debit, 2, '.', ',')) . '</td>';
        echo '<td>£' . esc_html(number_format($total_credit, 2, '.', ',')) . '</td>';
        echo '<td>' . esc_html__('Balance:', 'comptaflow-uk-by-meetempo') . ' £' . esc_html(number_format(abs($total_debit - $total_credit), 2, '.', ',')) . '</td>';
        echo '</tr>';
        echo '</tfoot>';
        echo '</table>';
    }
}