<?php
namespace ComptaFlowUK\Admin\Screens;

use ComptaFlowUK\Services\ChartOfAccounts;

defined('ABSPATH') || exit;

class ManualJournalEntryScreen {
    
    public static function render(): void {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('Insufficient permissions.', 'comptaflow-uk-by-meetempo'));
        }
        
        self::handleActions();
        
        echo '<div class="wrap">';
        echo '<h1>' . esc_html__('Manual Journal Entries', 'comptaflow-uk-by-meetempo') . '</h1>';
        echo '<p class="description">' . esc_html__('For depreciation charges, provisions, adjustments, etc.', 'comptaflow-uk-by-meetempo') . '</p>';
        
        self::showMessages();
        self::renderForm();
        
        echo '</div>';
    }
    
    private static function handleActions(): void {
        if (!isset($_POST['_wpnonce']) || !isset($_POST['action'])) {
            return;
        }
        
        $nonce = isset($_POST['_wpnonce']) ? sanitize_text_field(wp_unslash($_POST['_wpnonce'])) : '';
        $post_action = sanitize_text_field(wp_unslash($_POST['action']));
        if ($post_action === 'comptaflow_uk_create_manual_od' && wp_verify_nonce($nonce, 'comptaflow_uk_manual_od_action')) {
            self::saveManualOD();
        }
    }
    
    private static function saveManualOD(): void {
        global $wpdb;
        $journal_table = $wpdb->prefix . 'cfuk_journal_entries';
        $user_id = get_current_user_id();
        
        $date_ecriture = sanitize_text_field(wp_unslash($_POST['date_ecriture']));
        $piece_ref = sanitize_text_field(wp_unslash($_POST['piece_ref']));
        $label = sanitize_text_field(wp_unslash($_POST['libelle']));
        $lines_json = isset($_POST['lines_json']) ? sanitize_text_field(wp_unslash($_POST['lines_json'])) : '[]';
        $lines = json_decode($lines_json, true);
        
        if (json_last_error() !== JSON_ERROR_NONE || empty($lines) || !is_array($lines)) {
            add_settings_error('comptaflow_uk_manual_od', 'error', __('No lines entered.', 'comptaflow-uk-by-meetempo'));
            return;
        }
        
        // Validate debit/credit balance
        $total_debit = 0;
        $total_credit = 0;
        foreach ($lines as $line) {
            $total_debit += floatval($line['debit'] ?? 0);
            $total_credit += floatval($line['credit'] ?? 0);
        }
        
        if (round($total_debit, 2) !== round($total_credit, 2)) {
            add_settings_error('comptaflow_uk_manual_od', 'error', sprintf(
                /* translators: %1$s: debit total, %2$s: credit total */
                __('Unbalanced entry: Debit £%1$.2f ≠ Credit £%2$.2f', 'comptaflow-uk-by-meetempo'),
                $total_debit, $total_credit
            ));
            return;
        }
        
        $wpdb->query('START TRANSACTION');
        $ok = true;
        
        foreach ($lines as $line) {
            $account = sanitize_text_field($line['compte']);
            $debit = floatval($line['debit'] ?? 0);
            $credit = floatval($line['credit'] ?? 0);
            
            if (empty($account) || ($debit == 0 && $credit == 0)) {
                continue;
            }
            
            $res = $wpdb->insert($journal_table, [
                'uuid' => wp_generate_uuid4(),
                'date_ecriture' => $date_ecriture,
                'journal_code' => 'NL',
                'piece_ref' => $piece_ref,
                'compte_num' => $account,
                'libelle' => $label,
                'debit' => $debit,
                'credit' => $credit,
                'created_by' => $user_id,
                'created_at' => current_time('mysql'),
                'source' => 'MANUAL_NL',
                'transaction_id' => null,
            ]);
            
            if ($res === false) {
                $ok = false;
                break;
            }
        }
        
        if ($ok) {
            $wpdb->query('COMMIT');
            add_settings_error('comptaflow_uk_manual_od', 'success', __('Journal entry saved successfully!', 'comptaflow-uk-by-meetempo'), 'updated');
        } else {
            $wpdb->query('ROLLBACK');
            add_settings_error('comptaflow_uk_manual_od', 'error', __('Error saving entry.', 'comptaflow-uk-by-meetempo'));
        }
    }
    
    private static function renderForm(): void {
        ?>
        <div class="postbox" style="max-width: 900px; margin-top: 20px;">
            <h2 class="hndle" style="padding: 10px;"><span><?php echo esc_html__('New Journal Entry', 'comptaflow-uk-by-meetempo'); ?></span></h2>
            <div class="inside" style="padding: 20px;">
                
                <form method="post" id="comptaflow-uk-manual-od-form">
                    <?php wp_nonce_field('comptaflow_uk_manual_od_action'); ?>
                    <input type="hidden" name="action" value="comptaflow_uk_create_manual_od">
                    <input type="hidden" name="lines_json" id="lines_json" value="[]">
                    
                    <table class="form-table">
                        <tr>
                            <th><label for="date_ecriture"><?php echo esc_html__('Date *', 'comptaflow-uk-by-meetempo'); ?></label></th>
                            <td><input type="date" name="date_ecriture" id="date_ecriture" value="<?php echo esc_attr(gmdate('Y-m-d')); ?>" required></td>
                        </tr>
                        <tr>
                            <th><label for="piece_ref"><?php echo esc_html__('Reference no.', 'comptaflow-uk-by-meetempo'); ?></label></th>
                            <td><input type="text" name="piece_ref" id="piece_ref" value="OD-<?php echo esc_attr(gmdate('Ymd-His')); ?>" class="regular-text"></td>
                        </tr>
                        <tr>
                            <th><label for="libelle"><?php echo esc_html__('Description *', 'comptaflow-uk-by-meetempo'); ?></label></th>
                            <td><input type="text" name="libelle" id="libelle" placeholder="<?php echo esc_attr__('E.g.: Equipment depreciation charge', 'comptaflow-uk-by-meetempo'); ?>" class="regular-text" required></td>
                        </tr>
                    </table>
                    
                    <h3><?php echo esc_html__('Entry lines', 'comptaflow-uk-by-meetempo'); ?></h3>
                    <p class="description"><?php echo esc_html__('Enter your journal lines. Total debit must equal total credit.', 'comptaflow-uk-by-meetempo'); ?></p>
                    
                    <table class="wp-list-table widefat fixed striped" id="od-lines-table">
                        <thead>
                            <tr>
                                <th style="width: 200px;"><?php echo esc_html__('Account *', 'comptaflow-uk-by-meetempo'); ?></th>
                                <th><?php echo esc_html__('Line description', 'comptaflow-uk-by-meetempo'); ?></th>
                                <th style="width: 140px; text-align: right;"><?php echo esc_html__('Debit (£)', 'comptaflow-uk-by-meetempo'); ?></th>
                                <th style="width: 140px; text-align: right;"><?php echo esc_html__('Credit (£)', 'comptaflow-uk-by-meetempo'); ?></th>
                                <th style="width: 50px;"></th>
                            </tr>
                        </thead>
                        <tbody id="od-lines-tbody">
                            <tr class="od-line-row">
                                <td>
                                    <input type="text" class="line-compte" placeholder="<?php echo esc_attr__('E.g.: 8010', 'comptaflow-uk-by-meetempo'); ?>" style="width: 100%;" list="accounts-datalist">
                                </td>
                                <td>
                                    <input type="text" class="line-libelle" placeholder="<?php echo esc_attr__('Optional', 'comptaflow-uk-by-meetempo'); ?>" style="width: 100%;">
                                </td>
                                <td>
                                    <input type="number" class="line-debit" step="0.01" min="0" value="0" style="width: 100%; text-align: right;">
                                </td>
                                <td>
                                    <input type="number" class="line-credit" step="0.01" min="0" value="0" style="width: 100%; text-align: right;">
                                </td>
                                <td class="text-center">
                                    <button type="button" class="button button-link-delete remove-line">×</button>
                                </td>
                            </tr>
                        </tbody>
                        <tfoot>
                            <tr>
                                <td colspan="2" style="text-align: right;"><strong><?php echo esc_html__('Totals', 'comptaflow-uk-by-meetempo'); ?></strong></td>
                                <td style="text-align: right;"><strong id="total-debit">0.00</strong></td>
                                <td style="text-align: right;"><strong id="total-credit">0.00</strong></td>
                                <td></td>
                            </tr>
                            <tr>
                                <td colspan="2" style="text-align: right;"><strong><?php echo esc_html__('Difference', 'comptaflow-uk-by-meetempo'); ?></strong></td>
                                <td colspan="2" style="text-align: right;"><strong id="difference" style="color: #d63638;">0.00</strong></td>
                                <td></td>
                            </tr>
                        </tfoot>
                    </table>
                    
                    <p style="margin-top: 10px;">
                        <button type="button" class="button" id="add-line"><?php echo esc_html__('+ Add a line', 'comptaflow-uk-by-meetempo'); ?></button>
                    </p>
                    
                    <?php submit_button(esc_html__('Save journal entry', 'comptaflow-uk-by-meetempo')); ?>
                </form>
                
                <datalist id="accounts-datalist">
                    <?php
                    $accounts = ChartOfAccounts::getAllAccounts();
                    foreach ($accounts as $code => $account) {
                        echo '<option value="' . esc_attr($code) . '">' . esc_html($account['label']) . '</option>';
                    }
                    ?>
                </datalist>
                
            </div>
        </div>
        
        <div class="postbox" style="max-width: 900px; margin-top: 20px;">
            <h2 class="hndle" style="padding: 10px;"><span><?php echo esc_html__('Common journal entry examples', 'comptaflow-uk-by-meetempo'); ?></span></h2>
            <div class="inside" style="padding: 15px;">
                <h4><?php echo esc_html__('Depreciation charge', 'comptaflow-uk-by-meetempo'); ?></h4>
                <p><code>8010 (Debit) → 0xx1 (Credit)</code><br><?php echo esc_html__('E.g.: Computer depreciation', 'comptaflow-uk-by-meetempo'); ?></p>
                
                <h4><?php echo esc_html__('Provision for liabilities', 'comptaflow-uk-by-meetempo'); ?></h4>
                <p><code>8015 (Debit) → 2400 (Credit)</code><br><?php echo esc_html__('E.g.: Provision for legal claim', 'comptaflow-uk-by-meetempo'); ?></p>
                
                <h4><?php echo esc_html__('Prepayments', 'comptaflow-uk-by-meetempo'); ?></h4>
                <p><code>1103 (Debit) → 6xxx (Credit)</code><br><?php echo esc_html__('E.g.: Rent paid in advance', 'comptaflow-uk-by-meetempo'); ?></p>
                
                <h4><?php echo esc_html__('Accrued income', 'comptaflow-uk-by-meetempo'); ?></h4>
                <p><code>1104 (Debit) → 4xxx (Credit)</code><br><?php echo esc_html__('E.g.: Service delivered but not yet invoiced', 'comptaflow-uk-by-meetempo'); ?></p>
            </div>
        </div>
        
        <?php
    }
    
    private static function showMessages(): void {
        settings_errors('comptaflow_uk_manual_od');
    }
}
