<?php
/**
 * CheckGateway — offline payment by cheque/check.
 *
 * @package TitanCart\Modules\Payments\Gateways
 */

namespace TitanCart\Modules\Payments\Gateways;

use TitanCart\Modules\Payments\AbstractGateway;

defined( 'ABSPATH' ) || exit;

class CheckGateway extends AbstractGateway {

    const SLUG = 'check';

    // ══════════════════════════════════════════════════════════════════════════
    // INTERFACE IMPLEMENTATION
    // ══════════════════════════════════════════════════════════════════════════

    public function get_label(): string {
        return __( 'Pay by Check', 'titancart-lite' );
    }

    public function get_settings_fields(): array {
        return [
            [
                'key'   => 'payee_name',
                'label' => __( 'Make Checks Payable To', 'titancart-lite' ),
                'type'  => 'text',
                'hint'  => __( 'The name printed on the "Pay to the order of" line. Usually your business name.', 'titancart-lite' ),
            ],
            [
                'key'   => 'mailing_address',
                'label' => __( 'Mailing Address', 'titancart-lite' ),
                'type'  => 'textarea',
                'hint'  => __( 'Where customers should mail their check. Include full address with zip code.', 'titancart-lite' ),
            ],
            [
                'key'   => 'instructions',
                'label' => __( 'Additional Instructions', 'titancart-lite' ),
                'type'  => 'textarea',
                'hint'  => __( 'e.g. "Write your order number on the memo line. Orders ship after check clears (5–7 business days)."', 'titancart-lite' ),
            ],
        ];
    }

    /**
     * Check payments are always available.
     * Order is placed in 'open' (awaiting check receipt) status.
     *
     * {@inheritdoc}
     */
    public function process_payment( int $order_id, array $order, array $settings ): array {
        $this->log_transaction(
            $order_id,
            (int) ( $order['payment_method_id'] ?? 0 ),
            self::SLUG,
            'chk-' . $order_id,
            (float) ( $order['total'] ?? 0 ),
            $order['currency'] ?? 'USD',
            'charge',
            'pending',
            [ 'note' => 'Check payment — awaiting receipt.' ]
        );

        $this->set_order_status(
            $order_id,
            'open',
            __( 'Order placed via Check. Awaiting receipt of check.', 'titancart-lite' ),
            true
        );

        return $this->success_result(
            'chk-' . $order_id,
            __( 'Thank you. Please mail your check to the address below. Your order will be processed once your check is received and cleared.', 'titancart-lite' ),
            [ 'instructions' => $this->build_instructions( $settings ) ]
        );
    }

    /**
     * Check refunds are manual — record and update status.
     *
     * {@inheritdoc}
     */
    public function refund( int $order_id, string $transaction_id, float $amount, array $settings ): array {
        $order_row = $this->db->getRow(
            "SELECT * FROM {$this->db->table('orders')} WHERE id = ?i",
            $order_id
        );

        $this->log_transaction(
            $order_id,
            (int) ( $order_row['payment_method_id'] ?? 0 ),
            self::SLUG,
            'chk-refund-' . $order_id . '-' . time(),
            $amount,
            $order_row['currency'] ?? 'USD',
            'refund',
            'completed',
            [ 'note' => 'Manual check refund recorded.' ]
        );

        $this->set_order_status(
            $order_id,
            'refunded',
            __( 'Check refund recorded manually.', 'titancart-lite' ),
            true
        );

        return [
            'success'   => true,
            'refund_id' => 'chk-refund-' . $order_id,
            'message'   => __( 'Refund recorded. Please issue a replacement check to the customer.', 'titancart-lite' ),
        ];
    }

    // ══════════════════════════════════════════════════════════════════════════
    // POST-CHECKOUT INSTRUCTIONS
    // ══════════════════════════════════════════════════════════════════════════

    /**
     * Render check-payment instructions on order-received + account order-detail
     * pages. Delegates to the existing build_instructions() helper so the
     * checkout response and post-checkout pages emit identical markup.
     *
     * {@inheritdoc}
     */
    public function render_post_checkout_instructions( array $order, array $settings ): string {
        return $this->build_instructions( $settings );
    }

    // ══════════════════════════════════════════════════════════════════════════
    // PRIVATE HELPERS
    // ══════════════════════════════════════════════════════════════════════════

    /**
     * Build mailing instructions HTML from settings.
     *
     * Uses semantic <dl> definition-list markup matching BankTransferGateway,
     * so labels (Make checks payable to, Mail to) pair to values in a
     * screen-reader-friendly structure with consistent visual rhythm.
     *
     * @param  array $settings Decoded settings array.
     * @return string HTML snippet.
     */
    private function build_instructions( array $settings ): string {
        $rows = [];

        if ( ! empty( $settings['payee_name'] ) ) {
            $rows[] = [
                'label' => __( 'Make checks payable to', 'titancart-lite' ),
                'value' => esc_html( $settings['payee_name'] ),
            ];
        }

        if ( ! empty( $settings['mailing_address'] ) ) {
            $rows[] = [
                'label' => __( 'Mail to', 'titancart-lite' ),
                // nl2br on escaped multi-line addresses; pre-escaped so the
                // <dd> append below doesn't need additional escaping.
                'value' => nl2br( esc_html( $settings['mailing_address'] ) ),
            ];
        }

        $html = '<div class="tc-check-payment-details">';

        if ( $rows ) {
            $html .= '<dl class="tc-payment-instructions__dl">';
            foreach ( $rows as $row ) {
                $html .= '<dt class="tc-payment-instructions__label">'
                       . esc_html( $row['label'] )
                       . '</dt>';
                // $row['value'] is already escaped above (esc_html / nl2br on esc_html).
                $html .= '<dd class="tc-payment-instructions__value">'
                       . $row['value']
                       . '</dd>';
            }
            $html .= '</dl>';
        }

        if ( ! empty( $settings['instructions'] ) ) {
            $html .= '<p class="tc-payment-instructions__notes">'
                   . wp_kses_post( nl2br( $settings['instructions'] ) )
                   . '</p>';
        }

        $html .= '<p class="tc-payment-instructions__note">'
               . esc_html__( 'Your order will be processed once your check is received and cleared.', 'titancart-lite' )
               . '</p></div>';

        return $html;
    }
}
