<?php defined('SYSPATH') or die('No direct script access.');

class Controller_User extends Controller {

        const WEIGHT = 25; 
        const BOOKWEIGHT = 50;
        const MAXAMOUNT = 1000;
        
        const USERTYPE = 3; 
        
        const MKBOOK = 'Delivery 5 days';
        const GBOOK = 'Delivery 21 days';
        
        
        const MAILFOOT = '<br/><br/>Sincerely, <br/>MAKEEN BOOKS ONLINE TEAM <br/><br/>';
        
       

        
        public function action_index()
	{
		
	}
        
        
        public function action_new_user()
	{
            
           
                if(!Session::instance()->get('CARTARRAY')){
                    HTTP::redirect(URL::base(TRUE));
                    
                }
                
                if(Session::instance()->get('LOGINOBJ')){
                    HTTP::redirect(URL::base(TRUE) . 'User/delivery_address');
                    
                }
		
                
                $data = NULL;
                $data['error'] = NULL;
                
                 $messageType = trim($this->request->param('id'));
                
                 $data['messageType'] = $messageType;
                
                if(trim($this->request->param('id2'))){
                    $data['error'] = $this->request->param('id2');
                    
                }
                
                
                $view = View::factory('site/index');
                $view->ptype = 'USER';
                $view->pBody = View::factory('site/new_user' , $data);
                $this->response->body($view);
	}
        
        public function action_auto_completecity()
	{
		$q = strtolower($_GET['term']);
		if (!$q) return;
		$searchDataAll = DB::query(Database::SELECT, "SELECT courier_id  , area FROM courier WHERE area LIKE '$q%'")->execute();
		
		$result = array();
		foreach($searchDataAll as $dbObj){
			if($dbObj['courier_id']){
				array_push($result, array('id'=>$dbObj['courier_id'], 'label'=>$dbObj['area']));
			}else{
				array_push($result, array('id'=>$dbObj['courier_id'], 'label'=>$dbObj['area']));
			}
				//if (count($result) > 20) break;		
		}

    	echo  json_encode($result);
	
	}
        
        public function action_check_login()
	{
             
             //check email and pwd exsit
             
             $uName = trim($_POST['Emailfiled']);
             $pwd = trim($_POST['Password']);
             
             
             
             $user = ORM::factory('Userinfo')->where('userinfo_username', '=', $uName)->where('userinfo_pwd', '=', $pwd)->where('userinfo_type', '=', Controller_User::USERTYPE)->where('enable', '=', 'T')->find();
             if ($user->loaded()){
                 
                 
                 Session::instance()->set('LOGINOBJ' , $user);
                 
                 $messageType = trim($_POST['messageType']);
                 
                 
                 
                 
                 if($messageType == 1){
                    HTTP::redirect(URL::base(TRUE) . 'User/delivery_address');
                 }else if($messageType == 2){
                    HTTP::redirect(URL::base(TRUE) . 'User/user_home');
                     
                 }
             }else{
                 
                 $messageType = trim($_POST['messageType']);
                 if($messageType == 1){
                   HTTP::redirect(URL::base(TRUE) . 'User/new_user/1/3');
                 }else if($messageType == 2){
                    HTTP::redirect(URL::base(TRUE) . 'User/log_in/2');
                     
                 }
             }
             
        }
        
        
        public function action_user_home()
	{
            
                if(!Session::instance()->get('LOGINOBJ')){
                    HTTP::redirect(URL::base(TRUE));
                    
                }
		
                
                
                $data['seoNo'] = TRUE; 
                
                $view = View::factory('site/index');
                $view->ptype = 'USERHOME';
                $view->pBody = View::factory('site/user_home' , $data);
                $this->response->body($view);
	}
        
        
        public function action_my_sale()
	{
            
                if(!Session::instance()->get('LOGINOBJ')){
                    HTTP::redirect(URL::base(TRUE));
                    
                }
		
                
                $loginObj = Session::instance()->get('LOGINOBJ');
                
                $data['user'] = $loginObj;
                
                $data['allOrders'] = ORM::factory('Orders')->where('userinfo_id', '=', $loginObj->userinfo_id)->order_by('cdate' , 'DESC')->find_all();
               
                
                 $data['seoNo'] = TRUE; 
                
                $view = View::factory('site/index');
                $view->ptype = 'MYINFO';
                $view->pBody = View::factory('site/my_sale' , $data);
                $this->response->body($view);
	}
        
        
        public function action_my_info()
	{
            
                if(!Session::instance()->get('LOGINOBJ')){
                    HTTP::redirect(URL::base(TRUE));
                    
                }
		
                
                $data['user'] = Session::instance()->get('LOGINOBJ');
                
                
                $data['error'] = NULL;
                if(trim($this->request->param('id'))){
                    $data['error'] = trim($this->request->param('id'));
                }
                
                $data['seoNo'] = TRUE; 
                
                $view = View::factory('site/index');
                $view->ptype = 'MYINFO';
                $view->pBody = View::factory('site/my_info' , $data);
                $this->response->body($view);
	}
        
        public function action_update_user()
	{
             
             //check email exsit
             
            
            
            $fName = trim($_POST['fname']);
            $lName = trim($_POST['lname']);
            $phone = trim($_POST['Phone']);
            $address1 = trim($_POST['Address1']);
            $address2 = trim($_POST['Address2']);
            
            
           
            
            $bookObj = ORM::factory('Bookshop' , trim($_POST['userId']));
            $bookObj->bookshop_name = $fName;
            $bookObj->bookshop_lname = $lName;
            $bookObj->bookshop_phone = $phone;
            $bookObj->bookshop_address = $address1;
            $bookObj->bookshop_address2	 = $address2;
            $bookObj->save();
            
           
            
            HTTP::redirect(URL::base(TRUE) . 'User/my_info/1');
             
         }
        
         
         public function action_user_password()
	{
            
                if(!Session::instance()->get('LOGINOBJ')){
                    HTTP::redirect(URL::base(TRUE));
                    
                }
		
                
                $data['user'] = Session::instance()->get('LOGINOBJ');
                
                
                $data['error'] = NULL;
                if(trim($this->request->param('id'))){
                    $data['error'] = trim($this->request->param('id'));
                }
                
                 $data['seoNo'] = TRUE; 
                
                $view = View::factory('site/index');
                $view->ptype = 'USERPASSWORD';
                $view->pBody = View::factory('site/user_password' , $data);
                $this->response->body($view);
	}
        
        public function action_check_password()
	{
		$pwd = trim($_POST['Password']);
                
                $user =  Session::instance()->get('LOGINOBJ');
                
		
		
		if($user->userinfo_pwd == $pwd){
			$user->userinfo_pwd = trim($_POST['newPassword']);
			$user->save();
		
			HTTP::redirect(URL::base(TRUE) . 'User/user_password/1');
		}else{
			HTTP::redirect(URL::base(TRUE) . 'User/user_password/2');
			
		}
		
	}
        
        
         public function action_create_user()
	{
             
             //check email exsit
             
             $uName = trim($_POST['UserName']);
             
             
             
             $user = ORM::factory('Userinfo')->where('userinfo_username', '=', $uName)->where('enable', '=', 'T')->find();
             if ($user->loaded()){
                 
                 HTTP::redirect(URL::base(TRUE) . 'User/new_user/1/2');
             }
             
            
             
             
            
            //create User
            $pwd = trim($_POST['cpassword']);
            
            $fName = trim($_POST['fname']);
            $lName = trim($_POST['lname']);
            $phone = trim($_POST['Phone']);
            $address1 = trim($_POST['Address1']);
            $address2 = trim($_POST['Address2']);
            
            $bookObj = ORM::factory('Bookshop');
            $bookObj->bookshop_name = $fName;
            $bookObj->bookshop_lname = $lName;
            $bookObj->bookshop_phone = $phone;
            $bookObj->bookshop_address = $address1;
            $bookObj->bookshop_address2	 = $address2;
            $userInfoId = $bookObj->save();
            
            $user = ORM::factory('Userinfo');
            $user->userinfo_username = $uName;
            $user->userinfo_pwd = $pwd;
            $user->userinfo_type = 3;
            $user->bookshop_id	 = $userInfoId;
            $userId = $user->save();
            
            
            Session::instance()->set('LOGINOBJ' , $user);
            
            
            //send user create 
            
            
                                 
            $bodyCon = "Thank you for signing up with makeenbooks.com.<br/><br/>
                    UserName = $uName <br/>
                        Password = $pwd"
                    . "<br/><br/>Your Makeen  Books account has been created.<br/><br/>

You can login and browse our website. Just login, browse, order and get your favourite books delivered to your doorstep! Feel free to explore our website. Enjoy the experience!
<br/><br/>
Feel free to contact us by sending us an email at info@makeenbooks.com or giving us a call on +94 11 2375930"; 
                                
            $subject    = 'Thank you for signing up with makeenbooks.com';
                                                    
                                
            $mailObj = ORM::factory('Siteemails' , 1);
                                
            $fromEmail = $mailObj->email;
            $fromName = $mailObj->name	;

            $eData['name'] = $fName;
            $eData['ebody'] =   $bodyCon . self::MAILFOOT;      
            $subject    = 'Thank you for signing up with makeenbooks.com';

            $eBody = View::factory('site/email' , $eData); 
				
           Controller_User::action_send_email($eBody, $uName, $fromEmail, $fromName, $subject);
            
            
             HTTP::redirect(URL::base(TRUE) . 'User/delivery_address');
            
            
             
             
             
         }
         
         public function action_normal_create_user()
	{
             
             //check email exsit
             
             $uName = trim($_POST['UserName']);
             
             
             
             $user = ORM::factory('Userinfo')->where('userinfo_username', '=', $uName)->where('enable', '=', 'T')->find();
             if ($user->loaded()){
                 
                 HTTP::redirect(URL::base(TRUE) . 'User/log_in/1');
             }
             
            
             
             
            
            //create User
            $pwd = trim($_POST['cpassword']);
            
            $fName = trim($_POST['fname']);
            $lName = trim($_POST['lname']);
            $phone = trim($_POST['Phone']);
            $address1 = trim($_POST['Address1']);
            $address2 = trim($_POST['Address2']);
            
            $bookObj = ORM::factory('Bookshop');
            $bookObj->bookshop_name = $fName;
            $bookObj->bookshop_lname = $lName;
            $bookObj->bookshop_phone = $phone;
            $bookObj->bookshop_address = $address1;
            $bookObj->bookshop_address2	 = $address2;
            $userInfoId = $bookObj->save();
            
            $user = ORM::factory('Userinfo');
            $user->userinfo_username = $uName;
            $user->userinfo_pwd = $pwd;
            $user->userinfo_type = 3;
            $user->bookshop_id	 = $userInfoId;
            $userId = $user->save();
            
            
            Session::instance()->set('LOGINOBJ' , $user);
            
            //send user create 
            
            
                                 
                                
            $bodyCon = "Thank you for signing up with makeenbooks.com.<br/><br/>
                    UserName = $uName <br/>
                        Password = $pwd"
                    . "<br/><br/>Your Makeen  Books account has been created.<br/><br/>

You can login and browse our website. Just login, browse, order and get your favourite books delivered to your doorstep! Feel free to explore our website. Enjoy the experience!
<br/><br/>
Feel free to contact us by sending us an email at info@makeenbooks.com or giving us a call on +94 11 2375930"; 
                                
            
                
            $eData['name'] = $fName;
            $eData['ebody'] =   $bodyCon . self::MAILFOOT;      
            $subject    = 'Thank you for signing up with makeenbooks.com';

            $eBody = View::factory('site/email' , $eData); 
                                                    
                                
            $mailObj = ORM::factory('Siteemails' , 1);
                                
            $fromEmail = $mailObj->email;
            $fromName = $mailObj->name	;
				
				
                                
           Controller_User::action_send_email($eBody, $uName, $fromEmail, $fromName, $subject);
            
            
            HTTP::redirect(URL::base(TRUE) . 'User/user_home');

            
            
             
             
             
         }
         
         public function action_delivery_address()
	{       
                $data = NULL;
             
                if(!Session::instance()->get('CARTARRAY')){
                    HTTP::redirect(URL::base(TRUE));
                    
                }
                
             
             if(Session::instance()->get('LOGINOBJ')){
                    
                     $userObj = Session::instance()->get('LOGINOBJ');
                     $dArray['fname'] = $userObj->bookshop->bookshop_name;
                     $dArray['lname'] = $userObj->bookshop->bookshop_lname;
                     $dArray['Email'] = $userObj->userinfo_username;
                     $dArray['Phone'] = $userObj->bookshop->bookshop_phone;
                     $dArray['Address1'] = $userObj->bookshop->bookshop_address;
                     $dArray['Address2'] = $userObj->bookshop->bookshop_address2;
                     $dArray['Sameas'] = 'T';
                     
                     $dArray['dfname'] = NULL;
                     $dArray['dlname'] = NULL;
                     $dArray['dEmail'] = NULL;
                     $dArray['dPhone'] = NULL;
                     $dArray['dAddress1'] = NULL;
                     $dArray['dAddress2'] = NULL;
                     $dArray['City'] = NULL;
                      
                      
                     $data['dArray'] = $dArray;
                }else if(Session::instance()->get('ADDRESS')){
                    
                    $dArray = Session::instance()->get('ADDRESS');
                    $data['dArray'] = $dArray;
                    
                }
                
                
                if(trim($this->request->param('id'))){
                    $data['error'] = trim($this->request->param('id'));
                }
               
               
		$styles = array(
                    'assets/bower_components/jquery-ui/themes/excite-bike/jquery-ui.min.css' => 'all',
                    
                    
		);
                
                 $data['seoNo'] = TRUE; 
                
                $view = View::factory('site/index');
                $view->styles = $styles;
                $view->ptype = 'DELICERYUSER';
                $view->pBody = View::factory('site/delivery_address' , $data);
                $this->response->body($view);
	}
        
         public function action_payment()
	{
                
                
                if(!Session::instance()->get('CARTARRAY')){
                    HTTP::redirect(URL::base(TRUE));
                    
                }
             
                $payType  = 1;
                
                if(isset($_POST) && count($_POST)){

                        //set delevery arry
                    
                    

                        $dArray = $_POST;

                         Session::instance()->set('ADDRESS' , $dArray);

                }else if(Session::instance()->get('ADDRESS')){
                    $dArray = Session::instance()->get('ADDRESS');
                }
                
                

                 if(trim($this->request->param('id'))){


                    $errorId = $this->request->param('id');

                     //add order to table
                     $userId = 0;
                     $referenceNo = 0;
                     $oId =  Session::instance()->get('OVALUE');
                     $gType = Session::instance()->get('GTYPE');
                     
                     
                     
                     
                    
                    if(Session::instance()->get('LOGINOBJ')){
                 
                        $userObj = Session::instance()->get('LOGINOBJ');
                        $userId =  $userObj->userinfo_id;
                    }
                     
                    if(trim($this->request->param('id'))){

                     $referenceNo = $this->request->param('id');

                    }
                     
                     
                     $address = Session::instance()->get('ADDRESS'); 
                     
                     
                    $orderObj = ORM::factory('Orders');
                    $orderObj->userinfo_id  =  $userId ;
                    $orderObj->number_of_books = Session::instance()->get('PQUAN');
                    $orderObj->full_amount = Session::instance()->get('FAMOUT');
                    $orderObj->shipping_cost =Session::instance()->get('BCOST');
                    $orderObj->pay_type = Session::instance()->get('GTYPE');
                    $orderObj->reference_no = $referenceNo;
                    $orderObj->approve = Controller_Admin::PENDING;
                    $orderObj->user_ip =  $_SERVER['REMOTE_ADDR'];
                    $orderObj->systerm_order_id = $oId;
                
                    $orderObj->c_email = $address['dEmail'] ;
                    $orderObj->name = $address['dfname'] ;
                    $orderObj->lname = $address['dlname'] ;
                    $orderObj->address1 = $address['dAddress1'] ;
                    $orderObj->address2 = $address['dAddress2'] ;
                    $orderObj->phone = $address['dPhone'] ;
                
                
                    $orderObj->b_name = $address['fname'] ; 
                    $orderObj->b_lname = $address['lname']  ;
                    $orderObj->b_address1 = $address['Address1'] ;
                    $orderObj->b_address2 = $address['Address2'] ;
                    $orderObj->b_phone = $address['Phone'] ;
                    $orderObj->b_email = $address['Email'] ;
                    $orderObj->courier_id = Session::instance()->get('CITYID');
                    $orderObj->shippingother = $address['Sameas'] ;
                    $orderId = $orderObj->save();
                     
                     
                    $cartArray = Session::instance()->get('CARTARRAY');
                    foreach($cartArray as $productId=>$productInfo) { 
                    
                     $pObj = $cartArray[$productId]['pObj'];
                     $quan = $cartArray[$productId]['count'];
                    
                     $bookorderObj = ORM::factory('Bookorder');
                     $bookorderObj->orders_id = $orderId;
                     $bookorderObj->bookmain_id = $productId;
                     $bookorderObj->number_of_books =$cartArray[$productId]['count'];
                     
                     $bPrice = Controller_App::action_bookprice($pObj->price);
                        $bookorderObj->btype = 'G';
                        $bDays = Controller_User::GBOOK;
                     
//                    if($pObj->spquan){
//                        
//                        $bPrice = $pObj->spprice;
//                        $bookorderObj->btype = 'S';
//                        $bDays = Controller_User::MKBOOK;
//                        
//                    }elseif($pObj->stock) {
//                        
//                        
//                        $bPrice = $pObj->mkprice;
//                        $bookorderObj->btype = 'M';
//                        $bDays = Controller_User::MKBOOK;
//                        
//                    }else {
//                        
//                        $bPrice = Controller_App::action_bookprice($pObj->price);
//                        $bookorderObj->btype = 'G';
//                        $bDays = Controller_User::GBOOK;
//                        
//                     }
              
                     $bookorderObj->book_prize =$bPrice;
                     $bookorderObj->full_prize =$bPrice * $cartArray[$productId]['count'];
                     $bookorderObj->save();
                     
                }


                     
                    
                    
                    if($errorId == 36){

                         $data['errorcode'] =  'Credit Card holder canceled the request';
                    }else{

                         $data['errorcode'] =  'Transaction is declined';
                    }

                   



                }
                
               
                
                //get city type
                
                $cityTy = trim($dArray['City']);
                $city = ORM::factory('Courier')->where('area', '=', $cityTy)->find();
                
                 if(!$city->loaded()){
                     HTTP::redirect(URL::base(TRUE) . 'User/delivery_address/1');
                     
                 }
                
                
               
                //remove payment gatwau
                
                if($city->zone != 'A'){
                    $payType = 5;
                    
                }else{
                    $payType = 4;
                }
                
                if(Session::instance()->get('GTYPE')){
                    
                    $payType =  Session::instance()->get('GTYPE');
                }
                
                $data['zone'] = $city->zone;
                
                $data['payType'] = $payType;
                
                
                
             
            
        		$styles = array(
                            'assets/bower_components/jquery-ui/themes/excite-bike/jquery-ui.min.css' => 'all',
                            
                            
        		);
                
                 $data['seoNo'] = TRUE; 
                
                $view = View::factory('site/index');
                $view->styles = $styles;
                $view->ptype = 'PAYMENT';
                $view->pBody = View::factory('site/payment' , $data);
                $this->response->body($view);
	}
        
        public function action_review()
	{
             
                $cartArray = NULL;
                $bringCost = 0;
                
                $gType = $_POST['Gateway'];


                Session::instance()->set('GTYPE' , $gType);
               
                if(Session::instance()->get('CARTARRAY')){
                    $cartArray = Session::instance()->get('CARTARRAY');
                    
                    //check garden books exsit
                    
                    if( Session::instance()->get('GTYPE') == 4){
                            foreach($cartArray as $productId=>$productInfo) { 


                                    $pObj = $cartArray[$productId]['pObj'];

                                    if(!$pObj->stock) {
                                        HTTP::redirect(URL::base(TRUE) . 'Cart/cart/0/0/1');
                                    }


                            }
                    }
                    
                    
                }else{
                    
                     HTTP::redirect(URL::base(TRUE) . 'Cart/cart');
                }
                
               
             
                
                $address = Session::instance()->get('ADDRESS');
                
                
                
                if($address['Sameas'] == 'T'){
                    
                    $address['dfname'] =  $address['fname'] ;
                    $address['dlname'] =  $address['lname'] ;
                    $address['dEmail'] =  $address['Email'] ;
                    $address['dPhone'] =  $address['Phone'] ;
                    $address['dAddress1'] =  $address['Address1'] ;
                    $address['dAddress2'] =  $address['Address2'] ;
                    
                }
                
                
                Session::instance()->set('ADDRESS' , $address);
               
                
                $deCity = trim($address['City']);
                $city = ORM::factory('Courier')->where('area', '=', $deCity)->find();
                
                if($city->loaded()){
                    
                   Session::instance()->set('CITYID' , $city->courier_id);
                   $count = 0; 
                   $fullAmount = 0;
                   foreach($cartArray as $cartKey=>$valueCart){
                       
                       $bookObj = $cartArray[$cartKey]['pObj'];
                       $count = $count  + $cartArray[$cartKey]['count'];
                       
                       if($bookObj->stock) {
                           $price =  $bookObj->mkprice;
                       }else{
                            $price =  Controller_App::action_bookprice($bookObj->price);
                       }
                       
                       $fullAmount = $fullAmount + ($price * $cartArray[$cartKey]['count']);
                       
                   }
                  
                   
                   
                   if($fullAmount < self::MAXAMOUNT){
                   
                        $fullWeight = $count * self::WEIGHT;

                        if($fullWeight <= self::BOOKWEIGHT){


                            $bringCost = $city->first;

                        }else{
                             $bringCost =  $city->first;
                             $rem = $fullWeight - self::BOOKWEIGHT;

                             $divWe = ($rem / self::BOOKWEIGHT) *  $city->sec  ;
                             $bringCost = $bringCost + $divWe;

                        }
                    }
                  
                 
                    
                }else{
                    HTTP::redirect(URL::base(TRUE) . 'User/delivery_address/1');
                    
                }
                
                
            
        		$styles = array(
                            'assets/bower_components/jquery-ui/themes/excite-bike/jquery-ui.min.css' => 'all',
                            
                            
        		);
                
                
                //ganarate order id
                
                $findOrder = ORM::factory('Orders')->order_by('orders_id' , 'DESC')->limit(1)->find();
                $randOrderId =  $findOrder->orders_id + 1;
                
                $orderValue = 'BK' . (100000000 + $randOrderId);

                Session::instance()->set('OVALUE' , $orderValue);
                
                
                $data['cartArray'] = $cartArray;
                $data['bringCost'] = $bringCost;
                $data['address'] = $address;
                $data['gType'] = $gType;
                $data['orderValue'] = $orderValue;
                 $data['seoNo'] = TRUE; 
                
                $view = View::factory('site/index');
                $view->styles = $styles;
                $view->ptype = 'REVIEW';
                $view->pBody = View::factory('site/review' , $data);
                $this->response->body($view);
	}
        
        
         public function action_paydone()
	{       
                $data = NULL;
                $userId = 0;
                $referenceNo = 0;
             
                if(!Session::instance()->get('CARTARRAY')){
                    HTTP::redirect(URL::base(TRUE));
                    
                }

                if(isset($_POST['orderId'])){
                    $oId = trim($_POST['orderId']);

                }else{

                    $oId =  Session::instance()->get('OVALUE');
                }
                
                    
                $address = Session::instance()->get('ADDRESS');
                
                
                
                //add cart procusts to database
                
                 
                 
                 
                $data['orderId'] = $oId;
                
                
                
                $gType = Session::instance()->get('GTYPE');
                
               
                
                
                $data['gType'] = $gType;
                
                if(Session::instance()->get('LOGINOBJ')){
                 
                    $userObj = Session::instance()->get('LOGINOBJ');
                    $userId =  $userObj->userinfo_id;
                }
                
                $gType  = Session::instance()->get('GTYPE');

                

                if(trim($this->request->param('id'))){

                    $referenceNo = $this->request->param('id');

                }
                
                $orderObj = ORM::factory('Orders');
                $orderObj->userinfo_id  =  $userId ;
                $orderObj->number_of_books = Session::instance()->get('PQUAN');
                $orderObj->full_amount = Session::instance()->get('FAMOUT');
                $orderObj->shipping_cost =Session::instance()->get('BCOST');
                $orderObj->pay_type = Session::instance()->get('GTYPE');
                $orderObj->reference_no = $referenceNo;
                $orderObj->approve = Controller_Admin::PENDING;
                $orderObj->user_ip =  $_SERVER['REMOTE_ADDR'];
                $orderObj->systerm_order_id = $oId;
                
                $orderObj->c_email = $address['dEmail'] ;
                $orderObj->name = $address['dfname'] ;
                $orderObj->lname = $address['dlname'] ;
                $orderObj->address1 = $address['dAddress1'] ;
                $orderObj->address2 = $address['dAddress2'] ;
                $orderObj->phone = $address['dPhone'] ;
                
                
                $orderObj->b_name = $address['fname'] ; 
                $orderObj->b_lname = $address['lname']  ;
                $orderObj->b_address1 = $address['Address1'] ;
                $orderObj->b_address2 = $address['Address2'] ;
                $orderObj->b_phone = $address['Phone'] ;
                $orderObj->b_email = $address['Email'] ;
                $orderObj->courier_id = Session::instance()->get('CITYID');
                $orderObj->shippingother = $address['Sameas'] ;
                $orderId = $orderObj->save();
                
                $fName = $address['fname'];
                $orderValue = $oId;
                $uEmail = $address['Email'];
                
                
                $pHtml = NULL;
                
                $cartArray = Session::instance()->get('CARTARRAY');
                foreach($cartArray as $productId=>$productInfo) { 
                    
                    $pObj = $cartArray[$productId]['pObj'];
                    $quan = $cartArray[$productId]['count'];
                    
                     $bookorderObj = ORM::factory('Bookorder');
                     $bookorderObj->orders_id = $orderId;
                     $bookorderObj->bookmain_id = $productId;
                     $bookorderObj->number_of_books =$cartArray[$productId]['count'];
                     
                    if($pObj->spquan ){
                        
                        $bPrice = $pObj->spprice;
                        $bookorderObj->btype = 'S';
                        $bDays = Controller_User::MKBOOK;
                        
                    }elseif($pObj->stock) {
                        
                        
                        $bPrice = $pObj->mkprice;
                        $bookorderObj->btype = 'M';
                        $bDays = Controller_User::MKBOOK;
                        
                    }else {
                        
                        $bPrice = Controller_App::action_bookprice($pObj->price);
                        $bookorderObj->btype = 'G';
                        $bDays = Controller_User::GBOOK;
                        
                     }
              
                     $bookorderObj->book_prize =$bPrice;
                     $bookorderObj->full_prize =$bPrice * $cartArray[$productId]['count'];
                     $bookorderObj->save();
                     
                     
                     
                     
                     if($pHtml){
                         $pHtml = $pHtml . "<tr>"
                                 . "<td>". $pObj->name  ."</td>"
                                 . "<td>". $bDays ."</td>"
                                 . "<td>". Controller_App::action_price($bPrice) ."</td>"
                                 . "<td>". $cartArray[$productId]['count'] ."</td>"
                                 . "<td>". Controller_App::action_price(($bPrice * $cartArray[$productId]['count'])) ."</td>"
                                 . "</tr>";
                        }else{
                            
                            $pHtml = "<tr>"
                                 . "<td>". $pObj->name  ."</td>"
                                 . "<td>". $bDays ."</td>"
                                 . "<td>". Controller_App::action_price($bPrice) ."</td>"
                                 . "<td>". $cartArray[$productId]['count'] ."</td>"
                                 . "<td>". Controller_App::action_price(($bPrice * $cartArray[$productId]['count'])) ."</td>"
                                 . "</tr>";
							
                        }
                        
                         
                     
                     
                     
                }
                
                
                
                if($gType == 1 || $gType == 2){
                             
                             
                    $invoiceorderObj = ORM::factory('Invoiceorder')->order_by('invoiceorder_id' , 'DESC')->limit(1)->find();
		
                      if ($invoiceorderObj->loaded()){
                               $invoiceId = intval($invoiceorderObj->invoiceorder_id) + 1;
                         }else{
                              $invoiceId = 1;
                       }

                        $inVoiceId = 'MKI' . (100000000 + $invoiceId) ;
                                
                        $orderObj->approve = 2;
                        $orderObj->paid_amount = 'T';
                        $orderObj->save();
                                
                                
                        $adminlogObj = ORM::factory('Adminlog');
                        $adminlogObj->orders_id = $orderId;
                        $adminlogObj->comment = $inVoiceId . ' created';
                        $adminlogObj->approve = 2;
                        $adminlogObj->save();
                                
                                
                        $invoiceorderObj = ORM::factory('Invoiceorder') ;
                        $invoiceorderObj->orders_id = $orderId;
                        $invoiceorderObj->invoice_id = $inVoiceId ;
                        $invoiceorderObj->full_amount = Session::instance()->get('TPRODUCT');
                        $invoiceorderId = $invoiceorderObj->save();
                                
                       
                        //create invoice for cutermer
                        
                          
                        
                        $pdf = new Model_FPDF('P','mm','A4');
                        $pdf->AddPage();
                        $pdf->SetMargins(1,1,1);
                        $pdf->Image('assets/img/emailnew.png',1,1,170,20);
		
		
                
                        $pdf->SetFont('Arial','',10);
                
                
                
                        $pdf->Ln(10);
                        $pdf->Cell(30,10, 'Order : '.$orderObj->systerm_order_id);
                        
                        $pdf->Ln(5);
                        $pdf->Cell(30,10, 'Invoice : '.$inVoiceId);
                
                
                        $pdf->Ln(5);
                        $pdf->Cell(30,10, 'Order Date : '.date("Y-m-d H:i:s"));
		
                        $pdf->SetFont('Arial','B',10);
                
                        $pdf->Ln(15);
                        $pdf->SetFillColor(237,235,235);
                        $pdf->cell(103 ,10,"Sold to",1,0,'L',true);
                        $pdf->cell(103 ,10,"Ship to",1,0,'L',true);
                        $pdf->Ln();
                
                        $x=$pdf->GetX();
                        $y=$pdf->GetY();
                        $pdf->SetFont('Arial','',9);

                        $bname = $orderObj->b_name .  ' ' . $orderObj->b_lname ; 
                        $badd = $orderObj->b_address1 .  ' ' . $orderObj->b_address2 ;
                        $teleBe = $orderObj->b_phone;
                        $emailBe = $orderObj->b_email;

                        $pdf->MultiCell(103, 6, "$bname\n$badd\nT:$teleBe", 1, 1);

                        $pdf->SetXY($x+103, $y);


                        $dName = $orderObj->name .  ' ' . $orderObj->lname ; 
                        $address = $orderObj->address1 .  ' ' . $orderObj->address2 ;
                        $tele = $orderObj->phone;



                        $pdf->MultiCell(103, 6, "$dName\n$address\nT:$tele", 1, 1);


                        $pdf->SetFont('Arial','B',10);

                        $pdf->Ln(15);
                        $pdf->SetFillColor(237,235,235);
                        $pdf->cell(206 ,10,"Payment Method",1,0,'L',true);
                        $pdf->Ln();

                        $x=$pdf->GetX();
                        $y=$pdf->GetY();

                        $pdf->SetFont('Arial','',9);

                        if($orderObj->pay_type == 1) { 
                            $pType = Controller_App::ONE;
                        }elseif($orderObj->pay_type == 2) { 
                            $pType = Controller_App::TWO;
                        }elseif($orderObj->pay_type == 3) {
                            $pType = Controller_App::THREE;
                        }


                        $pdf->MultiCell(206, 6, $pType, 1, 1);







                        $pdf->Ln(16);
                        $pdf->SetFont('Arial','B',9);

                        $pdf->Cell(105,7,'Products',1);
                        $pdf->Cell(30,7,'Order Qty',1);
                        $pdf->Cell(30,7,'@ (Rs)',1);
                        $pdf->Cell(40,7,'Total (Rs)',1 , 0 , 'R');

                        $pdf->Ln();
                        
                        
                         $bookOrderAll = ORM::factory('Bookorder')->where('orders_id' , '=' , $orderId)->find_all() ;
                        
                         foreach($bookOrderAll as $bookObj) { 
                    
                           
                            $invoiceObj = ORM::factory('Invoice') ;
                            $invoiceObj->invoiceorder_id = $invoiceorderId ;
                            $invoiceObj->bookorder_id = $bookObj->bookorder_id;
                            $invoiceObj->ship_con =$bookObj->number_of_books;
                            $invoiceTableId = $invoiceObj->save();
                            
                            //reduce quan
                            
                            $bookMainObj = ORM::factory('Bookmain' , $bookObj->bookmain_id) ;
                            
                            if($bookObj->btype == 'M'){
                                $bookMainObj->stock = $bookMainObj->stock - $bookObj->number_of_books;
                            }else {
                                $bookMainObj->gstock = $bookMainObj->gstock - $bookObj->number_of_books;
                            }
                            
                            $bookMainObj->save();
                            
                            
                            $pdf->SetFont('Arial','B',8);
                            
                            
                            $name = $bookMainObj->name;
			
                            if(strlen($name) > 20){
                                    $bName =  substr($name, 0, 40) . ' .....';
                            }else{
                                    $bName =  $name;
                            }
			
                       
			
                            $pdf->Cell(105,7, $bName ,1);
                            $pdf->Cell(30,7,$bookObj->number_of_books,1);
                            $pdf->Cell(30,7,   Controller_App::action_price($bookObj->book_prize),1);
                            $pdf->Cell(40,7, Controller_App::action_price($bookObj->book_prize * $bookObj->number_of_books) ,1 ,0 , 'R');
                            $pdf->Ln();
                            
                           
                    
                         }
                         
                         
                        $pdf->Ln(4);
                        $pdf->SetFont('Arial','B',8);
                        $pdf->Cell(105,7,''  ,0);
                        $pdf->Cell(30,7, '',0);
                        $pdf->Cell(30,7,'Delivery charges : ' , 0,0 , 'R');
                        $pdf->Cell(40,7, Controller_App::action_price(Session::instance()->get('BCOST')) , 0 ,0 , 'R');

                
 		
                        $pdf->Ln(4);

                        $pdf->Cell(105,7,''  ,0);
                        $pdf->Cell(30,7, '',0);
                        $pdf->Cell(30,7,'' , 0);
                        $pdf->Cell(40,7,'........................'  ,0 , 0 , 'R');

                        $pdf->Ln(4);

                        $pdf->Cell(105,7,''  ,0);
                        $pdf->Cell(30,7, '',0);
                        $pdf->Cell(30,7,'Total Amount :' , 0,0 , 'R');
                        $pdf->Cell(40,7,   Controller_App::action_price(Session::instance()->get('FAMOUT'))  ,0 , 0 , 'R');


                        $pdf->Ln(4);

                        $pdf->Cell(105,7,''  ,0);
                        $pdf->Cell(30,7, '',0);
                        $pdf->Cell(30,7,'' , 0);
                        $pdf->Cell(40,7,'........................'  ,0 , 0 , 'R');

                        $pdf->Ln(3);

                        $pdf->Cell(105,7,''  ,0);
                        $pdf->Cell(30,7, '',0);
                        $pdf->Cell(30,7,'' , 0);
                        $pdf->Cell(40,7,'........................'  ,0 , 0 , 'R');

                        $attachdata[] =   $pdf->Output($inVoiceId . '.pdf' , 'S');    
                        
                        
                        

                                
                    
                }
                
               
                
                
                if($gType == 1) {
                    
                    $pdfPt = Controller_App::ONE;
                    $payMethod = 'You have chosen the Credit card option. Your order will be ready for delivery or pick up as soon as we receive your payment confirmation from the credit card processor. Thereafter we will deliver the book or email you  a Pickup note (depending on the delivery option you have chosen).';
                    
                }else if($gType == 2){
                    
                    $pdfPt = Controller_App::TWO;
                    $payMethod = 'You have chosen the Credit card option. Your order will be ready for delivery or pick up as soon as we receive your payment confirmation from the credit card processor. Thereafter we will deliver the book or email you  a Pickup note (depending on the delivery option you have chosen).';
                    
                }else if($gType == 4){
                    
                    $pdfPt =Controller_App::FOUR;
                    $payMethod = 'Please pay cash on receipt of your order.';
                    
                    
                }else if($gType == 5){
                    
                    
                    $pdfPt =Controller_App::FIVE;
                    $payMethod = "You have chosen the 'direct bank deposit' payment option. Please ensure that your purchase order ref $orderValue is stated on your bank deposit slip. Once payment is made send an email. Your order will be processed and ready for delivery once we receive your payment confirmation from our bank. <br/><br/>

Please note that the stock of the book/s you ordered is limited. Verifying bank deposits takes time and may result in the books sold before you get your payment confirmation. The best way of ensuring you receive the book you want is to pay online by credit card. 
				
Please deposit the payment to any branch of Pan Asia Bank. <br/><br/>
				Name of Acc: Makeen Books (Pvt) Ltd<br/>
				Acc No: 033233050119";
                }
                
                $dCost = Controller_App::action_price(Session::instance()->get('BCOST'));
                $tPr  = Controller_App::action_price(Session::instance()->get('TPRODUCT'));
                $fAmount  = Controller_App::action_price(Session::instance()->get('FAMOUT'));
                
                $bookHtml = '<table border="1" cellpadding="0" cellspacing="0" width="600px" style="border:#EAEAEA 1px solid;" >
                <thead>
                  <tr bgcolor="#EAEAEA">
                    <th width="150" align="left" valign="middle"><strong>Product</strong></th>
                    <th width="200" align="left" valign="middle"><strong>Delivery</strong></th>
                    <th width="150" align="left" valign="middle"><strong>Unit price</strong></th>
                    <th width="150" align="left" valign="middle"><strong>Qty</strong></th>
                    <th width="150" align="left" valign="middle"><strong>Total</strong></th>
                  </tr>
                </thead>' . $pHtml . '<tr>
                  <td align="left" valign="middle">&nbsp;</td>
                  <td align="left" valign="middle">&nbsp;</td>
                  <td align="left" valign="middle">&nbsp;</td>
                  <td align="left" valign="middle"><strong>Delivery Charges</strong></td>
                  <td align="left" valign="middle">' . $dCost . '</td>
                </tr>
                <tr>
                  <td align="left" valign="middle">&nbsp;</td>
                  <td align="left" valign="middle">&nbsp;</td>
                  <td align="left" valign="middle">&nbsp;</td>
                  <td align="left" valign="middle"><strong>Total Products</strong></td>
                  <td align="left" valign="middle">'. $tPr .'</td>
                </tr>
                <tr>
                  <td align="left" valign="middle">&nbsp;</td>
                  <td align="left" valign="middle">&nbsp;</td>
                  <td align="left" valign="middle">&nbsp;</td>
                  <td align="left" valign="middle"><strong>Grand Total</strong></td>
                  <td align="left" valign="middle">'.$fAmount.'</td>
                </tr></tbody></table>';

                 
                $bAdderess = $orderObj->b_name .  ' ' . $orderObj->b_lname  . '<br/>' . $orderObj->b_address1 . '<br/>' . $orderObj->b_address2 . '<br/>' . $orderObj->b_phone . '<br/>' . $orderObj->b_email;


                $dAdderess = $orderObj->name .  ' ' . $orderObj->lname  . '<br/>' . $orderObj->address1 . '<br/>' . $orderObj->address2 . '<br/>' . $orderObj->phone ;


                $pMethod = $pdfPt;

                if(Session::instance()->get('BCOST')){

                    $ddCost = $dCost;

                }else{

                    $ddCost = 'Free';

                }
               


           
                $bodyCon  = "Thank you for your order from Makeen Books. If you have any questions about your order please contact us at info@makeenbooks.com.
                    <br/>Your Order " . $orderObj->systerm_order_id . "<br/><br/>

                    <table width='600px' border='0' cellspacing='0' cellpadding='0'>
                      <tr align='left' bgcolor='#EAEAEA'>
                        <td width='280' align='left' valign='top' style='padding:7px 9px 9px 9px; border-left:1px solid #EAEAEA;border-bottom:1px solid #EAEAEA;border-right:1px solid #EAEAEA;'><strong>Billing Information</strong></td>
                        <td width='40' align='left' valign='top' bgcolor='#FFFFFF'>&nbsp;</td>
                        <td width='280' align='left' valign='top' style='padding:7px 9px 9px 9px; border-left:1px solid #EAEAEA;border-bottom:1px solid #EAEAEA;border-right:1px solid #EAEAEA;'><strong>Payment Method</strong></td>
                      </tr>
                      <tr>
                        <td align='left' valign='top' style='padding:7px 9px 9px 9px; border-left:1px solid #EAEAEA;border-bottom:1px solid #EAEAEA;border-right:1px solid #EAEAEA;'>
                        $bAdderess
                        </td>
                        <td align='left' valign='top' style='' bgcolor='#FFFFFF'>&nbsp;</td>
                        <td align='left' valign='top' style='padding:7px 9px 9px 9px; border-left:1px solid #EAEAEA;border-bottom:1px solid #EAEAEA;border-right:1px solid #EAEAEA;'>$pMethod</td>
                      </tr>
                    </table><br/><br/><table width='600px' border='0' cellspacing='0' cellpadding='0'>
                      <tr align='left' bgcolor='#EAEAEA'>
                        <td width='280' align='left' valign='top' style='padding:7px 9px 9px 9px; border-left:1px solid #EAEAEA;border-bottom:1px solid #EAEAEA;border-right:1px solid #EAEAEA;'><strong>Shipping Information</strong></td>
                        <td width='40' align='left' valign='top' bgcolor='#FFFFFF'>&nbsp;</td>
                        <td width='280' align='left' valign='top' style='padding:7px 9px 9px 9px; border-left:1px solid #EAEAEA;border-bottom:1px solid #EAEAEA;border-right:1px solid #EAEAEA;'><strong>Shipping Method</strong></td>
                      </tr>
                      <tr>
                        <td align='left' valign='top' style='padding:7px 9px 9px 9px; border-left:1px solid #EAEAEA;border-bottom:1px solid #EAEAEA;border-right:1px solid #EAEAEA;'>
                        $dAdderess
                        </td>
                        <td align='left' valign='top'  bgcolor='#FFFFFF'>&nbsp;</td>
                        <td align='left' valign='top' style='padding:7px 9px 9px 9px; border-left:1px solid #EAEAEA;border-bottom:1px solid #EAEAEA;border-right:1px solid #EAEAEA;'>Delivery :  $ddCost</td>
                      </tr>
                    </table><br/><br/>"
                        . $bookHtml 
                        . '<br/><br/>'
                        . $payMethod;

                
                $subject = "Your Order with makeenbooks.com  [Order Number:$orderValue]";

                $eData['name'] = $fName;
                $eData['ebody'] =   $bodyCon . self::MAILFOOT; 

                $eBody = View::factory('site/email' , $eData); 
                                                    
                                
                $mailObj = ORM::factory('Siteemails' , 3);
                                
                $fromEmail = $mailObj->email;
                $fromName = $mailObj->name	;
				
		//send order email to cus	
                
                
                if($gType == 1 || $gType == 2){
                        Controller_User::action_send_email($eBody,$uEmail , $fromEmail, $fromName, $subject , $attachdata , $orderValue);
                }else{
                        Controller_User::action_send_email($eBody, $uEmail, $fromEmail, $fromName, $subject);
                }
                                
                
                //send order email to admin
                
                $subjectAdmin = "New Order [Order Number:$orderValue]";
                        
                
               Controller_User::action_send_email($eBody, $fromEmail, $fromEmail, $fromName, $subjectAdmin);
      
                
                 
                Session::instance()->delete('CARTARRAY');
                 
               
                
               
               
		       $data['seoNo'] = TRUE; 
                
                
                $view = View::factory('site/index');
                $view->ptype = 'DELICERYUSER';
                $view->pBody = View::factory('site/paydone' , $data);
                $this->response->body($view);
	}
        
        
        public function action_log_in()
	{
            
                
		
                //check error
                
                $data['error'] = NULL;
                if(trim($this->request->param('id'))){
                    $data['error'] = trim($this->request->param('id'));
                }
                
                $data['messageType'] = 2;
                
          
                $view = View::factory('site/index');
                $view->ptype = 'LOGIN';
                $view->pBody = View::factory('site/log_in' , $data);
                $this->response->body($view);
	}
        
        public function action_forgot_your_password()
	{       
                $data = NULL;
             
                
               
               
		
                
                $data['error'] = NULL;
                if(trim($this->request->param('id'))){
                    $data['error'] = trim($this->request->param('id'));
                }
                
                
                $view = View::factory('site/index');
                $view->ptype = 'FORGOTPASS';
                $view->pBody = View::factory('site/forgot_your_password' , $data);
                $this->response->body($view);
	}
        
        
        public function action_forgot_your_password_send()
	{
		
		$uName = trim($_POST['UserName']);
		
			$user = ORM::factory('Userinfo')->where('userinfo_username', '=', $uName)->find();
			if ($user->loaded()){
				
				$str = Text::random('hexdec' , 6); 
				$user->userinfo_pwd = $str;
				$user->save();
				
				$name = $user->bookshop->bookshop_name;
                                 
                $bodyCon = "The password for your Account - $str - was recently changed. If you made this change, you don't need to do anything more. 
                <br/>
 To get back into your account, <a href='http://makeenbooks.com/User/log_in'>click here</a>";

                
                $eData['name'] = $name;
                $eData['ebody'] =   $bodyCon . self::MAILFOOT;      
                $subject    = 'Forgot your Password';

               $eBody = View::factory('site/email' , $eData);              

            
                                
                $toEmail = $user->userinfo_username;
                                
                                
                $mailObj = ORM::factory('Siteemails' , 1);
                                
                $fromEmail = $mailObj->email;
				$fromName = $mailObj->name	;
				
				
                                
                Controller_User::action_send_email($eBody, $toEmail, $fromEmail, $fromName, $subject);
				
				HTTP::redirect(URL::base(TRUE) . 'User/forgot_your_password/2');
						
				
			}else{
				
				HTTP::redirect(URL::base(TRUE) . 'User/forgot_your_password/1');
				
			}
		
	}
	
        
         public function action_logout()
         {
             
             Session::instance()->destroy();
             HTTP::redirect(URL::base(TRUE));
         }
		 
		 
		 
        public  static function  action_send_email($body , $toEmail , $fromEmail , $fromName ,    $subject , $attachdata = NULL , $oId = NULL)
	{
		
		$mail             = new Model_PHPMailer(true);
		$mail->IsSMTP(); 
		$mail->Host       = Controller_Admin::HOST; 
		$mail->SMTPAuth   = true; 
		$mail->Port       =Controller_Admin::PORT;             
		$mail->Username   = Controller_Admin::USERNAME;
		$mail->Password   =  Controller_Admin::PASSWORD;        
		$mail->SetFrom($fromEmail, 'makeenbooks.com');
		$mail->AddReplyTo($fromEmail ,$fromName);
		$mail->Subject    = $subject;
		$mail->IsHTML(true);

		$mail->AltBody   = $body  ;
                
                
                if($attachdata){
                    foreach($attachdata as $tchData=>$valueData){
                        $mail->AddStringAttachment($valueData, $oId .'.pdf');
                    }
                }


		$mail->MsgHTML($body);
		$address = $toEmail ;
		$mail->AddAddress($address);
		$mail->Send();
		
		
	}
        
        
        

} // End Welcome
