<?php

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

class Stripe_Express_Addons_CF7
{
  public function __construct()
  {
    add_action('wpcf7_init', array($this, 'wpcf7_add_form_tag_stripe_express'), 10, 0);
    /* Tag generator (CF7 v2) */
    add_action('wpcf7_admin_init', array($this, 'wpcf7_add_tag_generator_stripe_express'), 61, 0);
  }

  function wpcf7_add_form_tag_stripe_express()
  {
    wpcf7_add_form_tag(
      'stripe_express_element',
      array($this, 'wpcf7_stripe_express_form_tag_handler'),
      array('name-attr' => true)
    );
  }

  function wpcf7_stripe_express_form_tag_handler($tag)
  {
    global $WP_STRIPE;
    global $wpdb;

    $validation_error = wpcf7_get_validation_error($tag->name);

    $class = wpcf7_form_controls_class($tag->type);

    $class .= ' wpcf7-validates-as-number';

    if ($validation_error) {
      $class .= ' wpcf7-not-valid';
    }

    $atts = array();
    $atts['id'] = $tag->get_option('elementId', 'int', true);
    $item = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->prefix}stripe_express_elements WHERE id = %d", $atts['id']));
    if (empty($item)) {
      return "<span>stripe element not found: {$atts['id']} </span>";
    }

    $uiConfig = array();
    $uiConfig['amountField'] = $tag->get_option('amountField', '', true);
    $uiConfig['quantityField'] = $tag->get_option('quantityField', '', true);
    $atts['uiConfig'] = json_encode($uiConfig);

    return $WP_STRIPE->stripe_express_shortcode($atts);
  }

  function wpcf7_add_tag_generator_stripe_express()
  {
    $tag_generator = WPCF7_TagGenerator::get_instance();
    $tag_generator->add(
      'stripe_express_element',
      __('Stripe Express Element', 'contact-form-7'),
      array($this, 'wpcf7_tag_generator_stripe_express'),
      array('version' => '2')
    );
  }


  function wpcf7_tag_generator_stripe_express($contact_form, $options = '')
  {
    global $wpdb;
    $results = $wpdb->get_results(
      "
        SELECT * 
        FROM {$wpdb->prefix}stripe_express_elements
        WHERE type='ONE_TIME_CF7_REDIRECT'
        ORDER BY id DESC
      ", ARRAY_A
    );
    $options = wp_parse_args( $options, array() );
    $type    = 'stripe_express_element';

    $description = __( 'Generate a form-tag for stripe express element section. For more details, see %s.', 'contact-form-7' );
    $desc_link   = wpcf7_link( 'https://docs.itstripe.com/contact-form-7/', 'stripe-express for CF7' );

    $tgg = new WPCF7_TagGeneratorGenerator( $options['content'] );
    ?>
    <header class="description-box">
      <h3><?php echo esc_html( 'Stripe Express element' ); ?></h3>
      <p><?php echo wp_kses( sprintf( $description, $desc_link ), array( 'a' => array( 'href' => true ) ) ); ?></p>
    </header>
    
    <div class="control-box">
      <?php
    echo '<input type="hidden" data-tag-part="basetype" value="' . esc_attr( $type ) . '">';

    $tgg->print('field_name');
    ?>

      <fieldset>
        <legend><label><?php echo esc_html( 'Element' ); ?></label></legend>
        <select data-tag-part="option" data-tag-option="elementId:" name="elementId" class="oneline option">
          <option value=""><?php echo esc_html( 'Select one' ); ?></option>
          <?php foreach ( $results as $item ) :
            $cfg = json_decode( $item['paymentConfig'] );
            $elementName = isset( $cfg->item->name ) ? $cfg->item->name : sprintf( __( 'Element %d', 'contact-form-7' ), $item['id'] );
          ?>
            <option value="<?php echo esc_attr( $item['id'] ); ?>"><?php echo esc_html( $elementName ); ?></option>
          <?php endforeach; ?>
        </select>
        <?php if ( count( $results ) === 0 ) : ?>
          <div class="notice inline"><p><?php echo esc_html__( 'No element found, please create them first in Stripe Express plugin.', 'contact-form-7' ); ?></p></div>
        <?php endif; ?>
      </fieldset>

      <fieldset>
        <legend><label><?php echo esc_html( 'Amount Field' ); ?></label></legend>
        <input type="text" data-tag-part="option" data-tag-option="amountField:" name="amountField" class="oneline option" />
        <small><?php echo esc_html__( '(The value will be collected from user.)', 'contact-form-7' ); ?></small>
      </fieldset>

      <fieldset>
        <legend><label><?php echo esc_html( 'Quantity Field' ); ?></label></legend>
        <input type="text" data-tag-part="option" data-tag-option="quantityField:" name="quantityField" class="oneline option" />
        <small><?php echo esc_html__( '(The value will be collected from user.)', 'contact-form-7' ); ?></small>
      </fieldset>

      <?php $tgg->print( 'class_attr' ); ?>
    </div>

    <footer class="insert-box">
      <?php $tgg->print( 'insert_box_content' ); ?>
    </footer>
<?php
  }
}

new Stripe_Express_Addons_CF7();
