<?php
/**
 * Template Name: Stripe Payment Page
 *
 * @package WordPress
 * @subpackage Charity
 * @since Charity 1.0
 */
	$wplook_page_header = (isset($wplook_page_meta['wpl_page_header'][0]) && $wplook_page_meta['wpl_page_header'][0] != '') ? $wplook_page_meta['wpl_page_header'][0] : false;
?>
<?php get_header(); ?>

	<div class="main">
		<div class="main-head">
			<div class="main-head-image fullscreener">
				<?php
					if ( $wplook_page_header ) {
						echo '<img class="hide" src="'. esc_url( $wplook_page_header ).'">';
					}?>
			</div><!-- /.main-head-image fullscreener -->

			<div class="main-head-content">
				<div class="grid-container">
					<div class="grid-x grid-margin-x">
						<div class="cell small-12">
							<h1 class="main-title main-title-alt"><?php the_title(); ?></h1><!-- /.main-title main-title-alt -->
							<?php if (ot_get_option('wpl_breadcrumbs_status') == 'on') : ?>
								<ul class="breadcrumbs">
									<?php wplook_breadcrumbs(); ?>
								</ul><!-- /.breadcrumbs -->
							<?php endif; ?>
						</div><!-- /.cell small-12 -->
					</div><!-- /.grid-x grid-margin-x -->
				</div><!-- /.grid-container -->
			</div><!-- /.main-head-content -->
		</div><!-- /.main-head -->
		<div class="main-body">
			<div class="grid-container">
				<div class="grid-x grid-margin-x">
					<div class="cell small-12">
						<div class="content">
							<article id="post-<?php the_ID(); ?>" <?php post_class('post post-single post-event'); ?>>
								<div class="post-body">
									<div class="entry" itemprop="articleBody">
										<?php if ( have_posts() ) while ( have_posts() ) : the_post(); endwhile;?>
										<?php
											if ($_SERVER['REQUEST_METHOD'] == 'POST') {
												$error = false;

												try {
													if (!isset($_POST['stripeToken'])) throw new Exception("The Stripe Token was not generated correctly");

														$cu                        = wp_get_current_user();
														$wplook_customer           = get_user_meta( $cu->ID, '_swp_stripe_customer', true);
													 	$wplook_donation_frequency = ( isset( $_POST["donation_frequency"] ) && !empty( $_POST["donation_frequency"] ) ) ? $_POST["donation_frequency"] : false;
														$wplook_amount_cc          = ( isset( $_POST["amount_cc"] ) && !empty( $_POST["amount_cc"] ) ) ? $_POST["amount_cc"] : false;
														$wplook_cause_id           = ( isset( $_POST["causeid"] ) && !empty( $_POST["causeid"] ) ) ? $_POST["causeid"] : 0;
														$wplook_product_name       = sanitize_title_with_dashes( get_the_title( $wplook_cause_id ) );

														if ($wplook_donation_frequency == 'onetime') {
															$wplook_donation_frequency_meta = 'onetime';
															$wplook_donation_frequency      = 'day';
														} else {
															$wplook_donation_frequency_meta = $wplook_donation_frequency;
														}
														// stripe api love cents
														$wplook_amount_cc         = $wplook_amount_cc * 100;
														$wplook_plan_meta_key     = 'wpl_stripe_'.$wplook_donation_frequency.'_plan_'.$wplook_cause_id.'_'.$wplook_amount_cc;

														// Stripe Plan
														try {
															if ( $first_plan = \Stripe\Plan::retrieve( $wplook_plan_meta_key ) ) { }
														} catch (Exception $e) {
															$first_plan = \Stripe\Plan::create( array(
																"amount"   => $wplook_amount_cc,
																"interval" => $wplook_donation_frequency,
																"product"  => [ "name" => $wplook_product_name, "type" => "service" ],
																"currency" => ot_get_option( 'wpl_curency_code' ),
																"id"       => $wplook_plan_meta_key
																)
															);
														}
														update_post_meta( $wplook_cause_id, $first_plan->id, true );

														try {
															if( $customer_obj = \Stripe\Customer::retrieve( $wplook_customer ) ) {  }
														} catch (Exception $e ) {
															$customer_obj = \Stripe\Customer::create(array(
																"description" => "Customer for " . get_bloginfo('name'),
																"email"       => $cu->user_email,
																'card'        => $_POST['stripeToken'],
																"metadata"    => array (
																	"wpl_username"   => $cu->user_login,
																	"wpl_first_name" => get_user_meta( $cu->ID, 'first_name', true ),
																	"wpl_last_name"  => get_user_meta( $cu->ID, 'last_name', true ),
																),
															));
															//add customer ID to user meta
														}
														update_user_meta( $cu->ID, '_swp_stripe_customer', $customer_obj->id );

														//create subscription object
														$subscription_obj = \Stripe\Subscription::create(
															array(
																'customer' => $customer_obj->id,
																'items'    => [['plan' => $first_plan->id]],
																'metadata' => array (
																	'wpl_sub_frequency' => $wplook_donation_frequency_meta,
																	'wpl_user_id'       => $cu->ID,
																	'wpl_user_name'     => $cu->user_login,
																	'wpl_first_name'    => get_user_meta( $cu->ID, 'first_name', true ),
																	'wpl_last_name'     => get_user_meta( $cu->ID, 'last_name', true ),
																	'wpl_cause_id'      => $wplook_cause_id,
																),
															)
														);

												} catch (Exception $e) {
													$error = $e->getMessage();
												} catch (\Stripe\Error\ApiConnection $e) {
													$error = $e->getMessage();
													// Network problem, perhaps try again.
												} catch (\Stripe\Error\InvalidRequest $e) {
													$error = $e->getMessage();
													// You screwed up in your programming. Shouldn't happen!
												} catch (\Stripe\Error\Api $e) {
													$error = $e->getMessage();
													// Stripe's servers are down!
												} catch (\Stripe\Error\Card $e) {
													$error = $e->getMessage();
													// Card was declined.
												}
												if (!$error) {
													printf( '<h1>%s<h1>', __( 'Thank you! Your donation was received.', 'charity-wpl' ) );
													the_content();
												}
												else {
													printf( '<h1>%s<h1>', __( 'Sorry, the transaction not occurred', 'charity-wpl' ) );
													echo esc_html($error);
												}
											}
										?>
									</div>
								</div>
							</article>
						</div><!-- /.content -->
					</div><!-- /.cell large-12 -->
				</div><!-- /.grid-x grid-margin-x -->
			</div><!-- /.grid-container -->
		</div><!-- /.main-body -->
	</div><!-- /.main -->
<?php get_footer(); ?>
