<?php
require_once(FCPATH . 'vendor/autoload.php');

defined('BASEPATH') OR exit('No direct script access allowed');

class Stripe extends MY_Controller1 {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see https://codeigniter.com/user_guide/general/urls.html
	 */
	public function __construct()
	{
		parent::__construct();
		\Stripe\Stripe::setApiKey($this->config->item('stripe')['secret_key']);
	}

	public function index()
	{
		echo "<h1>Access Denied</h1>";
		exit;
	}

	public function config()
	{
		echo json_encode(['publicKey' => $this->config->item('stripe')['publishable_key']]);
	}

	public function create_checkout_session()
	{
		$request = $this->input->get();
		if (! array_key_exists('access_token', $request)) {
			echo json_encode([]);
			return;
		}
		$token = $request['access_token'];
		$this->session->set_userdata('access_token', $token);
		$this->load->model('Applicant_model', 'applicant');
		$applicant = $this->applicant->token_search($token);
		if (! $applicant) {
			echo json_encode([]);
			return;
		}
		$this->load->model('Webinar_model', 'webinar');
		$webinar = $this->webinar->detail($applicant['webinar_id']);
		if (! $webinar) {
			echo json_encode([]);
			return;
		}
		if ($webinar['course_id'] == 0) {
			echo json_encode([]);
			return;
		}
		$this->load->model('Course_Model', 'course');
		$course = $this->course->detail($webinar['course_id']);
		$checkout_session = \Stripe\Checkout\Session::create([
			'success_url' => base_url() . 'selling/success?session_id={CHECKOUT_SESSION_ID}',
			'cancel_url' => base_url() . 'selling/fail',
			'payment_method_types' => ['card'],
			'mode' => 'payment',
			'line_items' => [[
				'price_data' => [
					'currency' => 'hkd',
					'product_data' => [
						'name' => $course['name'],
					],
					'unit_amount' => $webinar['discounted_price'] * 100,
				],
				'quantity' => 1,
			]],
		]);

		echo json_encode(['sessionId' => $checkout_session['id']]);
	}

}
