<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use Kreait\Firebase\Exception\FirebaseException;
class Site extends CI_Controller {
	public function __construct() {
        parent::__construct();
		$this->load->helper('url');
		$this->load->library('session');
		$this->load->model('common');
    }
    public function index()
	{
		$this->template->template_render('index');
	}

	public function orders()
	{
		if (empty($this->session->userdata('session_data'))) {
			redirect(base_url('site/login'));
			exit;
		}
		$userId = $this->session->userdata('session_data')['userId'];

		$orders = $this->common->readdatafromcollectionwhereclause('Orders', 'userId', '=', $userId);
		$myOrders = array();
		foreach($orders as $key => $order) {
			$myOrders[$key] = $order;
			$orderProducts = $order['products'];
			$orderedProducts = array();
			foreach($orderProducts as $id => $product){
				$tproduct = $this->common->readdatadocument('Product', $product['productId']);
				$orderedProducts[$id] = $tproduct;
				$orderedProducts[$id]['orderPrice'] = $product['price'];
				$orderedProducts[$id]['orderQuantity'] = $product['quantity'];
			}

			$myOrders[$key]['orderedProducts'] = $orderedProducts;
		}

		// print "<pre>";
		// print_r($myOrders);
		// print "</pre>";
		// die;
		
		$data['orders'] = $myOrders;
		$this->template->template_render('orders', $data);
	}

	public function login()
	{
		if (!empty($this->session->userdata('session_data'))) {
			redirect(base_url('site/products'));
			exit;
		}
		$this->template->template_render('login');
	}

	public function dologin(){
		$email = $this->input->post("email");
		$password = $this->input->post("password");

		$firebase = $this->firebase->init();

		$auth = $firebase->createAuth();

		try {
			$signInResult = $auth->signInWithEmailAndPassword($email, $password);
		} catch (FirebaseException $e) {
			$this->session->set_flashdata('warningmessage', 'Invalid email and/or password !');
			redirect(base_url('site/login'));
		}

		$my = $signInResult->data();
		
		
		$user = $this->common->readdatadocument("WebUsers", $my['localId']);
		

		if (!empty($my["idToken"])) {

			$session_data = array(
				'userId' => $my["localId"],
				'name' => $user["name"],
				'email' => $user["email"],
				'firebaseToken' => $my["idToken"]
			);
			$this->session->set_userdata('session_data', $session_data);

			if(isset($this->session->redirpage)){
				redirect(base_url('site/checkout'));
			}else{

				redirect(base_url('site/products'));
			}

		} else {
			$this->session->set_flashdata('warningmessage', 'Invalid email and/or password !');
			redirect(base_url('site/login'));
		}
	}

	public function logout()
	{
		// Removing session data
		$sess_array = array('userId', 'email', 'name', 'firebaseToken');
		$this->session->unset_userdata('session_data', $sess_array);
		$this->session->set_flashdata('successmessage', 'Successfully Logged out !');
		redirect(base_url('site/login'));
	}

	public function signup()
	{
		if (!empty($this->session->userdata('session_data'))) {
			redirect(base_url('site/products'));
			exit;
		}
		$this->template->template_render('signup');
	}

	public function dosignup()
	{
		$post = $this->input->post();
		$user = $this->common->readdatafromcollectionwhereclause('WebUsers', 'email', '=', $post['email']);
		if(count($user) > 0){
			$this->session->set_flashdata('warningmessage', 'Email already exists, please login.');
			redirect(base_url('site/login'));
			exit;
		}
		$firebase = $this->firebase->init();
		$auth = $firebase->createAuth();
		$userProperties = [
			'email' => $post['email'],
			'password' => $post['password'],
			'displayName' => $post['name'],
			'disabled' => false
		];
		
		$auth->createUser($userProperties);

		$signInResult = $auth->signInWithEmailAndPassword($post['email'], $post['password']);
		$my = $signInResult->data();

		if (!empty($my["idToken"])) {
			$data = [
				'name' => $post['name'],
				'email' => $post['email'],
				'password' => $post['password'],
				'isActive' => true,
				'userRole' => 'webuser',
				'createdDate' => time()
			];
			$this->common->adddatamodel('WebUsers', $my["localId"], $data);
			$session_data = array(
				'userId' => $my["localId"],
				'name' => $post['name'],
				'email' => $post["email"],
				'firebaseToken' => $my["idToken"]
			);
			$this->session->set_userdata('session_data', $session_data);
			$this->session->set_flashdata('successmessage', 'Successfully signed up and logged in.');
			if(isset($this->session->redirpage)){
				redirect(base_url('site/checkout'));
			}else{

				redirect(base_url('site/products'));
			}
		}
	}
	
	public function products($page=null,$catid=null,$subcatid=null)
	{
		// var_dump($_SESSION['cart']);die;
		if(!$page){
			$page = 1;
		}
		$data['catid'] = $catid;
		$data['subcatid'] = $subcatid;
		
		if($catid && $subcatid){
			$data['products'] = $this->common->readdatafromcollectionbetween("Product","category","=",(string)$catid,"subcategory","=",(string)$subcatid);
		}elseif($catid){
			$data['products'] = $this->common->readdatafromcollectionbetween("Product","category","=",(string)$catid);
		}else{
			$data['products'] = $this->common->readdatafromcollectionbetween("Product");

		}
		$categories = $this->common->readdatafromcollectionwhereclause("Category");
		foreach($categories as $id => $category){
			$subcategories = $this->common->readdatafromcollectionwhereclause("Subcategory","category","=",(string)$id);
			$categories[$id]['subcategories'] = $subcategories;
		}
		$data['categories'] = $categories;

		$perPage = 2;
		$totalProducts = count($data['products']);
		$totalPages = ceil($totalProducts/$perPage);
		$totalPages = $totalPages > 1 ? $totalPages : 1;
		$currentPage = isset($page) ? $page : 1;
		$currentPage = ($totalProducts > 0) ? min($totalPages, $currentPage) : 1;
		$offset = $currentPage * $perPage - $perPage;
		// echo($start);die;
		$data['products'] = array_slice($data['products'], $offset, $perPage, true);
		$data['page'] = $page;
		$data['totalPages'] = $totalPages;

		$this->template->template_render('products', $data);
	}
	
	public function productdetails($productId=null)
	{
		if(!$productId){
			redirect(base_url('site/cart'));
			exit;
		}
		$data['productId'] = $productId;
		$data['product'] = $this->common->readdatadocument('Product', $productId);
		$this->template->template_render('productDetails', $data);
	}

	public function searchForId($id, $array) {
	foreach ($array as $key => $val) {
		if ($val['productId'] === $id) {
			return $key;
		}
	}
	return null;
	}

	

	public function test(){
		$this->template->template_render('test');
	}

	public function process(){
		$message = '';
		$success = '';
		if(!empty($_POST['stripeToken'])){
			
			
			\Stripe\Stripe::setApiKey($this->config->item('stripe_secret'));    
			
			try {
				
				$userId = $this->session->userdata('session_data')['userId'];
				$items = $this->session->userdata('cart');
				$cartItems = array();
				$products = array();

				foreach($items as $key => $item) {
					$cartItems[$key] =  $this->common->readdatadocument('Product', $item['productId']);
					$cartItems[$key]['quantity'] = $item['quantity'];
					$cartItems[$key]['productId'] = $item['productId'];
					
				}

				$totalPrice = 0;
				$shippingCost = 0;

				foreach($cartItems as $key => $item) {

					$itemPrice = (int)$item['price'] * (int)$item['quantity'];
					$totalPrice = $totalPrice + $itemPrice;
					$products[] = [
						"productId" => $item['productId'],
						"quantity" => (int)$item['quantity'],
						"price" => (int)$item['price'],
					];
					$shippingCost = 10;
				}
				$totalPrice = $totalPrice + $shippingCost;
				
				$timestamp = time();
				$orderId = $timestamp.'-'.mt_rand(1, 999);

				
				//charge a credit or a debit card
				$charge = \Stripe\Charge::create([
					'amount'      => $totalPrice * 100,
					'currency'    => 'usd',
					'source'      => $this->input->post('stripeToken'),
					'description' => 'Yahlove payment',
					'metadata'    => [
						'order_id' => $orderId,
					],
				]);
				$response = $charge->jsonSerialize();
				if($response["amount_refunded"] == 0 && empty($response["failure_code"]) && $response['paid'] == 1 && $response["captured"] == 1 && $response['status'] == 'succeeded'){
					
					$orderData = [
						"orderId" => $orderId,
						"userId" => $userId,
						"totalAmount" => $totalPrice,
						"products" => $products,
						"paymentStatus" => 'paid',
						"orderStatus" => 'pending',
						"orderDate" => time(),
						'shippingAddress' => [
							"address" => $_POST['address'],
							"city" => $_POST['city'],
							"state" => $_POST['state'],
							"zip" => $_POST['zip'],
							"country" => $_POST['country'],
							"email" => $_POST['email'],
						]
					];
					$this->common->adddatamodel('Orders', $orderId, $orderData);
					$this->session->unset_userdata('cart');
					$success = 'paid';
				}
			} catch (\Stripe\Error\Card $e) {
				
				$body = $e->getJsonBody();
				$err = $body['error'];
				$message = $err['message'];
			} catch (\Stripe\Error\RateLimit $e) {
				// Too many requests made to the API too quickly
				$message = $e->getMessage();
			} catch (\Stripe\Error\InvalidRequest $e) {
				// Invalid parameters were supplied to Stripe's API
				$message = $e->getMessage();
			} catch (\Stripe\Error\Authentication $e) {
				// Authentication with Stripe's API failed
				// (maybe you changed API keys recently)
				$message = $e->getMessage();
			} catch (\Stripe\Error\ApiConnection $e) {
				// Network communication with Stripe failed
				$message = $e->getMessage();
			} catch (\Stripe\Error\Base $e) {
				// Display a very generic error to the user, and maybe send
				// yourself an email
				$message = $e->getMessage();
			} catch (Exception $e) {
				// Something else happened, completely unrelated to Stripe
				$message = $e->getMessage();
			}
					
		} else{
			$message = "No token";
		}
		$_SESSION['error'] = $message;
		
		if($success) {
			redirect(base_url('site/paid'));
			exit;
		}else{
			redirect(base_url('site/failed'));
			exit;
		}
	}

	public function paid() {
		$this->template->template_render('paid');
	}
	public function failed() {
		$this->template->template_render('failed');
	}

	public function checkout(){
		if (empty($this->session->userdata('session_data'))) {
			$this->session->set_userdata('redirpage', 'cart');
			redirect(base_url('site/login'));
			exit;
		}
		if(isset($_SESSION['error'])){
			unset($_SESSION['error']);
		}
		// $userId = $this->session->userdata('session_data')['userId'];
		$items = $this->session->userdata('cart');
		$cartItems = array();

		foreach($items as $key => $item) {
			$cartItems[$key] =  $this->common->readdatadocument('Product', $item['productId']);
			$cartItems[$key]['quantity'] = $item['quantity'];
			$cartItems[$key]['productId'] = $item['productId'];
		}

		$totalPrice = 0;
		$shippingCost = 0;

		foreach($cartItems as $key => $item) {

			$itemPrice = (int)$item['price'] * (int)$item['quantity'];
			$totalPrice = $totalPrice + $itemPrice;
			$shippingCost = 10;
		}
		$totalPrice = $totalPrice + $shippingCost;
		$data['totalPrice'] = $totalPrice;

		$this->template->template_render('checkout', $data);
	}

	public function removefromcart($id){
		
		unset($_SESSION['cart'][$id]);

		redirect(base_url('site/cart'));
		exit;
	}

	public function clearcart(){
		
		unset($_SESSION['cart']);

		redirect(base_url('site/cart'));
		exit;
	}

	public function updatecart(){
		
		$items = $this->input->post('quantity');

		foreach($items as $key => $item){
			$_SESSION['cart'][$key]['quantity'] = $item;
		}

		redirect(base_url('site/cart'));
		exit;
	}

	public function addtocart($productId=null, $qty=1){
		if(!$productId){
			redirect(base_url('site/cart'));
			exit;
		}
		

		$data = $this->session->userdata('cart');
		
		$searchId = $this->searchForId($productId, $data);
		
		if($searchId !== null){
			$oldQty = $data[$searchId]['quantity'];
			$newQty = (int)$oldQty + (int)$qty;
			$data[$searchId]['quantity'] = $newQty;
		}else{
			$cartData['productId'] = $productId;
			$cartData['quantity'] = (int)$qty;

			$data[] = $cartData;
		}
		$this->session->set_userdata('cart', $data);
		

		// var_dump($this->session->userdata('cart'));die;
		
		redirect(base_url('site/products'));
		exit;
	}

	public function cart(){
		
		$items = $this->session->userdata('cart');
		$cartItems = array();

		foreach($items as $key => $item) {
			$cartItems[$key] =  $this->common->readdatadocument('Product', $item['productId']);
			$cartItems[$key]['quantity'] = $item['quantity'];
		}
		// print "<pre>";
		// print_r($cartItems);
		// print "</pre>";
		// die;
		$data['cartItems'] = $cartItems;
		$this->template->template_render('cart', $data);
	}

	
	
}
?>