<?php
namespace ComptaFlowPro\Admin\Screens;

defined('ABSPATH') || exit;

class JournalEntriesScreen {
    
    public static function render(): void {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have sufficient permissions.', 'comptaflow-by-meetempo'));
        }
        
        echo '<div class="wrap">';
        echo '<h1>' . esc_html__('Journal Entries', 'comptaflow-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="cfp-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-journal">';
        
        echo '<label>' . esc_html__('From:', 'comptaflow-by-meetempo') . ' <input type="date" name="from" value="' . esc_attr($from) . '"></label>';
        echo '<label>' . esc_html__('To:', 'comptaflow-by-meetempo') . ' <input type="date" name="to" value="' . esc_attr($to) . '"></label>';
        
        echo '<label>' . esc_html__('Journal:', 'comptaflow-by-meetempo') . ' 
        <select name="journal">
            <option value="">' . esc_html__('All', 'comptaflow-by-meetempo') . '</option>
            <option value="VE"' . selected($journal, 'VE', false) . '>' . esc_html__('VE - Sales', 'comptaflow-by-meetempo') . '</option>
            <option value="AC"' . selected($journal, 'AC', false) . '>' . esc_html__('AC - Purchases', 'comptaflow-by-meetempo') . '</option>
            <option value="TR"' . selected($journal, 'TR', false) . '>' . esc_html__('TR - Treasury', 'comptaflow-by-meetempo') . '</option>
            <option value="OD"' . selected($journal, 'OD', false) . '>' . esc_html__('OD - Miscellaneous', 'comptaflow-by-meetempo') . '</option>
        </select></label>';
        
        echo '<label>' . esc_html__('Source:', 'comptaflow-by-meetempo') . ' 
        <select name="source">
            <option value="">' . esc_html__('All', 'comptaflow-by-meetempo') . '</option>
            <option value="SALE"' . selected($source, 'SALE', false) . '>' . esc_html__('Sales', 'comptaflow-by-meetempo') . '</option>
            <option value="EXPENSE"' . selected($source, 'EXPENSE', false) . '>' . esc_html__('Purchases', 'comptaflow-by-meetempo') . '</option>
            <option value="PAYMENT"' . selected($source, 'PAYMENT', false) . '>' . esc_html__('Payments', 'comptaflow-by-meetempo') . '</option>
            <option value="VAT_DECLARATION"' . selected($source, 'VAT_DECLARATION', false) . '>' . esc_html__('VAT Declarations', 'comptaflow-by-meetempo') . '</option>
        </select></label>';
        
        echo '<input type="submit" value="' . esc_attr__('Filter', 'comptaflow-by-meetempo') . '" class="button button-primary">';
        echo '</form>';
        echo '</div>';
    }
    
    private static function renderEntriesList(): void {
        global $wpdb;
        $prefix = $wpdb->prefix . 'cfp_';
        $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-by-meetempo') . '</p></div>';
            return;
        }
        
        echo '<div class="cfp-entries-count" style="margin: 20px 0;">';
        echo '<p><strong>' . sprintf(
            /* translators: %d: number of entries found */
            esc_html__('%d entries found', 'comptaflow-by-meetempo'),
            count($entries)
        ) . '</strong> ' . esc_html__('(limited to 500 results)', 'comptaflow-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-by-meetempo') . '</th>';
        echo '<th style="width: 50px;">' . esc_html__('Journal', 'comptaflow-by-meetempo') . '</th>';
        echo '<th style="width: 80px;">' . esc_html__('Ref', 'comptaflow-by-meetempo') . '</th>';
        echo '<th style="width: 80px;">' . esc_html__('Account', 'comptaflow-by-meetempo') . '</th>';
        echo '<th>' . esc_html__('Label', 'comptaflow-by-meetempo') . '</th>';
        echo '<th style="width: 100px;">' . esc_html__('Debit', 'comptaflow-by-meetempo') . '</th>';
        echo '<th style="width: 100px;">' . esc_html__('Credit', 'comptaflow-by-meetempo') . '</th>';
        echo '<th style="width: 100px;">' . esc_html__('Source', 'comptaflow-by-meetempo') . '</th>';
        echo '</tr>';
        echo '</thead>';
        echo '<tbody>';
        
        $current_entry = null;
        $total_debit = 0;
        $total_credit = 0;
        
        foreach ($entries as $entry) {
            // Separator line 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-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-by-meetempo') . ' ' . esc_html(number_format(abs($total_debit - $total_credit), 2, ',', ' ')) . ' €</td>';
        echo '</tr>';
        echo '</tfoot>';
        echo '</table>';
    }
}
