<?php
namespace ComptaFlowPro\Admin\Screens;

use ComptaFlowPro\Services\ChartOfAccounts;

defined('ABSPATH') || exit;

class ManualJournalEntryScreen {
    
    public static function render(): void {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have sufficient permissions.', 'comptaflow-by-meetempo'));
        }
        
        self::handleActions();
        
        echo '<div class="wrap">';
        echo '<h1>' . esc_html__('Manual Journal Entries', 'comptaflow-by-meetempo') . '</h1>';
        echo '<p class="description">' . esc_html__('For depreciation, provisions, adjustments, etc.', 'comptaflow-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'])) : '';
        if (isset($_POST['action']) && $_POST['action'] === 'comptaflow_create_manual_od' && wp_verify_nonce($nonce, 'comptaflow_manual_od_action')) {
            self::saveManualOD();
        }
    }
    
    private static function saveManualOD(): void {
        global $wpdb;
        $journal_table = $wpdb->prefix . 'cfp_journal_entries';
        $user_id = get_current_user_id();
        
        $date_ecriture = sanitize_text_field($_POST['date_ecriture'] ?? '');
        $piece_ref = sanitize_text_field($_POST['piece_ref'] ?? '');
        $libelle = sanitize_text_field($_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_manual_od', 'error', __('No lines entered.', 'comptaflow-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_manual_od', 'error', sprintf(
                /* translators: %1$s: debit amount, %2$s: credit amount */
                __('Unbalanced entry: Debit %1$.2f € ≠ Credit %2$.2f €', 'comptaflow-by-meetempo'),
                $total_debit, $total_credit
            ));
            return;
        }
        
        $wpdb->query('START TRANSACTION');
        $ok = true;
        
        foreach ($lines as $line) {
            $compte = sanitize_text_field($line['compte'] ?? '');
            $debit = floatval($line['debit'] ?? 0);
            $credit = floatval($line['credit'] ?? 0);
            
            if (empty($compte) || ($debit == 0 && $credit == 0)) {
                continue;
            }
            
            $res = $wpdb->insert($journal_table, [
                'uuid' => wp_generate_uuid4(),
                'date_ecriture' => $date_ecriture,
                'journal_code' => 'OD',
                'piece_ref' => $piece_ref,
                'compte_num' => $compte,
                'libelle' => $libelle,
                'debit' => $debit,
                'credit' => $credit,
                'created_by' => $user_id,
                'created_at' => current_time('mysql'),
                'source' => 'MANUAL_OD',
                'transaction_id' => null,
            ]);
            
            if ($res === false) {
                $ok = false;
                break;
            }
        }
        
        if ($ok) {
            $wpdb->query('COMMIT');
            add_settings_error('comptaflow_manual_od', 'success', __('Manual entry saved successfully!', 'comptaflow-by-meetempo'), 'updated');
        } else {
            $wpdb->query('ROLLBACK');
            add_settings_error('comptaflow_manual_od', 'error', __('Error saving the entry.', 'comptaflow-by-meetempo'));
        }
    }
    
    private static function renderForm(): void {
        $current_date = gmdate('Y-m-d');
        $default_ref = 'OD-' . gmdate('Ymd-His');
        ?>
        <div class="postbox" style="max-width: 900px; margin-top: 20px;">
            <h2 class="hndle" style="padding: 10px;"><span><?php echo esc_html__('New Manual Entry', 'comptaflow-by-meetempo'); ?></span></h2>
            <div class="inside" style="padding: 20px;">
                
                <form method="post" id="comptaflow-manual-od-form">
                    <?php wp_nonce_field('comptaflow_manual_od_action'); ?>
                    <input type="hidden" name="action" value="comptaflow_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-by-meetempo'); ?> *</label></th>
                            <td><input type="date" name="date_ecriture" id="date_ecriture" value="<?php echo esc_attr($current_date); ?>" required></td>
                        </tr>
                        <tr>
                            <th><label for="piece_ref"><?php echo esc_html__('Reference #', 'comptaflow-by-meetempo'); ?></label></th>
                            <td><input type="text" name="piece_ref" id="piece_ref" value="<?php echo esc_attr($default_ref); ?>" class="regular-text"></td>
                        </tr>
                        <tr>
                            <th><label for="libelle"><?php echo esc_html__('General Label', 'comptaflow-by-meetempo'); ?> *</label></th>
                            <td><input type="text" name="libelle" id="libelle" placeholder="<?php echo esc_attr__('Ex: Equipment depreciation', 'comptaflow-by-meetempo'); ?>" class="regular-text" required></td>
                        </tr>
                    </table>
                    
                    <h3><?php echo esc_html__('Entry Lines', 'comptaflow-by-meetempo'); ?></h3>
                    <p class="description"><?php echo esc_html__('Enter your accounting lines. Total debit must equal total credit.', 'comptaflow-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-by-meetempo'); ?> *</th>
                                <th><?php echo esc_html__('Line Label', 'comptaflow-by-meetempo'); ?></th>
                                <th style="width: 140px; text-align: right;"><?php echo esc_html__('Debit (€)', 'comptaflow-by-meetempo'); ?></th>
                                <th style="width: 140px; text-align: right;"><?php echo esc_html__('Credit (€)', 'comptaflow-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__('Ex: 6811', 'comptaflow-by-meetempo'); ?>" style="width: 100%;" list="accounts-datalist">
                                </td>
                                <td>
                                    <input type="text" class="line-libelle" placeholder="<?php echo esc_attr__('Optional', 'comptaflow-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-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-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-by-meetempo'); ?></button>
                    </p>
                    
                    <?php submit_button(__('Save Manual Entry', 'comptaflow-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 Manual Entry Examples', 'comptaflow-by-meetempo'); ?></span></h2>
            <div class="inside" style="padding: 15px;">
                <h4><?php echo esc_html__('Depreciation', 'comptaflow-by-meetempo'); ?></h4>
                <p><code>6811 (<?php echo esc_html__('Debit', 'comptaflow-by-meetempo'); ?>) → 28xxx (<?php echo esc_html__('Credit', 'comptaflow-by-meetempo'); ?>)</code><br><?php echo esc_html__('Ex: Computer depreciation', 'comptaflow-by-meetempo'); ?></p>
                
                <h4><?php echo esc_html__('Provision for Risks', 'comptaflow-by-meetempo'); ?></h4>
                <p><code>6815 (<?php echo esc_html__('Debit', 'comptaflow-by-meetempo'); ?>) → 151x (<?php echo esc_html__('Credit', 'comptaflow-by-meetempo'); ?>)</code><br><?php echo esc_html__('Ex: Litigation provision', 'comptaflow-by-meetempo'); ?></p>
                
                <h4><?php echo esc_html__('Prepaid Expenses', 'comptaflow-by-meetempo'); ?></h4>
                <p><code>486 (<?php echo esc_html__('Debit', 'comptaflow-by-meetempo'); ?>) → 6xxx (<?php echo esc_html__('Credit', 'comptaflow-by-meetempo'); ?>)</code><br><?php echo esc_html__('Ex: Prepaid rent', 'comptaflow-by-meetempo'); ?></p>
                
                <h4><?php echo esc_html__('Accrued Revenue', 'comptaflow-by-meetempo'); ?></h4>
                <p><code>418 (<?php echo esc_html__('Debit', 'comptaflow-by-meetempo'); ?>) → 7xxx (<?php echo esc_html__('Credit', 'comptaflow-by-meetempo'); ?>)</code><br><?php echo esc_html__('Ex: Unbilled service performed', 'comptaflow-by-meetempo'); ?></p>
            </div>
        </div>
        
        <?php
    }
    
    private static function showMessages(): void {
        settings_errors('comptaflow_manual_od');
    }
}
