<?php
if ( ! defined( 'ABSPATH' ) ) { exit; }

if ( ! class_exists('WC_Payment_Gateway') ) { return; }

// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound -- Legacy WooCommerce gateway class kept for backward compatibility.
class WC_Gateway_Asp_Bit extends WC_Payment_Gateway {

    public function __construct(){
        $this->id                 = 'asp_bit';
        $this->method_title       = 'תשלום בביט (פרטי) - SAFE';
        $this->method_description = 'גרסת חירום בטוחה. נטענת רק עם WooCommerce פעיל.';
        $this->has_fields         = true;
        $this->supports           = ['products'];

        $this->init_form_fields();
        $this->init_settings();

        $this->title        = $this->get_option('title', 'תשלום בביט (פרטי)');
        $this->description  = $this->get_option('description', 'שלחו את התשלום בביט והעלו אישור/צילום מסך.');
        $this->bit_phone    = $this->get_option('bit_phone', '0525326377');
        $this->notify_email = $this->get_option('notify_email', get_option('admin_email'));

        add_action('woocommerce_update_options_payment_gateways_' . $this->id, [$this, 'process_admin_options']);
        add_action('woocommerce_checkout_process', [$this, 'validate_fields']);
        add_action('woocommerce_checkout_create_order', [$this, 'save_upload_to_order'], 10, 2);
    }

    public function init_form_fields(){
        $this->form_fields = [
            'enabled' => [
                'title'   => 'הפעלת אמצעי תשלום',
                'label'   => 'אפשר תשלום בביט פרטי',
                'type'    => 'checkbox',
                'default' => 'yes'
            ],
            'title' => [
                'title'   => 'כותרת בקופה',
                'type'    => 'text',
                'default' => 'תשלום בביט (פרטי)'
            ],
            'description' => [
                'title'   => 'תיאור',
                'type'    => 'textarea',
                'default' => 'שלחו את התשלום בביט והעלו אישור/צילום מסך.'
            ],
            'bit_phone' => [
                'title'   => 'מספר ביט לקבלת תשלום',
                'type'    => 'text',
                'default' => '0525326377'
            ],
            'notify_email' => [
                'title'   => 'אימייל להודעה על תשלום',
                'type'    => 'email',
                'default' => ''
            ],
        ];
    }

    public function payment_fields(){
        echo '<div dir="rtl" class="asp-bit-fields">';
        echo wp_kses_post(wpautop(esc_html($this->description)));
        echo '<div class="asp-bit-note"><strong>מספר ביט לתשלום:</strong> <code>' . esc_html($this->bit_phone) . '</code></div>';
        echo '<label>העלאת צילום מסך/אישור תשלום</label>';
        echo '<input type="file" name="asp_bit_receipt" accept="image/*,application/pdf" required />';
        echo '</div>';
    }

    public function validate_fields(){
        $receipt = $this->receipt_file();
        if (empty($receipt['name'])) {
            wc_add_notice('יש להעלות צילום מסך/אישור תשלום מביט.', 'error');
        }
    }

    public function save_upload_to_order($order, $data){
        $receipt = $this->receipt_file();
        if (!empty($receipt['name'])) {
            $uploaded = asp_bit_handle_upload($receipt);
            if ($uploaded && !isset($uploaded['error'])) {
                $order->update_meta_data('_asp_bit_receipt_url', $uploaded['url']);
            } else {
                wc_add_notice('שגיאה בהעלאת קובץ.', 'error');
            }
        }
    }

    private function receipt_file(): array {
        // phpcs:disable WordPress.Security.NonceVerification.Missing,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- WooCommerce validates checkout submission; this method only normalizes the uploaded receipt.
        if (empty($_FILES['asp_bit_receipt']) || !is_array($_FILES['asp_bit_receipt'])) {
            return [];
        }

        $file = wp_unslash($_FILES['asp_bit_receipt']);
        // phpcs:enable WordPress.Security.NonceVerification.Missing,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
        return [
            'name' => sanitize_file_name((string) ($file['name'] ?? '')),
            'type' => sanitize_mime_type((string) ($file['type'] ?? '')),
            'tmp_name' => isset($file['tmp_name']) ? (string) $file['tmp_name'] : '',
            'error' => isset($file['error']) ? absint($file['error']) : 0,
            'size' => isset($file['size']) ? absint($file['size']) : 0,
        ];
    }

    public function process_payment($order_id){
        $order = function_exists('wc_get_order') ? wc_get_order($order_id) : null;
        if (!$order) {
            wc_add_notice('שגיאה בעיבוד ההזמנה.', 'error');
            return ['result' => 'fail'];
        }
        $order->update_status('paycal-bit-pending', 'ממתין לאישור תשלום בביט.');
        if (function_exists('wc_reduce_stock_levels')) wc_reduce_stock_levels($order_id);
        if (function_exists('WC') && WC()->cart) WC()->cart->empty_cart();
        $admin_email = $this->notify_email ?: get_option('admin_email');
        if (function_exists('wp_mail')) {
            @wp_mail($admin_email, 'התקבלה הזמנה (Bit) #' . $order->get_order_number(), 'בדקי את צילום המסך ואשרי בממשק ההזמנות.');
        }
        return ['result' => 'success', 'redirect' => $this->get_return_url($order)];
    }
}
