<?php namespace App\Http\Controllers\user;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;
use Auth;
use App\Models\user\UserModel;
use App\Models\teamstore\TeamStoreModel;
use App\Models\MainModel;
use Illuminate\Support\Facades\Hash;
use Paypal;
use View;
use Mail;

class UserController extends Controller {
	
	// private $_apiContext;

    // public function __construct()
    // {
    //     $this->_apiContext = PayPal::ApiContext(
    //         config('services.paypal.client_id'),
    //         config('services.paypal.secret'));


    //     $this->_apiContext->setConfig(array(
    //         'mode' => 'sandbox',
    //         'service.EndPoint' => 'https://api.sandbox.paypal.com',
    //         'http.ConnectionTimeOut' => 30,
    //         'log.LogEnabled' => true,
    //         'log.FileName' => storage_path('logs/paypal.log'),
    //         'log.LogLevel' => 'FINE'
	// 	));
		

	// 	// view()->share('datas', [1, 2, 3]);

	// }

	//
	public function index(){

		return view('user-layouts.index');
	
	}

	public function addressBook(){
		$m 		= new UserModel;
		$userId = Auth::user()->id;
		
		$array_address_book 	= 	$m->selectAddresBook('UserId', $userId);

		return view('user-layouts.address_book')
									->with('array_address_book', $array_address_book);
		
	}

	public function createAddressBook(){

		return view('user-layouts.create_address_book');
		
	}

	public function saveAddressBook(Request $request){
		$post 	=	$request->all();
		$m 		= new UserModel;

		$userId = Auth::user()->id;
		
		$data = array(
			'UserId'			=> $userId,
			'Fullname'			=> $post['fullname'],
			'ContactNumber'		=> $post['mobilenumber'],
			'OtherNotes' 	 	=> $post['othernotes'],
			'Address' 			=> $post['address'],
			'State'	 			=> $post['state'],
			'City' 		 		=> $post['city'],
			'ZipCode'     		=> $post['zipcode']
		);
		
		echo $i 	= 	$m->insertAddressBook($data);

	}

	public function editAddressBook($id){
		$m 		= new UserModel;
		$userId = Auth::user()->id;
		
		$array_address_book 	= 	$m->selectAddresBook('Id', $id);
		
		if($array_address_book[0]->UserId != $userId){
			return redirect('user/address-book');
		}
		
		return view('user-layouts.edit_address_book')
									->with('array_address_book', $array_address_book);
		
	}

	public function updateAddressBook(Request $request){
		$post 	=	$request->all();
		$m 		= new UserModel;

		$userId = Auth::user()->id;
		$id = $post['id'];

		$data = array(
			'UserId'			=> $userId,
			'Fullname'			=> $post['fullname'],
			'ContactNumber'		=> $post['mobilenumber'],
			'OtherNotes' 	 	=> $post['othernotes'],
			'Address' 			=> $post['address'],
			'State'	 			=> $post['state'],
			'City' 		 		=> $post['city'],
			'ZipCode'     		=> $post['zipcode']
		);
		
		echo $i 	= 	$m->saveUpdateAddressBook($data, $id);

	}

	public function profile(){
		$m 		= new UserModel;
		$userId = Auth::user()->id;

		$array_profile_info 	= 	$m->selectProfileInfo($userId);
		return view('user-layouts.profile')
										->with('array_profile_info', $array_profile_info);
	}

	public function editProfile(){
		$m 		= new UserModel;
		$userId = Auth::user()->id;

		$array_profile_info 	= 	$m->selectProfileInfo($userId);
		return view('user-layouts.edit_profile')
										->with('array_profile_info', $array_profile_info);
	
	}
	
	public function updateProfile(Request $request){
		$post 	=	$request->all();
		$m 		= new UserModel;

		$userId = Auth::user()->id;

		$user_logins_data = array(
								'name'			=> $post['fullname'],
								'email'			=> $post['email']
							);

		$user_info_data = array(
								'UserId'			=> $userId,
								'ContactNumber'		=> $post['contactnumber'],
								'Gender'			=> $post['gender'],
								'Birthday'			=> date('Y-m-d', strtotime($post['birthday']))
							);
	
		$i = $m->saveUpdateUserLogins($user_logins_data, $userId);
		$i1 = $m->saveUpdateUserInfo($user_info_data, $userId);
		

		return $i;
	}

	public function changePassword(){
		return view('user-layouts.change_password');
	}

	public function updatePassword(Request $request){
		$post 	=	$request->all();
		$m 		= new UserModel;
		$c_password = Auth::user()->password;
		$userId = Auth::user()->id;

		if(!(Hash::check($post['current_password'], $c_password))){
			$message = "Your current password does not matches with the password you provided. Please try again.";
            return $message;
		}

		if(strcmp($post['current_password'], $post['new_password']) == 0){
            //Current password and new password are same
			$message = "New Password cannot be same as your current password. Please choose a different password.";
            return $message;
        }

		if ($post['new_password'] != $post['con_new_password']) {
			// The passwords matches
			$message = "Password confirmation and New Password must match. Please try again.";
            return $message;
		}


		$i = $m->saveUpdatePassword(bcrypt($post['new_password']) , $userId);
		
		return $i;
	}
	
	public function orders(){
		$m 		= new UserModel;
		$userId = Auth::user()->id;
		$array_payment_details 	= 	$m->selectPaymentDetails('UserId', $userId);

		// var_dump($array_payment_details);

		// var_dump($array_payment_details);
		return view('user-layouts.orders')->with('array_payment_details', $array_payment_details);
	}


	public function myDesigns(){
		$m 		= new UserModel;
		$userId = Auth::user()->id;
		
		$array_client_designs 	= 	$m->selectClientDesigns($userId);
		// var_dump($array_client_designs);
		return view('user-layouts.my-design')->with('array_client_designs', $array_client_designs);
	}
	
	public function viewDesign($designCode){
		$m 		= new UserModel;
		$newMainModel 		= new MainModel;
		$userId = Auth::user()->id;
		$array_client_designs 	= 	$m->selectClientDesignsbyCode($designCode);
		
		// check if its your design	
		if($userId != $array_client_designs[0]->ClientId){
			return redirect()->back();
		}

		$array_template_paths 	= 	$m->selectTemplatePaths('TemplateCode', $array_client_designs[0]->TemplateCode);
		$array_cat_name = $newMainModel->selectCategoryName($array_client_designs[0]->TemplateCode);

		return view('user-layouts.view-design')
											->with('array_client_designs', $array_client_designs)
											->with('array_template_paths', $array_template_paths)
											->with('array_cat_name', $array_cat_name);
	}

	public function updateDesignDetails(Request $request){
		$post 	=	$request->all();
		$m 		= new UserModel;

		$design_name = $post['design_name'];
		$design_code = $post['design_code'];

		$client_design_data = array(
			'DesignName'	=> $design_name
		);

		$i = $m->updateClientDesign($client_design_data, $design_code);

		return $i;
		
	}

	public function store(){
		$m 		= new UserModel;
		$userRole = Auth::user()->role;
		$array_store_info = array();

		if($userRole == "store_owner"){
			$storeId = Auth::user()->store_id;
			
			$array_store_info 	= 	$m->selectStoreInfo($storeId);

			return redirect('teamstore/'. $array_store_info[0]->StoreUrl);


		}

	}

	public function storeItems(){
		$thumbnails = array();
		$newUserModel 		= new UserModel;
		$newTeamStoreModel 	= new TeamStoreModel;

		$user_role = Auth::user()->role;
		$store_id = Auth::user()->store_id;

		$store_array 	= $newTeamStoreModel->selectTeamStore('Id', $store_id);
		$product_array 	= $newTeamStoreModel->selectTeamStoreProducts('TeamStoreId', $store_id);

		foreach ($product_array as $p => $pr_arr) {

			$thumbnails_array 			= 	$newTeamStoreModel->getProductThumbnails($pr_arr->Id);
			foreach ($thumbnails_array as $t => $thumb) {
				
				if($thumb->ImageClass == 'custom'){
					$displayThumbnails = $thumb->Image;
					break;
				}

				if($thumb->ImageClass == 'active'){
					$displayThumbnails = $thumb->Image;
					break;
				}	
			}

			$thumbnails[] = array(
								'folder' 	=>	$store_array[0]->ImageFolder,
								'product_id' =>  $pr_arr->Id,
								'thumb'	     =>  $displayThumbnails
			);
		}

		// var_dump($thumbnails);
		return view('user-layouts.store_items')->with('store_array', $store_array)
											->with('product_array', $product_array)
											->with('thumbnails', $thumbnails);
	}

	public function viewStoreItem($url){
		$product_array = array();
		$newUserModel 		= new UserModel;
		$newTeamStoreModel 	= new TeamStoreModel;

		$product_array 		= $newTeamStoreModel->selectTeamStoreProducts('ProductURL', $url);
		$thumbnails_array 	= $newTeamStoreModel->getThumbnails($product_array[0]->Id);
		// var_dump($product_array);
		return view('user-layouts.view-store-item')->with('product_array', $product_array)
													->with('thumbnails_array', $thumbnails_array);

		
	}


	public function storeItemUpdate(Request $request){
		$post 	=	$request->all();
		$newTeamStoreModel 	= new TeamStoreModel;

		$item_url = $post['item_url'];
		$data = array(
			'ProductName'			=> $post['itemName'],
			'ProductPrice'			=> str_replace('$ ', '', $post['item_price']),
			'ProductDescription'	=> $post['itemDescription'],
			'PrivacyStatus' 	 	=> $post['item_privacy']
		);

		$i 	= $newTeamStoreModel->updateStoreItem($data, $item_url);
		
		return $i;
	}

	public function storeSetting()
	{
		return view('user-layouts.store_setting');
	}

	public function emailVerify()
	{
		$m 		= new UserModel;
		$userId = Auth::user()->id;
		$email_is_verified = Auth::user()->email_is_verified;

		if($email_is_verified == 0){
			$array_profile_info 	= 	$m->selectProfileInfo($userId);
			return view('user-layouts.email_verify')
											->with('array_profile_info', $array_profile_info);
		}

		return redirect('user/profile');
		
	}


	public function resendVericationCode(Request $request){
		$post 	=	$request->all();
		$random_hash =  rand(1000, 9999);

		$newUserModel 		= new UserModel;
	
		$emailDetails = [
            'receiver'   => $post['email'],  
			'subject' => 'CREW Sportswear Email Verification Code',
			'verification_code' 		=> $random_hash
		];
		
		Mail::send('emails.resend_code', $emailDetails, function($message) use ($emailDetails) {
			
			$message->from('no-reply@crewsportswear.com', 'CREW Sportswear');
			$message->to($emailDetails['receiver'])->subject('CREW Sportswear Email Verification Code');

		});

		if( count(Mail::failures()) > 0 ) {
			
			echo '0';
	 
		}else{
			$data = array(
				'EmailAddress'		=> $post['email'],
				'VerCode'		=> $random_hash
			);
	
			$i 	= $newUserModel->saveResendCode($data);
			echo $i;
		}
	}
	

	public function verifyCode(Request $request){
		$post 	=	$request->all();

		$verification_code = $post['verification_code'];
		$userEmail = Auth::user()->email;

		$newUserModel 		= new UserModel;
		$userId = Auth::user()->id;
		
		$data = array(
			'EmailAddress'		=> $userEmail,
			'Code'				=> $verification_code
		);

		$i 	= $newUserModel->validateCode($data);
		// var_dump($i);

		if($i){

			$user_logins_data = array(
				'email_is_verified'		=> 1
			);
			
			$newUserModel->saveUpdateUserLogins($user_logins_data, $userId);
		
			return response()->json(array(
				'success' => true, 
				'message'=>'Your email is successfully verified.'
			));
			
		}else{
			return response()->json(array(
				'success' => false, 
				'message'=>'Invalid verification code.'
			));
		}
	}

	public function orderDetails($ck){
		$newUserModel 		= new UserModel;
		$order_item_array 		= $newUserModel->selectOrderItem($ck);
		$item_goup_array 		= $newUserModel->itemGroup($ck);
		$item_thumbs 		= $newUserModel->selectDisplayItemThumb();
		$array_payment_details 	= 	$newUserModel->selectPaymentDetails('CartKey', $ck);
		return view('user-layouts.order_details')
									->with('array_payment_details', $array_payment_details)
									->with('img_thumb', $item_thumbs)
									->with('item_goup_array', $item_goup_array)
									->with('order_item_array', $order_item_array);
	}
	
}
