<?php

namespace Pixeldev\SquareWooSync\Payments;

use Pixeldev\SquareWooSync\Security\SquareTokenManager;

if (!defined('ABSPATH')) {
  exit;
}

class WC_SquareSync_CashApp_Gateway extends \WC_Payment_Gateway
{
  private $square_application_id;
  private $square_url;
  private $location_id;
  public $page = null;

  public function __construct()
  {
    $settings = get_option('square-woo-sync_settings', []);

    $this->id = 'squaresync_cashapp';
    $this->icon = '';
    $this->has_fields = true;
    $this->method_title = 'Cash App Pay by SquareSync for Woo';
    $this->method_description = 'Accept payments using Cash App Pay via Square.';

    // Cash App Pay supports these features
    $this->supports = [
      'products',
      'refunds',
    ];

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

    $this->title = $this->get_option('title');
    $this->description = $this->get_option('description');
    $this->enabled = $this->get_option('enabled');
    $this->location_id = $settings['location'] ?? '';

    $hasStoredToken = (bool) SquareTokenManager::get();
    $isSandbox = isset($settings['environment']) && $settings['environment'] === 'sandbox';

    if ($hasStoredToken) {
      $this->square_application_id = $isSandbox
        ? 'sandbox-sq0idb-LMyDEf_itd9_DZukD9RGCQ'
        : 'sq0idp-HD7Og08_uCPjxkaEgoG40Q';
    }

    add_action('woocommerce_update_options_payment_gateways_' . $this->id, [$this, 'process_admin_options']);
    add_action('wp_enqueue_scripts', [$this, 'payment_scripts']);
  }

  public function init_form_fields()
  {
    $this->form_fields = [
      'enabled' => [
        'title' => 'Enable/Disable',
        'type' => 'checkbox',
        'label' => 'Enable Cash App Pay',
        'default' => 'no',
      ],
      'title' => [
        'title' => 'Title',
        'type' => 'text',
        'description' => 'Title that the user sees during checkout.',
        'default' => 'Cash App Pay',
        'desc_tip' => true,
      ],
      'description' => [
        'title' => 'Description',
        'type' => 'textarea',
        'description' => 'Description that the user sees during checkout.',
        'default' => 'Pay securely using Cash App Pay.',
      ],
    ];
  }

  public function payment_scripts()
  {
    // Only load scripts on classic checkout pages (not block-based checkout)
    if (!is_checkout() && !is_checkout_pay_page()) {
      return;
    }

    // Check if this is a block-based checkout - if so, scripts are handled by blocks
    if (function_exists('has_block') && (has_block('woocommerce/checkout') || has_block('woocommerce/cart'))) {
      return;
    }

    if ('no' === $this->enabled) {
      return;
    }

    $settings = get_option('square-woo-sync_settings', []);
    $hasStoredToken = (bool) SquareTokenManager::get();

    if (!$hasStoredToken) {
      return;
    }

    // Enqueue Square Web Payments SDK
    $is_sandbox = isset($settings['environment']) && $settings['environment'] === 'sandbox';
    $square_sdk_url = $is_sandbox
      ? 'https://sandbox.web.squarecdn.com/v1/square.js'
      : 'https://web.squarecdn.com/v1/square.js';

    wp_enqueue_script('wc-square-payments-sdk', $square_sdk_url, array(), null, true);

    // Enqueue Cash App Pay classic checkout script
    $script_path = SQUAREWOOSYNC_URL . '/build/blocks/cashapp-classic.js';
    $script_asset_path = SQUAREWOOSYNC_PATH . '/build/blocks/cashapp-classic.asset.php';
    $script_asset = file_exists($script_asset_path) ? require($script_asset_path) : array('dependencies' => array(), 'version' => SQUAREWOOSYNC_VERSION);

    wp_enqueue_script(
      'squaresync-cashapp-classic',
      $script_path,
      array_merge(array('jquery', 'wc-square-payments-sdk'), $script_asset['dependencies']),
      $script_asset['version'],
      true
    );

    // Localize script with settings
    wp_localize_script('squaresync-cashapp-classic', 'squareCashAppSettings', array(
      'applicationId' => $this->square_application_id,
      'locationId' => $this->location_id,
      'ajaxUrl' => admin_url('admin-ajax.php'),
      'nonce' => wp_create_nonce('wc-square-cashapp-payment'),
    ));
  }

  public function payment_fields()
  {
    if ($this->description) {
      echo wpautop(wptexturize($this->description));
    }

    // Check if this is block-based checkout
    if (function_exists('has_block') && (has_block('woocommerce/checkout') || has_block('woocommerce/cart'))) {
      // Blocks checkout - the button is rendered by the React component
      return;
    }

    // Classic checkout - render Cash App Pay button container
    ?>
    <div id="cash-app-pay-instructions" style="padding: 10px; background: #f0f0f0; border-radius: 4px; margin: 10px 0;">
      <p><?php _e('Loading Cash App Pay button...', 'squarewoosync'); ?></p>
    </div>

    <div id="cash-app-pay-button-container" style="min-height: 48px; margin: 10px 0; display: none;"></div>

    <input type="hidden" id="squaresync_cashapp_token" name="squaresync_cashapp_token" value="">
    <input type="hidden" id="squaresync_cashapp_verification_token" name="squaresync_cashapp_verification_token" value="">
    <?php
  }

  public function process_payment($order_id)
  {
    error_log("[SquareSync CashApp Gateway] Starting payment processing for Order #{$order_id}");

    try {
      $order = wc_get_order($order_id);

      // Get the Cash App payment token from the POST data
      $cashapp_token = isset($_POST['squaresync_cashapp_token']) ? sanitize_text_field($_POST['squaresync_cashapp_token']) : '';
      $verification_token = isset($_POST['squaresync_cashapp_verification_token']) ? sanitize_text_field($_POST['squaresync_cashapp_verification_token']) : '';

      if (empty($cashapp_token)) {
        wc_add_notice(__('Cash App Pay token is missing. Please try again.', 'squarewoosync'), 'error');
        return ['result' => 'failure'];
      }

      // Get the main gateway instance to reuse its payment processing logic
      $gateways = WC()->payment_gateways->payment_gateways();
      $main_gateway = isset($gateways['squaresync_credit']) ? $gateways['squaresync_credit'] : null;

      if (!$main_gateway) {
        error_log("[SquareSync CashApp Gateway] Main gateway not found");
        wc_add_notice(__('Payment processing error. Please try again.', 'squarewoosync'), 'error');
        return ['result' => 'failure'];
      }

      // Set the POST data for the main gateway to process
      // The main gateway expects these specific POST keys
      $_POST['square_payment_token'] = $cashapp_token;
      $_POST['square_verification_token'] = $verification_token;
      $_POST['wc-squaresync_credit-payment-nonce'] = $cashapp_token;
      $_POST['wc-squaresync_credit-buyer-verification-token'] = $verification_token;

      // Use the main gateway's payment processing logic
      $result = $main_gateway->process_payment($order_id);

      return $result;
    } catch (\Exception $e) {
      error_log("[SquareSync CashApp Gateway] Error: " . $e->getMessage());
      wc_add_notice(__('An error occurred processing your payment. Please try again.', 'squarewoosync'), 'error');
      return ['result' => 'failure'];
    }
  }

  public function process_refund($order_id, $amount = null, $reason = '')
  {
    // Get the main gateway instance to handle refunds
    $gateways = WC()->payment_gateways->payment_gateways();
    $main_gateway = isset($gateways['squaresync_credit']) ? $gateways['squaresync_credit'] : null;

    if (!$main_gateway || !method_exists($main_gateway, 'process_refund')) {
      return new \WP_Error('error', __('Refund processing not available.', 'squarewoosync'));
    }

    return $main_gateway->process_refund($order_id, $amount, $reason);
  }
}
