<?php
/**
 * Cash on Delivery (COD) Gateway.
 *
 * Offline payment — no external API calls. The order is immediately
 * moved to the configured post-COD status (default: 'on_hold') to signal
 * the admin that the physical payment is pending collection.
 *
 * SETTINGS FIELDS
 * ---------------
 *   order_status — Status to set after checkout (handle). Default: 'on_hold'
 *
 * @package TitanCart\Modules\Payments\Gateways
 */

namespace TitanCart\Modules\Payments\Gateways;

use TitanCart\Modules\Payments\AbstractGateway;

defined( 'ABSPATH' ) || exit;

class CodGateway extends AbstractGateway {

    const SLUG = 'cod';

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

    public function get_label(): string {
        return __( 'Cash on Delivery', 'titancart-lite' );
    }

    public function get_settings_fields(): array {
        return [
            [
                'key'     => 'order_status',
                'label'   => __( 'Order Status After Checkout', 'titancart-lite' ),
                'type'    => 'select',
                'default' => 'on_hold',
                'options' => [
                    'on_hold'    => __( 'On Hold', 'titancart-lite' ),
                    'processing' => __( 'Processing', 'titancart-lite' ),
                ],
                'hint'    => __( '"On Hold" waits for manual payment confirmation. "Processing" starts fulfillment immediately.', 'titancart-lite' ),
            ],
        ];
    }

    /**
     * COD requires no external payment — just advance the order status.
     *
     * {@inheritdoc}
     */
    public function process_payment( int $order_id, array $order, array $settings ): array {
        $post_status = $this->setting( $settings, 'order_status', 'on_hold' );

        // Log a zero-value transaction for consistency / audit trail.
        $this->log_transaction(
            $order_id,
            (int) ( $order['payment_method_id'] ?? 0 ),
            self::SLUG,
            'cod-' . $order_id,
            (float) ( $order['total'] ?? 0 ),
            $order['currency'] ?? 'USD',
            'charge',
            'pending',      // COD payment is physically pending collection.
            [ 'note' => 'Cash on delivery — awaiting collection.' ]
        );

        // Advance the order to the configured post-COD status.
        $this->set_order_status(
            $order_id,
            $post_status,
            __( 'Order placed via Cash on Delivery.', 'titancart-lite' ),
            true    // Notify customer of the status change.
        );

        return $this->success_result(
            'cod-' . $order_id,
            __( 'Your order has been placed and is awaiting payment on delivery.', 'titancart-lite' )
        );
    }

    /**
     * COD refunds are manual (cash returned to customer).
     * We log the refund record and update the order; no API call is made.
     *
     * {@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,
            'cod-refund-' . $order_id . '-' . time(),
            $amount,
            $order_row['currency'] ?? 'USD',
            'refund',
            'completed',
            [ 'note' => 'Manual COD refund recorded.' ]
        );

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

        return [
            'success'   => true,
            'refund_id' => 'cod-refund-' . $order_id,
            'message'   => __( 'COD refund recorded. Please ensure cash is returned to the customer.', 'titancart-lite' ),
        ];
    }
}
