<?php
// File: src/Admin/Actions/PaymentsActions.php
// Version 1.2 - UK payment processing

namespace ComptaFlowUK\Admin\Actions;

use ComptaFlowUK\Services\JournalEntryGenerator;

defined('ABSPATH') || exit;

class PaymentsActions
{
    /**
     * Register payment action listener.
     */
    public static function boot(): void
    {
        add_action('admin_post_comptaflow_uk_mark_as_paid', [self::class, 'handleMarkAsPaid']);
    }

    /**
     * Handle "Mark as Paid" form submission.
     */
    public static function handleMarkAsPaid(): void
    {
        // 1. Security and permission checks
        if (!current_user_can('manage_options')) {
            wp_die('Insufficient permissions.');
        }

        check_admin_referer('comptaflow_uk_mark_paid_nonce');

        // 2. Retrieve and sanitise data
        $tx_id        = isset($_REQUEST['tx_id']) ? intval($_REQUEST['tx_id']) : 0;
        $payment_date = !empty($_REQUEST['payment_date']) ? sanitize_text_field(wp_unslash($_REQUEST['payment_date'])) : current_time('Y-m-d');
        $method       = !empty($_REQUEST['payment_method']) ? sanitize_text_field(wp_unslash($_REQUEST['payment_method'])) : 'BANK_TRANSFER';
        $redirect_to  = !empty($_REQUEST['redirect_to']) ? esc_url_raw(wp_unslash($_REQUEST['redirect_to'])) : admin_url();

        if ($tx_id === 0) {
            wp_die('Missing transaction ID.');
        }

        global $wpdb;
        $hub_table     = $wpdb->prefix . 'cfuk_transactions';
        $journal_table = $wpdb->prefix . 'cfuk_journal_entries';
        
        $transaction = $wpdb->get_row($wpdb->prepare("SELECT * FROM $hub_table WHERE id = %d", $tx_id));
        if (!$transaction || $transaction->payment_status === 'PAID') {
            wp_safe_redirect(add_query_arg('status', 'already_paid', $redirect_to));
            exit;
        }

        $wpdb->query('START TRANSACTION');
        $ok = true;

        // 4. Generate payment journal entries
        try {
            $amount = (float) $transaction->amount_ttc;
            $is_sale = $transaction->type === 'SALE';
            // UK nominal codes: 1100 Trade Debtors, 2100 Trade Creditors, 1200 Bank Current Account
            $third_party_account = $is_sale ? '1100' : '2100';
            $description = $is_sale ? 'Customer receipt' : 'Supplier payment';

            $base_entry = [
                'uuid' => wp_generate_uuid4(),
                'date_ecriture' => $payment_date,
                'journal_code' => 'CB',
                'libelle' => sprintf('%s | %s | %s', $description, date_i18n('d/m/Y', strtotime($payment_date)), $transaction->partner_name),
                'piece_ref' => 'PAY-' . $transaction->id,
                'created_by' => get_current_user_id(),
                'source' => 'MANUAL_PAYMENT',
                'transaction_id' => $tx_id,
            ];

            $res1 = $wpdb->insert($journal_table, array_merge($base_entry, [
                'compte_num' => $third_party_account,
                'debit' => $is_sale ? 0 : $amount,
                'credit' => $is_sale ? $amount : 0,
            ]));
            if($res1 === false) $ok = false;
            
            $res2 = $wpdb->insert($journal_table, array_merge($base_entry, [
                'uuid' => wp_generate_uuid4(),
                'compte_num' => '1200',
                'debit' => $is_sale ? $amount : 0,
                'credit' => $is_sale ? 0 : $amount,
            ]));
            if($res2 === false) $ok = false;

        } catch (\Exception $e) {
            $ok = false;
        }

        // 5. Update transaction hub
        if ($ok) {
            $res3 = $wpdb->update(
                $hub_table,
                [
                    'payment_status' => 'PAID',
                    'payment_date'   => $payment_date,
                    'payment_method' => $method,
                ],
                ['id' => $tx_id]
            );
            if ($res3 === false) $ok = false;
        }

        // 6. Finalise transaction
        if ($ok) {
            $wpdb->query('COMMIT');
            wp_safe_redirect(add_query_arg('payment_status', 'success', $redirect_to));
        } else {
            $wpdb->query('ROLLBACK');
            wp_safe_redirect(add_query_arg('payment_status', 'error', $redirect_to));
        }
        exit;
    }
}
