<?php

class AdminController extends baseController {
    function index() {
		//		echo "admin " . rand();
		//		exit; 
        global $website_options;

        //$this->platformDump();

        //$store_model                = new storeModel();
        $category_model          	= new categoryModel();
        $projectModel              	= new projectModel();
        //$paymentModel            	= new paymentModel();
        $pageModel                  = new pageModel();
        $userModel                  = new userModel();
        $portfolioModel            	= new portfolioModel();
        //$ordersModel              = new ordersModel();
        $testimonialModel         	= new testimonialModel();
        $logosModel                 = new logosModel();
        //$jets                     = new jetModel();
        //$eventsmainModel         	= new eventsmainModel();
        //$eventsModel              = new eventsModel();
        //$eventsotherModel        	= new eventsotherModel();
        //$mdealsModel              = new mdealsModel();
        //$rewardsModel             = new rewardsModel();
        //$specialsModel            = new specialsModel();
        //$formModel                = new formModel();
        //$remindersModel          	= new remindersModel();
        //$promocodeModel           = new promocodeModel();
        //$soptionsModel            = new soptionsModel();
        //$squarecategoryModel  	= new squarecategoryModel();
        //$squarelocationsModel     = new squarelocationsModel();
        //$squarexproductsModel     = new squarexproductsModel();
        //$locationsModel           = new locationsModel();
        //$sconfigModel             = new sconfigModel();
        //$ordrsModel               = new ordrsModel();
        $squareusersModel         	= new squareusersModel();
        //$squarevariationsModel   	= new squarevariationsModel();
		//$squaremodifierlistsModel = new squaremodifierlistsModel();
        //$tableModel        		= new tableModel();
		//$ticketsModel 			= new ticketsModel();	
		//$messagesModel			= new messagesModel();
		//$menusModel				= new menusModel();
		//$servicesModel			= new servicesModel();
		//$challengeModel 			= new challengeModel();
		//$seriesModel				= new seriesModel();
		//$setsModel 				= new setsModel();
		$questionsModel 			= new questionsModel();
		$subscribersModel			= new $subscribersModel();
		
//        if (isset($_GET['saveForm'])) {
//            if ($formModel->update($_POST['formData'])) {
//                echo 'ok';
//            }
//            exit;
//        }
//        
//        if (isset($_GET['loadFormRecords'])) {
//            $records = $formModel->getSubmissions();
//            require('views/admin/forms/loadFormRecords.tpl.php');
//            exit;
//        }
//        
//        if (isset($_GET['deleteFormRecords'])) {
//            if ($formModel->deleteSubmissions()) {
//                echo 'ok';
//            }
//            exit;
//        }
        
//        $form = $formModel->get();
            
        /*      
        if (isset($_POST['jet'])) {
            if ($_POST['jet'] == 'add_plane')
                $jets->addPlane($_POST);
            if ($_POST['jet'] == 'add_trip')
                $jets->addTrip($_POST);
            if ($_POST['jet'] == 'add_carrier')
                $jets->addCarrier($_POST);
            if ($_POST['jet'] == 'add_seat')
                $jets->addSeat($_POST);
                
            if ($_FILES) {
                $jets->import(file_get_contents($_FILES['import']['tmp_name']));
            }
        }
    
        if (isset($_GET['jet'])) {
            if (isset($_GET['deleteTrip'])) 
                $jets->deleteTrip($_GET['deleteTrip']);
            if (isset($_GET['deleteCarrier'])) 
                $jets->deleteCarrier($_GET['deleteCarrier']);
            if (isset($_GET['deletePlane'])) 
                $jets->deletePlane($_GET['deletePlane']);
            if (isset($_GET['deleteSeat'])) 
                $jets->deleteSeat($_GET['deleteSeat']);
                
            if (isset($_GET['viewTrip'])) {
                $trip = $jets->getTrips(['id' => $_GET['viewTrip']]);

                require('views/admin/jet/view_trip.tpl.php');
                exit;
            }
        }
        */
        
        //$jet_planes = $jets->getPlanes();
        //$jet_trips = $jets->getTrips();
       // $jet_carriers = $jets->getCarriers();
       // $jet_seats = $jets->getSeats();
                
        if (!$_SESSION['user']['is_admin']) {
            header("Location: /auth/logout");
            exit;
        }
        
//        if (isset($_GET['test'])) {
//            require('views/_header.tpl.php');
//            //require('views/admin/jets-tab.tpl.php');
//            require('views/_footer.tpl.php');
//            exit;
//        }

        $pages = $pageModel->getList();     

        if (isset($_GET['project_cat'])) {
            if (isset($_GET['edit']) || isset($_GET['add'])) {
                $this->editProjectCat();
                exit;
            }
            if (isset($_GET['delete'])) {
                $category_model->deleteCategory($_GET['delete']);
                header('Location: /admin/');
                exit;
            }
        }

        if (isset($_GET['user'])) {
            if (isset($_GET['edit']) || isset($_GET['add'])) {
                $this->editUser(); // Line 599
                exit;
            }
            if (isset($_GET['delete'])) {
                $userModel->deleteUser($_GET['delete']);
                header('Location: /admin/');
                exit;
            }           
        }   
        
        if (isset($_GET['tes'])) {
            if (isset($_GET['edit']) || isset($_GET['add'])) {
                $this->editTestimonial();
                exit;
            }
            if (isset($_GET['delete'])) {
                $testimonialModel->deleteTestimonial($_GET['delete']);
                header('Location: /admin/');
                exit;
            }           
        }   

        if (isset($_GET['logo'])) {
            if (isset($_GET['edit']) || isset($_GET['add'])) {
                $this->editLogo();
                exit;
            }
            if (isset($_GET['delete'])) {
                $logosModel->deleteLogo($_GET['delete']);
                header('Location: /admin/');
                exit;
            }           
        }         
        
        if (isset($_GET['uid'])) {
            if (isset($_GET['delete'])) {
                $userModel->deleteUser($_GET['delete']);
                header('Location: /admin/');
                exit;
            }           
        }                        

        if (isset($_GET['edit'])) {
            $this->edit();
            exit;
        }                        
        
        $projects = $projectModel->getList(['category_id' => $cat_id]);
        
        /*
        $db   = Mysql::getInstance();
        $opts = $db->select("website_options");
        
        $website_options = [];
        foreach ($opts as $opt)
            $website_options[$opt['name']] = $opt['value'];
        */
        
//        $total_store_spent = $store_model->getTotalCreditsSpent();
//        $total_points_purchased = $paymentModel->getTotalPointsPurchased();
//        $total_points_cost = $paymentModel->getTotalAmountPurchased();       

        if (isset($_GET['delete'])) {
            $projectModel->delete((int)$_GET['delete']);
            header("Location: ?");
            exit;
        }
        
		if (isset($_GET['portfolio'])) {
			$portfolioModel->savePictures($_POST);
			header('Location: /admin/');
			exit;
		}

		if (isset($_GET['portfolioDeleteFile'])) {
			$portfolioModel->deleteFile((int)$_GET['portfolioDeleteFile']);
			header('Location: /admin/');
			exit;
		}

//        if (isset($_GET['setFeatured'])) {
//            if (is_numeric($_POST['flag'])) {
//                if ($_POST['featured'] == 'true') {
//                    $projectModel->setFeaturedFlag((int)$_POST['id'], $_POST['flag']);
//                } else {
//                    $projectModel->unsetFeaturedFlag((int)$_POST['id'], $_POST['flag']);
//                }
//            }
//            die('ok');
//        }
        
        //$categories = $category_model->getList();

        $categories         = $category_model->getCategories();
        $testimonials       = $testimonialModel->getList();
        $logos              = $logosModel->getList();
        $square_users       = $squareusersModel->getList();
		//$tickets 			= $ticketsModel->getList();	
        
        $inactive_users = $userModel->getList();
        //$inactive_users = $userModel->getList(['is_activated' => 0]);
        //$all_users = $userModel->getAllUsers();
        $featured_accounts = $userModel->getFeaturedAccounts();
        $portfolio_entries = $portfolioModel->getList();
        
		if (isset($_GET['tab'])) {
			$tabs = ['welcome','settings','testimonials','managelogos','featuredcontent','blogcategories','managepages','manageusers','portfolio','app-tab'];
            
            if (in_array($_GET['tab'], $tabs)) {
                $tab = $_GET['tab'];
                ini_set('display_errors', 1);
                require("views/admin/tabs/$tab.tpl.php");
                exit;
            }
            
            die('tab not found');
        }
        
        require('views/admin/index.tpl.php');
    }
    
	/////////////////////////////////////////////////////////
	///   START OF EDIT PAGES & SEPARATE PAGES IS HERE    ///
	/////////////////////////////////////////////////////////
	
	// MAIN DASH WITH ALL THE INDIVIDUAL EDIT BUTTONS
	function dash(){
    	if (!$_SESSION['user_id'] && !$_SESSION['user']['is_admin']) {
    		header("Location: /auth/login");
    		exit;
    	}
		
		require('views/admin/dash.tpl.php');		
	}
	
	function subscribers(){
		if (!$_SESSION['user_id'] && !$_SESSION['user']['is_admin']
		|| !$_SESSION['user_id'] && !$_SESSION['user']['is_admin']==2) {
			header("Location: /auth/login");
			exit;
		}

		$subscribersModel   = new $subscribersModel();
		$subscribers           = $subscribersModel->getList();

		require('views/admin/subscribers.tpl.php');
	}	
	
	function faqs(){
		if (!$_SESSION['user_id'] && !$_SESSION['user']['is_admin'] 
			|| !$_SESSION['user_id'] && !$_SESSION['user']['is_admin']==2) {
    		header("Location: /auth/login");
    		exit;
    	}
    	
		$faqsModel = new faqsModel();
    	
		if (isset($_GET['faq'])) {
			if (isset($_GET['edit']) || isset($_GET['add'])) {
				$this->editFAQ();
				exit;
			}
			if (isset($_GET['delete'])) {
				$faqsModel->delete($_GET['delete']);
				header('Location: /admin/faqs');
				exit;
			}
		} 
    	
		$faqs = $faqsModel->getAllFAQs();
		
		require('views/admin/faqs.tpl.php');		
	}	
	
	function portfolio(){
		if (!$_SESSION['user_id'] && !$_SESSION['user']['is_admin'] 
			|| !$_SESSION['user_id'] && !$_SESSION['user']['is_admin']==2) {
    		header("Location: /auth/login");
    		exit;
    	}
    	
		$portfolioModel = new portfolioModel();
		$userModel     = new userModel();
		$projectModel  = new projectModel();
		$uploadsModel   = new uploadsModel();
		
		if ($_POST) {
			//echo "Saving...";
			$portfolioModel->savePictures($_POST);
			header('Location: /admin/portfolio');
			exit;
		}

		if (isset($_GET['portfolioDeleteFile'])) {
			$portfolioModel->deleteFile((int)$_GET['portfolioDeleteFile']);
			header('Location: /admin/portfolio');
			exit;
		}
    	
		$portfolio_entries      = $portfolioModel->getList();
		
		require('views/admin/portfolio.tpl.php');		
	}
		
	// TRIVIA PAGES
	function sets(){
		if (!$_SESSION['user_id'] && !$_SESSION['user']['is_admin'] 
			|| !$_SESSION['user_id'] && !$_SESSION['user']['is_admin']==2) {
    		header("Location: /auth/login");
    		exit;
    	}
    	
		$setsModel	= new setsModel();
		$sets    	= $setsModel->getList();
		
		require('views/admin/sets.tpl.php');		
	}
	
	function series(){
		if (!$_SESSION['user_id'] && !$_SESSION['user']['is_admin'] 
			|| !$_SESSION['user_id'] && !$_SESSION['user']['is_admin']==2) {
    		header("Location: /auth/login");
    		exit;
    	}
    	
		$seriesModel = new seriesModel();
		$series    	 = $seriesModel->getList();
		
		require('views/admin/series.tpl.php');		
	}
	// TRIVIA PAGES ENDS
	
	function tickets(){
		if (!$_SESSION['user_id'] && !$_SESSION['user']['is_admin'] 
			|| !$_SESSION['user_id'] && !$_SESSION['user']['is_admin']==2) {
    		header("Location: /auth/login");
    		exit;
    	}
    	
		$ticketsModel        = new ticketsModel();
		$tickets        = $ticketsModel->getList();
		
		require('views/admin/tickets.tpl.php');		
	}	    
	
	function promocodes(){
		if (!$_SESSION['user_id'] && !$_SESSION['user']['is_admin'] 
			|| !$_SESSION['user_id'] && !$_SESSION['user']['is_admin']==2) {
    		header("Location: /auth/login");
    		exit;
    	}
    	
    	$promocodeModel        = new promocodeModel();
    	$promocodes          = $promocodeModel->getList();
		
		require('views/admin/promocodes.tpl.php');		
	}	  
	
	function tables(){
    	if (!$_SESSION['user_id'] && !$_SESSION['user']['is_admin']) {
    		header("Location: /auth/login");
    		exit;
    	}
    	
    	$tableModel = new tableModel();
    	$tables          = $tableModel->getList();
		
		require('views/admin/tables.tpl.php');		
	}	  
	
	function submissions(){

		if (!$_SESSION['user']['is_admin']) {
			header("Location: /auth/logout");
			exit;
		}

		$formsModel = new formsModel();
		$submissions = $formsModel->getList();

		require('views/admin/submissions.tpl.php');
	}   			
	
	function notifications(){

		if (!$_SESSION['user']['is_admin']) {
			header("Location: /auth/logout");
			exit;
		}

		$messagesModel = new messagesModel();
		$notifications = $messagesModel->getNotifications();

		require('views/admin/notifications.tpl.php');
	}   
	
	function menus(){

		if (!$_SESSION['user']['is_admin']) {
			header("Location: /auth/logout");
			exit;
		}

		$menusModel = new menusModel();
		$menus = $menusModel->getList();

		require('views/admin/menus.tpl.php');
	}   
	
	function reminders(){
		if (!$_SESSION['user_id'] && !$_SESSION['user']['is_admin'] 
			|| !$_SESSION['user_id'] && !$_SESSION['user']['is_admin']==2) {
    		header("Location: /auth/login");
    		exit;
    	}
    	
		$remindersModel = new remindersModel();
		$reminders      = $remindersModel->getList();
		
		require('views/admin/reminders.tpl.php');		
	}		
	
	function services(){
		if (!$_SESSION['user_id'] && !$_SESSION['user']['is_admin'] 
			|| !$_SESSION['user_id'] && !$_SESSION['user']['is_admin']==2) {
    		header("Location: /auth/login");
    		exit;
    	}
    	
		$servicesModel = new servicesModel();
    	
		if (isset($_GET['service'])) {
			if (isset($_GET['edit']) || isset($_GET['add'])) {
				$this->editService();
				exit;
			}
			if (isset($_GET['delete'])) {
				$servicesModel->delete($_GET['delete']);
				header('Location: /admin/services');
				exit;
			}
		} 
    	
		$services      = $servicesModel->getList();
		
		require('views/admin/services.tpl.php');		
	}		
	
	function accounts(){
		if (!$_SESSION['user_id'] && !$_SESSION['user']['is_admin'] 
			|| !$_SESSION['user_id'] && !$_SESSION['user']['is_admin']==2) {
    		header("Location: /auth/login");
    		exit;
    	}
    	
		$accountsModel = new accountsModel();
    	
		if (isset($_GET['account'])) {
			if (isset($_GET['edit']) || isset($_GET['add'])) {
				$this->editAccount();
				exit;
			}
			if (isset($_GET['del'])) {
				$accountsModel->delete($_GET['del']);
				header('Location: /admin/accounts');
				exit;
			}
		} 
    	
		$accounts = $accountsModel->getList();
		
		require('views/admin/accounts.tpl.php');		
	}		
	
	function users(){
		if (!$_SESSION['user_id'] && !$_SESSION['user']['is_admin'] == 1) {
			header("Location: /auth/login");
			exit;
		}
		
		$squareusersModel = new squareusersModel();
		
		if (isset($_GET['delete'])) {
			//echo "Yes! " . $_GET['delete'];
			$squareusersModel->deleteSquareUser($_GET['delete']);
			header('Location: /admin/users');
			exit;
		}

		if ($_POST) {	
			$search["search"] = $_POST["search"];
			// should I just detect the is_admin ==  here and then do a new condition for is_super? okay
			//$search["is_admin"]=$_POST["is_admin"]; // leave this?
			if(!empty($_POST["usertype"])){
				$search["usertype"]=$_POST["usertype"];
			}

			if(!empty($_POST["is_admin"]) && $_POST["is_admin"] == 1){
				$search["is_admin"]=$_POST["is_admin"]; 
			}
			
			if(!empty($_POST["permissions"]) && $_POST["permissions"] > 0){
				$search["permissions"]=$_POST["permissions"]; 
			}			
			
//			if ($_SESSION['logged_in'] && $_SESSION['user']['is_admin']) {
//				$search["ihpadmin"] = 1;
//			} 
			//print_r($search);

			$users = $squareusersModel->getList($search);

			require('views/admin/users.tpl.php');
		} else {
			if (!$_SESSION['user']['is_admin'] == 1) {
				header("Location: /auth/login");
				exit;				
			} else {
//				$num_results_on_page = 50;
//				if ($_GET["page"] && is_numeric($_GET["page"])) {
//					$inactive_users = $userModel->paginateUsers($_GET["page"], $num_results_on_page);
//				} else {
//					$inactive_users = $userModel->paginateUsers(1, $num_results_on_page);
//				}
//				$total_pages = $userModel->TotalUsers();
				// print_r($users);
				$users = $squareusersModel->getList();
				require('views/admin/users.tpl.php');				
			}
		}
	}	
	
	function orders(){
		if (!$_SESSION['user_id'] && !$_SESSION['user']['is_admin'] == 1) {
			header("Location: /auth/login");
			exit;
		}
		$ordrsModel = new ordrsModel();
		$promo_codes = $ordrsModel->getPromoCodes();
		
		//$_POST["orderid"] = "ZfUGjv8Un74Q6kjLoM5zkWtndoaZY";

		if ($_POST) {	
			if(!empty($_POST["promo_code"])){
				$search["promo_code"]=$_POST["promo_code"];
			}
			//print_r($search);
			if(isset($_POST['but_update'])){

			  if(isset($_POST['update'])){
			    foreach($_POST['update'] as $updateid){
			    	//echo "Order ID: " . $updateid . "<br />";
			    	$ordrsModel->setasPaid($updateid); 
			    }
			  }

			}				
			$ordrs = $ordrsModel->getList($search); 
			//$ordrs = $ordrsModel->getList($search); 
			//print_r($_POST);
			//$_POST["orderid"] = "ZfUGjv8Un74Q6kjLoM5zkWtndoaZY";
			//$ordr = $ordrsModel->getOrdr($_POST["orderid"]);
			
			//echo "POST";
			//print_r($ordr);

			require('views/admin/orders.tpl.php');
		} else {

//				$num_results_on_page = 50;
//				if ($_GET["page"] && is_numeric($_GET["page"])) {
//					$inactive_users = $userModel->paginateUsers($_GET["page"], $num_results_on_page);
//				} else {
//					$inactive_users = $userModel->paginateUsers(1, $num_results_on_page);
//				}
//				$total_pages = $userModel->TotalUsers();
				// print_r($users);
				$ordrs = $ordrsModel->getList(); 
				require('views/admin/orders.tpl.php');				
		}
	}		
	
	function markasReady(){
		if (isset($_POST['oid']) && !empty($_POST['oid'])) {
			$orderid = $_POST['oid'];
		} else {
			exit;
		} 	
		$ordrsModel = new ordrsModel();
		
		$ordrsModel->markasReady($orderid);
		
		die('ok');
			
	}
	
	function setasFulfilled(){
		if (isset($_POST['oid']) && !empty($_POST['oid'])) {
			$orderid = $_POST['oid'];
		} else {
			exit;
		} 	
		$ordrsModel = new ordrsModel();
		$ordrsModel->setasFulfilled($orderid);
		
		die('ok');
			
	}	
	
    function getOrderDetails()
    {
        if(isset($_POST['orderid']) && !empty($_POST['orderid'])){
            $orderid = $_POST['orderid'];
        } else {
            exit;
        } 
        //$db = Mysql::getInstance();
        //$oid = $db->where("id = ?", $orderid)
                         // ->select_one("square_orders");
                          //->select_one("promo_codes", 'amount'); // this was here before, but I needed to do more stuff
		$ordrsModel = new ordrsModel();
		$oid =$ordrsModel->getTheOrder($orderid);

        if (empty($oid))
            exit;

         // TYPE 1 IS A FIXED VALUE DISCOUNT; TYPE 2 IS A PERCENTAGE DISCOUNT
         /*
        if($rid['allowed'] > $rid['claimed'] && $rid['type'] == 1){
                echo $rid['amount'];
                exit;
        } else {
                echo $rid['amount'];
                exit;
        }
        */
        
        // Remove the 'amount' parameter from the select_one if you want to group more variables and read it with result.fieldname in JQuery/Ajax
        // this is how you parse it - var result = $.parseJSON(d);
        //echo json_encode(array("type" => $rid['type'], "amount" => $rid['amount']));
        
        if($oid){
        	if(empty($oid['customer_phone'])){
        		$cust_phone = "None provided";
        	} else {
        		$cust_phone = "<a href='tel:" . $oid['customer_phone'] . "'>" . format_phone($oid['customer_phone']) . "</a>";	
        	}
        	$locationName = $ordrsModel->getLocationName($oid['location_id']);
        	$pickup_at = date('g:iA \o\n D, m/d', strtotime($oid['pickup_at']));
        	$order_total = "$" . number_format(($oid['amount']/100),2,'.',',');
        	if($oid['paid'] == 1){
        		$paid = "<span style='color:#29d030; font-weight:600;'>Yes! Cha-ching!</span>";
        	} else {
        		$paid = "Pending...";
        	}
			if ($oid['is_fulfilled'] == 1) {
				$fulfilled = "Yes";
				$status = "Complete";
			} else {
				$fulfilled = "No";
				if ($oid['status'] == 1) {
					$status = "<span style='color:#3ab500'>New!</span>"; // Order Received
				} elseif($oid['status'] == 2){
					$status = "In Progress"; // Being Prepared
				} elseif($oid['status'] == 3){
					if ($oid['delivery'] ==1) {
						$status = "Ready!"; // Ready for Delivery
					} else {
						$status = "Ready!";	 // Ready for Pickup
					}
				} elseif($oid['status'] == 4){
					$status = "Ready!";	
				} else {
					$status = "N/A";
				}				
			}		
			
            //$_SESSION['discount']     = $rid['amount'];
            //$_SESSION['entercode']  = $rid['code'];
            //$_SESSION['promo_type']  = $rid['type'];
            //unset($_SESSION['loggedin']);
            //echo $rid['amount'];
            //$html = "<div>{$oid['customer_name']}</div>";
            
			$html = "<div class='orderdetails'>
				<div class='orderdetailslabel'>
					STATUS
				</div>
				<div class='orderdetailsinfo' id='order_status' style='font-weight:600'>"
			. $status .
			"</div>
			<div class='clear'></div>
			</div>
			<div class='orderdetails'>
				<div class='orderdetailslabel'>
					CUSTOMER	
				</div>
				<div class='orderdetailsinfo'>"
					. $oid['customer_name'] .
				"</div>			
				<div class='clear'></div>
			</div>
			<div class='orderdetails'>
				<div class='orderdetailslabel'>
					CONTACT
				</div>
				<div class='orderdetailsinfo' style='line-height:28px;'>"
					 . $cust_phone . "<br />
				 	<a href='mailto:" . $oid['customer_email'] . "?subject=EMail about your Order'>" . $oid['customer_email'] . "</a>
				</div>			
				<div class='clear'></div>
			</div>		
			<div class='orderdetails'>
				<div class='orderdetailslabel'>
					LOCATION	
				</div>
				<div class='orderdetailsinfo'>"
					. $locationName .
				"</div>			
				<div class='clear'></div>
			</div>		
			<div class='orderdetails'>
				<div class='orderdetailslabel'>
					PICKUP TIME
				</div>
				<div class='orderdetailsinfo'>"
					. $pickup_at.
				"</div>			
				<div class='clear'></div>
			</div>";
//			while($row = mysqli_fetch_assoc($oid['items'])){
//				$html .= 'Item: ' . $row['name'];	
//			}
			$html .= "<div style='margin-top:10px; margin-bottom:10px;'>";
			foreach($oid['items'] as $item){
				$oitem = $item['name'];
				$imgfix = "onerror=\"this.src='/static/client/placeholder.jpg'\"";
				$price = "$" . number_format(($item['amount']/100),2,'.',',');
				$html .= '<div class="prodrow">
					<div class="thumb"><img src="'. $item['images'] . '" align="absmiddle" ' . $imgfix . ' /></div> 
				<div class="proddetails">
					<div class="proddescrip">
						<span>' . $oitem . '</span> x ' . $item['quantity'] .  '
						<div class"options" style="font-size:12px; line-height:15px; font-weight:300; margin-top:5px; color:#777">' . $item['options'] . '</div>
					</div> 
					<div class="price">' .  $price. '</div>
				</div>
				</div>';
				//$html .= 'Item: ' . $oitem . ' x ' . $item['quantity'] . '<span style="float:right">' . $item['amount'] . '<span>';
			}
			$html .= "</div>
			<br />
			<div class='orderdetails' style='font-size:16px; font-weight:600; border-top:1px solid #eee;'>
				<div class='orderdetailslabel'>
					Note
				</div>
				<div class='orderdetailsinfo' style='font-size:14px; font-weight:400; text-align:left;'>"
					. $oid['note'].
				"</div>			
				<div class='clear'></div>
			</div>							
			<div class='orderdetails' style='font-size:17px; font-weight:600;'>
				<div class='orderdetailslabel'>
					TOTAL
				</div>
				<div class='orderdetailsinfo' style='font-weight:600; text-align:right;'>"
					. $order_total.
				"</div>			
				<div class='clear'></div>
			</div>		
			<div class='orderdetails' style='font-size:14px; font-weight:600; color:#000'>
				<div class='orderdetailslabel'>
					<i class='fa fa-credit-card'></i> Paid
				</div>
				<div class='orderdetailsinfo' style='font-size:14px; font-weight:400; text-align:right;'>"
					. $paid .
				"</div>			
				<div class='clear'></div>
			</div>	
			<div class='orderdetails' style='font-size:14px; font-weight:600; color:#000'>
				<div class='orderdetailslabel'>
					Fulfilled
				</div>
				<div class='orderdetailsinfo' id='fulfilled' style='font-size:14px; font-weight:400; text-align:right;'>"
					. $fulfilled .
				"</div>			
				<div class='clear'></div>
			</div>							
			<div class='orderdetails' style='font-size:14px; font-weight:400; color:#bbb'>
				<div class='orderdetailslabel'>
					Receipt#
				</div>
				<div class='orderdetailsinfo' style='font-size:14px; font-weight:400; text-align:right;'>"
					. $oid['receipt_id'] .
				"</div>			
				<div class='clear'></div>
			</div>	
			<div class='orderdetails' style='font-size:14px; font-weight:400; color:#bbb'>
				<div class='orderdetailslabel'>
					Pmt/Tx ID
				</div>
				<div class='orderdetailsinfo' style='font-size:14px; font-weight:400; text-align:right;'>"
					. $oid['payment_id'] .
				"</div>			
				<div class='clear'></div>
			</div>							
			<br />
			<h3>Order ID:</h3>
			<input type='text' class='orderidvalue' value='" . $oid['id'] . "' placeholder='orderidvalue' readonly />
			<br /><br /><br /><br /><br /><br /><br /><br /><br />
										
			";
		            
            echo $html;
           // echo json_encode(array("customer_name"=> $oid['customer_name'],"amount"=>$oid['amount']));
            exit; // or die;
        }
    }    
    
	function items()
	{
		if (!$_SESSION['user']['is_admin'] && $_SESSION['user']['usertype'] != 'Team') {
			header("Location: /auth/keypad");
			exit;
		}
		
		$squarexproductsModel   = new squarexproductsModel();
		
		if ($_POST) {
			if (isset($_POST['outofstock_update'])) {

				if (isset($_POST['update'])) {
					//print_r($_POST['update']);
					
					foreach ($_POST['update'] as $updateid) {
						//echo "Item ID: " . $updateid . "<br />";
						$squarexproductsModel->settoOutofStock($updateid);
					}
				} 
				//$squarexproducts    	= $squarexproductsModel->getXProducts();
				//require('views/admin/items.tpl.php');				

			}
			
			if (isset($_POST['instock_update'])) {

				if (isset($_POST['update'])) {
					foreach ($_POST['update'] as $updateid) {
						//echo "Order ID: " . $updateid . "<br />";
						$squarexproductsModel->settoInStock($updateid);
					}
				}
				//$squarexproducts    	= $squarexproductsModel->getXProducts();
				//require('views/admin/items.tpl.php');

			}	
			$squarexproducts    	= $squarexproductsModel->getXProducts();

			require('views/admin/items.tpl.php');					
		} else{
			$squarexproducts    	= $squarexproductsModel->getXProducts();

			require('views/admin/items.tpl.php');			
		}			
		

	}          	
    
    function scan(){
    	if (!$_SESSION['user_id'] && !$_SESSION['user']['is_admin']) {
    		//header("Location: /auth/login");
    		//exit;
				$msg = '<img src="/static/images/not_authorized_icon.png" alt="NOT Authorized" align="absmiddle" 
								style="height:60px; padding-bottom:5px; margin-right:10px; letter-spacing:2px;"> Stop! You are not 
								permitted to access this information.
								<br /><br />If you are an Admin, please <a href="/auth/login" style="font-weight:600;">click here to login</a>
								<br /><br />';
    			require 'views/admin/scan.tpl.php';
    	}        	
    	$authModel = new authModel();
    	
		if(isset($_POST)){
			if(isset($_POST['amount_due']) && $_POST['amount_due'] > 0){
				//print_r($_POST);
				$amt = $_POST['amount_due'];
				$amt_formatted = number_format($amt,2,'.','');
				$amt_cents = $amt_formatted * 100;
				
				//echo $amt_cents;
				//exit;
				if(isset($_GET['uid'])){
					$uid = $_GET['uid'];	
				} else {
					$uid = $_POST['uid'];	
				}
				//echo $uid;
				$nb = $authModel->tenderPayment($uid,$amt_cents);
				$nbf = number_format($nb,2,'.','');
				header('Location: /admin/scan?uid='.$uid.'&msg=Payment%20Successful!&nb='.$nbf);
			} 
			
			
			//require 'views/admin/scan.tpl.php';
			//$msg = "POST...";
			//echo "before";
			
			//echo "after";
			//require 'views/admin/scan.tpl.php';
			//exit;
		}    	
    	
//		if (isset($_POST)) {
//        	//$msg = 'POST';
//        	//print_r($_POST);
//        	if(isset($_POST['amount_due']) && isset($_POST['uid']) && $_POST['amount_due'] > 0){
//        		$msg = 'tttttttt';
//        		$uid = $_POST['uid'];
//    
//				$authModel = new authModel();
//				$customer = $authModel->getCustomer($uid);
//
//				$name = $customer['name'];        		
//        		
//        		//require 'views/admin/scan.tpl.php';
//        	} else {
//        		$msg = 'Else....';
//        		//echo "Yooo,";
//        		 //header('Location: /admin/scan');
//        	}
//            header('Location: /admin/scan');
//            exit;
//        }	    	
    	
 		if (isset($_GET['uid'])) {
            $msg = 'GET';
		 	$uid = $_GET['uid'];	
		
			$customer = $authModel->getCustomer($uid);
			
			//print_r($customer);

			$name = $customer['name'];

			if(empty($name)){
				$name = "Customer";
			} else { 
				$name = $customer['name'];
			}             
			   
			if (!empty($customer)) {
				$msg = '<div style="border:0px dotted #000; border-radius: 50px; -moz-border-radius: 50px; -webkit-border-radius: 50px; padding:4px 5px 0px"><img src="/static/images/big_green_checkmark.png" alt="Verified!" align="absmiddle" style="height:30px; padding-bottom:5px; margin-right:10px; letter-spacing:2px;"><b>Verified!</b></div>';
    			require 'views/admin/scan.tpl.php';				
			} else {
				$msg = '<div style="border:0px solid #ff0000; border-radius: 50px; -moz-border-radius: 50px; -webkit-border-radius: 50px; padding:4px 5px 0px"><img src="/static/images/not_authorized_icon.png" alt="NOT Valid" align="absmiddle" style="height:30px; padding-bottom:5px; margin-right:10px; letter-spacing:2px;"><b>Not Valid</b></div>';
    			require 'views/admin/scan.tpl.php';				
			}	
			
        }	else {
        	$msg = "Please scan E-Wallet QR Code....";
        }

    	require 'views/admin/scan.tpl.php';
    }
    
    // FOR TAKING PAYMENTS FROM E-WALLETS ON MOBILE SITE & INSTANT APPS
    function scanbkp() {
    	if (!$_SESSION['user_id'] && !$_SESSION['user']['is_admin']) {
    		//header("Location: /auth/login");
    		//exit;
				$msg = '<img src="/static/images/not_authorized_icon.png" alt="NOT Authorized" align="absmiddle" 
								style="height:60px; padding-bottom:5px; margin-right:10px; letter-spacing:2px;"> Stop! You are not 
								permitted to access this information.
								<br /><br />If you are an Admin, please <a href="/auth/login" style="font-weight:600;">click here to login</a>
								<br /><br />';
    			require 'views/admin/scan.tpl.php';
    	}    	

		if ($_GET) {
			//echo "yes";
			//exit;
		 	$uid = $_GET['uid'];	
		
			$authModel = new authModel();
			$customer = $authModel->getCustomer($uid);

			$name = $customer['name'];

			if(empty($name)){
				$name = "Customer";
			} else { 
				$name = $customer['name'];
			}    				
			
			if(!empty($customer)){
				$msg = '<img src="/static/images/big_green_checkmark.png" alt="Verified!" align="absmiddle" style="height:30px; padding-bottom:5px; margin-right:10px; letter-spacing:2px;"><b>Verified!</b>';
    			require 'views/admin/scan.tpl.php';				
			} else {
				$msg = '<img src="/static/images/not_authorized_icon.png" alt="NOT Valid" align="absmiddle" style="height:60px; padding-bottom:5px; margin-right:10px; letter-spacing:2px;"><b>Not Valid</b>';
    			require 'views/admin/scan.tpl.php';				
			}		

		} // end of get
		
//		if($_POST){	
//			if(isset($_POST['amount_due']) && $_POST['amount_due'] > 0){
//				$uid = $_GET['uid'];	
//				$due = $_POST['amount_due'];
//				
//				$msg = 'Thanks! Customer: ' . $uid . ' This is due: ' . $due;
//				require 'views/admin/scan.tpl.php';					
//			} else {
//				$msg = "Please enter an amount to send an instant payment request to the Customer...";
//			}					
//			//header('Location: /admin');
//			//require 'views/admin/scan.tpl.php';
//		}				
		 
    	require 'views/admin/scan.tpl.php';
    }    

    function page() {
		if (!$_SESSION['user_id'] && !$_SESSION['user']['is_admin']) {
			header("Location: /auth/login");
			exit;
		}
		
        $pageModel = new pageModel();
        $userModel = new userModel();
        $categoryModel = new categoryModel();

        $id = $this->registry->args[2];
        if (!is_numeric($id)) {
            $id = '';
        }

        if ($_POST) {
            if ($id) {
                $pageModel->update($id, $_POST);
                header('Location: /admin/page/'.$id.'?edit');
            } else {
                $pageModel->insert($_POST);
                header('Location: /admin/');
            }
            //header('Location: /admin/?tab=content');
            exit;
        }

        if (isset($_GET['delete'])) {
            $page = $pageModel->delete(['id' => $id]);
            header('Location: /admin/');
            exit;
        }
        
        if (isset($_GET['duplicate'])) {
            $this->duplicate($id);
            exit;
        }           
        
        $user_list = $userModel->getList([
            'justIds' => 1
        ]);
        
//        $category_list = $categoryModel->getList([
//            'justIds' => 1
//        ]);

        $page = $pageModel->get(['id' => $id]);
        $widgets = json_decode($page['widgets'], true);
        
        require('views/admin/edit_page.tpl.php');
    }
    
    function duplicate($id){
        $pageModel = new pageModel();
        $userModel   = new userModel();

        $page  = $pageModel->get(['id' => $id]);
        $dupl_id = $pageModel->duplicate($page);
		header("Location: /admin/");
        //header("Location: /admin/page/" . $dupl_id . "?edit");
    }       

    function editStoreCat() {
        $store_model = new storeModel();

        if (!empty($_GET['edit']))
           $cat = $store_model->getCategory($_GET['edit']);

        if ($_POST) {
            if ($_GET['edit']) {
                $store_model->updateCategory($_GET['edit'], $_POST);    
            } else {
                //$store_model->insertCategory($_POST['name']);
                $store_model->insertCategory($_POST);
            }
            header('Location: /admin/');
            exit;
        }

        require('views/admin/edit_store_category.tpl.php');
    }

    function editProjectCat() {
        $category_model = new categoryModel();

        if (!empty($_GET['edit']))
           $cat = $category_model->getCategory($_GET['edit']);

        if ($_POST) {
            if ($_GET['edit']) {
                $category_model->updateCategory($_GET['edit'], $_POST);
            } else {
                //$category_model->insertCategory($_POST['title']);
                $category_model->insertCategory($_POST);
            }
            header('Location: /admin/');
            exit;
        }

        require('views/admin/edit_project_category.tpl.php');
    }
    
    function editTestimonial() {
        $testimonial_model = new testimonialModel();

        if (!empty($_GET['edit']))
           $tes = $testimonial_model->getTestimonial($_GET['edit']);

        if ($_POST) {
            if ($_GET['edit']) {
                $testimonial_model->updateTestimonial($_GET['edit'], $_POST);   
            } else {
                $testimonial_model->insertTestimonial($_POST);
            }
            header('Location: /admin/');
            exit;
        }

        require('views/admin/edit_testimonial.tpl.php');
    }   
    
    function editLocation() {
        $locations_Model = new locationsModel();

        if (!empty($_GET['edit']))
           $location = $locations_Model->getLocation($_GET['edit']);

        if ($_POST) {
            if ($_GET['edit']) {
                $locations_Model->updateLocation($_GET['edit'], $_POST); 
            } else {
                $locations_Model->insertLocation($_POST);
            }
            header('Location: /admin/');
            exit;
        }

        require('views/admin/edit_location.tpl.php');
    }       
    
    function editLogo() {
        $logo_model = new logosModel();

        if (!empty($_GET['edit']))
           $logo = $logo_model->getLogo($_GET['edit']);

        if ($_POST) {
            if ($_GET['edit']) {
                $logo_model->updateLogo($_GET['edit'], $_POST); 
            } else {
                $logo_model->insertLogo($_POST);
            }
            header('Location: /admin/');
            exit;
        }

        require('views/admin/edit_logo.tpl.php');
    }   
    
    /*************************************/
    /************      ORDR      ***********/
    /*************************************/    
    
    function editOrdr() {
        $ordr_model = new ordrsModel();

		if (!empty($_GET['edit']))
			$ordr = $ordr_model->getTheOrder($_GET['edit']);
        
//		echo "Order ID exists";
//        
//		echo "<pre>";
//		print_r($ordr);

        if ($_POST) {
            if ($_GET['edit']) {
                $ordr_model->updateOrdr($_GET['edit'], $_POST); 
				header('Location: /admin/?oid&edit=' . $_GET['edit'] . '&msg');
            } else {
                $ordr_model->insertOrdr($_POST);
				header('Location: /admin/orders');  
            }
            exit;
        }

        require('views/admin/edit_ordr.tpl.php');
    }     
    
    /*************************************/
    /************     SPECIAL    ***********/
    /*************************************/            
    
    function editSpecial() {
        $special_model = new specialsModel();

        if (!empty($_GET['edit']))
           $special = $special_model->getSpecial($_GET['edit']);

        if ($_POST) {
            if ($_GET['edit']) {
                $special_model->updateSpecial($_GET['edit'], $_POST);   
            } else {
                $special_model->insertSpecial($_POST);
            }
            header('Location: /admin/');
            exit;
        }

        require('views/admin/edit_special.tpl.php');
    }    
 
    /*************************************/
    /************     USERS       ***********/
    /*************************************/     
    
      function editUser() {
        $user_model = new userModel();
        // Line 201
        if (!empty($_GET['edit']))
           $user = $user_model->getUser($_GET['edit']);

        if ($_POST) {
            if ($_GET['edit']) {
                $user_model->updateUser($_GET['edit'], $_POST); 
            } else {
                //$user_model->insertLogo($_POST);
            }
            header('Location: /admin/?user&edit='.$_GET['edit']);
            exit;
        }

        require('views/admin/edit_user.tpl.php');
    }      
 
    /*************************************/
    /************   REWARDS   ***********/
    /*************************************/       
 
    function rewardCropped() { 
        if ($_POST) {
            $id       = $_POST['edit']; 
            $img    = $_POST['image']; 
            
			if (!empty($id) && !empty($img)) {
				$siteroot = $_SERVER['SERVER_NAME'];
				
                $rewardsModel = new rewardsModel();
                $rewardsModel->insertRewardcropped($id, $img);  
				//header('Location: https://'.$siteroot.'/admin/?reward&edit='.$id); 
                //header('Location: https://preorder.sqdash.co/admin/?reward&edit='.$id); 
            } else {
                echo "Something is wrong";
            }
        }
    }       
    
    function editReward() {
        $reward_model = new rewardsModel();

        if (!empty($_GET['edit']))
           $reward = $reward_model->getReward($_GET['edit']);

        if ($_POST) {
			if ($_GET['edit']) {
				$siteroot = $_SERVER['SERVER_NAME'];
				
                $reward_model->updateReward($_GET['edit'], $_POST);   
				//header('Location: https://'.$siteroot.'/admin/?reward&edit='.$_GET['edit']); 
				header('Location: /admin/?reward&edit='.$_GET['edit']); 
                //header('Location: https://preorder.sqdash.co/admin/?reward&edit='.$_GET['edit']); 
                //header('Location: /admin/');
            } else {
                $reward_model->insertReward($_POST);
                header('Location: /admin/');
            }
            //header('Location: /admin/');
            exit;
        }

        require('views/admin/edit_reward.tpl.php');
    }         
 
     
    /*************************************/
    /************      MDEAL   ***********/
    /*************************************/        
    
    function mdealCropped() { 
        if ($_POST) {
            $id       = $_POST['edit']; 
            $img    = $_POST['image']; 
            
            if (!empty($id) && !empty($img)) {
                $mdealsModel = new mdealsModel();
                $mdealsModel->insertMdealcropped($id, $img);  
				$siteroot = $_SERVER['SERVER_NAME'];
				header('Location: https://'.$siteroot.'/admin/?mdeal&edit='.$id); 
            } else {
                echo "Something is wrong";
            }
        }
    }             
    
    function editMdeal() {
        $mdeal_model = new mdealsModel();

        if (!empty($_GET['edit']))
           $mdeal = $mdeal_model->getMdeal($_GET['edit']);

        if ($_POST) {
            if ($_GET['edit']) {
                $mdeal_model->updateMdeal($_GET['edit'], $_POST); 
				$siteroot = $_SERVER['SERVER_NAME'];  
				header('Location: https://'.$siteroot.'/admin/?mdeal&edit='.$_GET['edit']); 
            } else {
                $mdeal_model->insertMdeal($_POST);
            }
            //header('Location: /admin/');
            exit;
        }

        require('views/admin/edit_mdeal.tpl.php');
    }         
    
    /*************************************/
    /********      SQUARE CATS     *******/
    /*************************************/         
    
    function squarecatCropped() { 
        if ($_POST) {
            $id       = $_POST['edit']; 
            $img    = $_POST['image']; 
            
            if (!empty($id) && !empty($img)) {
                $squarecategoryModel = new squarecategoryModel();
                $squarecategoryModel->insertSquareCatcropped($id, $img);  
                //header('Location: https://preorder.sqdash.co/admin/?square_cat&edit='.$id); 
            } else {
                echo "Something is wrong";
            }
        }
    }       
    
    function editSquareCat() {
        $squarecategoryModel = new squarecategoryModel();

        if (!empty($_GET['edit']))
           $cat = $squarecategoryModel->getSquareCategory($_GET['edit']);

        if ($_POST) {
            if ($_GET['edit']) {
                $squarecategoryModel->updateSquareCategory($_GET['edit'], $_POST);
                header('Location: /admin/?square_cat&edit='.$_GET['edit']); 
            } else {
                $squarecategoryModel->insertSquareCategory($_POST);
                header('Location: /admin/');
            }
            //header('Location: /admin/?square_cat&edit=11');
            exit;
        }

        require('views/admin/edit_square_category.tpl.php');
    }    
    
    /*************************************/
    /****      SQUARE LOCATIONS     ****/
    /*************************************/         
    
    function squarelocCropped() { 
        if ($_POST) {
            $id       = $_POST['edit']; 
            $img    = $_POST['image']; 
            
            if (!empty($id) && !empty($img)) {
                $squarelocationsModel = new squarelocationsModel();
                $squarelocationsModel->insertSquareLoccropped($id, $img);  
                header('Location: /admin/?square_loc&edit='.$id); 
            } else {
                echo "Something is wrong";
            }
        }
    }       
    
    function editSquareLoc() {
        $squarelocationsModel = new squarelocationsModel();

        if (!empty($_GET['edit']))
           $loc = $squarelocationsModel->getSquareLocation($_GET['edit']);
        
		//$new_location_id = $squarelocationsModel->getCode();

        if ($_POST) {
            if ($_GET['edit']) {
                $squarelocationsModel->updateSquareLocation($_GET['edit'], $_POST);
                header('Location: /admin/?square_loc&edit='.$_GET['edit']); 
            } else {
                //$category_model->insertCategory($_POST['title']);
                $squarelocationsModel->insertSquareLocation($_POST);
				//header('Location: /admin/?tab=squarelocs');
                header('Location: /admin/');
            }
            //header('Location: /admin/?square_cat&edit=11');
            exit;
        }

        require('views/admin/edit_square_location.tpl.php');
    }        
    
    /***************************************/
    /****     SQUARE X PRODUCTS    ****/
    /***************************************/ 
    
     function editXProduct() {
        $squarexproductsModel = new squarexproductsModel();

        if (!empty($_GET['edit']))
           $squarexproduct = $squarexproductsModel->getXProduct($_GET['edit']);

        if ($_POST) {
            if ($_GET['edit']) {
                $squarexproductsModel->updateXProduct($_GET['edit'], $_POST);
                header('Location: /admin/?square_xp&msg&edit='.$_GET['edit']); 
            } else {
                //$category_model->insertCategory($_POST['title']);
                $squarexproductsModel->insertXProduct($_POST);
                header('Location: /admin/');
            }
            //header('Location: /admin/?square_cat&edit=11');
            exit;
        }

        require('views/admin/edit_squarexproduct.tpl.php');
    }                       
     
    /*************************************/
    /********     SQUARE USERS     *******/
    /*************************************/     
    
      function editSquareUser() {
        $squareuser_model = new squareusersModel();
        // Line 201
        if (!empty($_GET['edit']))
           $squareuser = $squareuser_model->getSquareUser($_GET['edit']);

        if ($_POST) {
			if ($_GET['edit']) {
//				print_r($_POST);
//				print_r($_FILES);
				$squareuser_model->updateUser($_GET['edit'], $_POST, $_FILES); 
            } else {
                //$user_model->insertLogo($_POST);
            }
            header('Location: /admin/?squareuser&edit='.$_GET['edit']);
            exit;
        }

        require('views/admin/edit_squser.tpl.php');
    }     
 
	/*************************************/
	/********    SUPPORT TICKETS   *******/
	/*************************************/     
    
	function editTicket(){
		$tickets_model = new ticketsModel();

		if (!empty($_GET['edit']))
			$ticket = $tickets_model->getTicket($_GET['edit']);
			//print_r($ticket);

		if ($_POST) {
			
			if ($_GET['edit']) {
				$tickets_model->updateTicket($_GET['edit'], $_POST);
				$sub_id = $_GET['edit'];
			} else {
				$tickets_model->insertTicket($_POST);
			}
			//header('Location: /admin/?ticket&edit='.$sub_id.'&saved');
			header('Location: /admin/?ticket&edit='.$sub_id.'&saved');
			//header('Location: /admin/');
			exit;
		}

		require('views/admin/edit_ticket.tpl.php');
	}	  
	
	/*************************************/
	/********     NOTIFICATONS     *******/
	/*************************************/

	function editNotification()
	{
		$messages_model = new messagesModel();

		if (!empty($_GET['edit']))
			$notification = $messages_model->getNotification($_GET['edit']);
		//print_r($ticket);

		if ($_POST) {

			if ($_GET['edit']) {
				
//				echo "<pre>";
//				print_r($_POST);	
//				exit;
								
				// this sets sent to 1 instantly after a Notification is saved with the send checkbox checked
				$_POST['sent'] =  !empty($_POST['send']) ? 1 : 0; 
				
				$messages_model->updateNotification($_GET['edit'], $_POST);
				$sub_id = $_GET['edit'];
				
//				print_r($_POST['send']);
//				exit;
				if (isset($_POST['send'])) {
					if ($_POST['group'] == "All") {
						$members = $messages_model->getAllMembers();
					// WHEN WE DO RECENT, WE MAY HAVE TO JOIN SQUARE_USERS TABLE TO GET SUBSCRIBER PREFERENCES	
					} else if ($_POST['group'] == "Recent") {
						//$members = $messages_model->getRecentCustomers();
					// WHEN WE DO RECENT, WE MAY HAVE TO JOIN SQUARE_USERS TABLE TO GET SUBSCRIBER PREFERENCES	
					} else if ($_POST['group'] == "NotRecent") {
						//$members = $messages_model->getNotRecentCustomers();
					} else if ($_POST['group'] == "Subscribers") {
						//echo "Subscribers";
						$members = $messages_model->getSubscribers();
					} else {
						$members = $messages_model->getAllMembers();
					}
					
//					echo "<pre>";
//					print_r($members);
					
					foreach ($members as $member) {
//						echo "<pre>";
//						print_r($member);
						
						$from = 276;
						$to = $member['email'];
						$message = $_POST['message'];
						//echo $member['id'] . " - " . $member['email'] . " - " . $member['is_text'] . "<br /><br />";
						//echo $_POST['message'];
						
						if (isset($_POST['inbox'])) {
							//echo "Send an Inbox notification...<br />";
							//insertNotification($data); // Send via Private Inbox
						}
						
						if (isset($_POST['email'])) {
							//echo "Send an Email notification...<br /><br />";
						}
						
						if (isset($_POST['text']) && $_POST['group'] != "Subscribers") {
							if ($member['is_text'] == 1) {
								//echo "Send an SMS Text notification...<br /><br />";	
							} 
						}				
					
						$db = Mysql::getInstance();
						$db->insert("messages", [
							'from'     => $from,
							'to' => $to,
							'message' => $message
						]);

						$headers = "MIME-Version: 1.0" . "\r\n";
						$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
						// .'Content-type: text/html; charset=utf-8' . "\r\n"

						// More headers techsupport@app.ihphysicians // ihpap@204-12-74-82.cprapid.com
						$headers .= 'From: OrderItFrom.com <contact@orderitfrom.com>' . "\r\n";
						$headers .= 'Reply-To: OrderItFrom.com <contact@orderitfrom.com>';
						//$headers .= 'Cc: thinappdev@gmail.com' . "\r\n";

						$email_recipient = $member;

						$welcome_email_title = "New Notification!";
						// <img src='https://app.ihphysicians.com/static/images/ihp_email_banner.png' alt='IHP' style='width:100%; height:auto;' />
						$welcome_email_body_OLD = "
							<br /><br />
							Hi,
							<br /><br />

							Thank you,<br />
							- Tech Support";
						$welcome_email_body = $_POST['message'];
						//@mail($email_recipient, $email_title, $email_body, $headers, '-fappsupport@ihphysicians.com');
						//@mail($email_recipient, $welcome_email_title, $welcome_email_body, $headers, '-fcontact@igy6app.com');
					} 
					
				} else {
					//echo "Email is not set to send.";
				}	
				header('Location: /admin/?notification&edit='.$sub_id.'&msg');
			} else {
				$messages_model->insertNotification($_POST);
				header('Location: /admin/notifications');
			}
			//header('Location: /admin/?notification&edit='.$sub_id.'&msg');
			//header('Location: /admin/');
			exit;
		}

		require('views/admin/edit_notification.tpl.php');
	}	  	      	
	
    /*************************************/
    /********     MODIFIER LIST    *******/
    /*************************************/     
    
      function editModifierList() {
		$squaremodifierlistModel 	= new squaremodifierlistsModel();
        // Line 201
		if (!empty($_GET['edit']))
			$modifierList = $squaremodifierlistModel->getaModifiersList($_GET['edit']);
		
//		echo "<pre>";
//		print_r($modifierList);

//		echo "<pre>";
//		print_r($_POST);
		
		$id = $_POST['id'];
		$modifier_name = $_POST['modifier_name'];
		$in_stock = $_POST['in_stock'];
		
//		echo "<pre>";
//		print_r($modifier_name);

		if (isset($_POST['edit_this'])) {
			if (is_array($_POST['edit_this'])) {
				foreach ($_POST['edit_this'] as $value) {

					echo $value['id'] . " " . $value['modifier_name'] . " " . $value['in_stock']; 
					$myarray[]=$value;
				}
			} else {
				$value = $_POST['edit_this'];
				echo $value;
			}
		}		
		
		print_r($myarray);


        if ($_POST) {
			if ($_GET['edit']) {
//				print_r($_POST);
//				print_r($_FILES);
				//$squaremodifierlistModel->updateModifiersList($_GET['edit'], $_POST, $_FILES); 
            } else {
                //$user_model->insertLogo($_POST);
            }
            header('Location: /admin/?modlist&edit='.$_GET['edit']);
            exit;
        }

        require('views/admin/edit_squaremodlist.tpl.php');
    }   	                  
    
    /***************/
    
    function eventCropped() { 
        if ($_POST) {
            $id       = $_POST['edit']; 
            $img    = $_POST['image']; 
            
            if (!empty($id) && !empty($img)) {
                $eventsmainModel = new eventsmainModel();
                $eventsmainModel->insertEventcropped($id, $img);  
				$siteroot = $_SERVER['SERVER_NAME'];
				header('Location: https://'.$siteroot.'/admin/?eventmain&edit='.$id); 
            } else {
                echo "Something is wrong";
            }
        }
    }       
    
    function editEventmain() {
        $eventmain_model = new eventsmainModel();

        if (!empty($_GET['edit']))
           $eventmain = $eventmain_model->getEvent($_GET['edit']);

        if ($_POST) {
            if ($_GET['edit']) {
                $eventmain_model->updateEvent($_GET['edit'], $_POST);  
				$siteroot = $_SERVER['SERVER_NAME'];               
				header('Location: https://'.$siteroot.'/admin/?eventmain&edit='.$_GET['edit']); 
            } else {
                $eventmain_model->insertEvent($_POST);
            }
            //header('Location: /admin/');
            exit;
        }

        require('views/admin/edit_eventmain.tpl.php');
    }       
    
    function editEvent() {
        $event_model = new eventsModel();

        if (!empty($_GET['edit']))
           $event = $event_model->getEvent($_GET['edit']);

        if ($_POST) {
            if ($_GET['edit']) {
                $event_model->updateEvent($_GET['edit'], $_POST);   
            } else {
                $event_model->insertEvent($_POST);
            }
            header('Location: /admin/');
            exit;
        }

        require('views/admin/edit_event.tpl.php');
    }   

    function editEventother() {
        $eventother_model = new eventsotherModel();

        if (!empty($_GET['edit']))
           $eventother = $eventother_model->getEventother($_GET['edit']);

        if ($_POST) {
            if ($_GET['edit']) {
                $eventother_model->updateEventother($_GET['edit'], $_POST); 
            } else {
                $eventother_model->insertEventother($_POST);
            }
            header('Location: /admin/');
            exit;
        }

        require('views/admin/edit_eventother.tpl.php');
    }           
    
    function editReminder() {
        $reminder_model = new remindersModel();

        if (!empty($_GET['edit']))
           $reminder = $reminder_model->getReminder($_GET['edit']);

        if ($_POST) {
            if ($_GET['edit']) {
                $reminder_model->updateReminder($_GET['edit'], $_POST); 
				header('Location: /admin/?reminder&edit='.$_GET['edit']);
            } else {
                $reminder_model->insertReminder($_POST);
				header('Location: /admin/reminders');
            }
            
            exit;
        }

        require('views/admin/edit_reminders.tpl.php');
    }       
    
    // TRIVIA 
    function editSet() {
        $sets_model = new setsModel();

		if (!empty($_GET['edit']))
			$set = $sets_model->get($_GET['edit']);

		if ($_POST) {
			if (empty($_POST['is_active']))
				$_POST['is_active'] = 0;
			else
				$_POST['is_active'] = 1;
			
			if ($_GET['edit']) {
				$sets_model->update($_GET['edit'], $_POST); 
				header('Location: /admin/?set&edit='.$_GET['edit'].'&saved');
            } else {
//				echo "<pre>";
//				print_r($_POST);
//				exit;

				$_POST = Array(
					"is_active" =>  $_POST['is_active'],
				    "title" => $_POST['title'],
					"description" => $_POST['description']
				);

				$sets_model->insert($_POST);
				header('Location: /admin/sets');
            }
            
            exit;
        }

        require('views/admin/edit_set.tpl.php');
    } 
    
    function editSeries() {
		$series_model = new seriesModel();

		if (!empty($_GET['edit']))
			$series = $series_model->getItem($_GET['edit']);

		if ($_POST) {
			if (empty($_POST['is_active']))
				$_POST['is_active'] = 0;
			else
				$_POST['is_active'] = 1;
			
			if (empty($_POST['parent']))
				$_POST['parent'] = 0;
			else
				$_POST['parent'] = 1;
			
			// A, B, C, D
			if(isset($_POST['itemChoiceA']) && $_POST['itemChoiceA'] !=""
			&& isset($_POST['itemChoiceB']) && $_POST['itemChoiceB'] !="" 
			&& isset($_POST['itemChoiceC']) && $_POST['itemChoiceC'] !="" 
			&& isset($_POST['itemChoiceD']) && $_POST['itemChoiceD'] !="") {
				$_POST['itemChoices'] = $_POST['itemChoiceA'].";".$_POST['itemChoiceB'].";".$_POST['itemChoiceC'].";".$_POST['itemChoiceD'];
				// A, B, C
			} elseif (isset($_POST['itemChoiceA']) && $_POST['itemChoiceA'] !=""
			       && isset($_POST['itemChoiceB']) && $_POST['itemChoiceB'] !=""
				   && isset($_POST['itemChoiceC']) && $_POST['itemChoiceC'] !=""
				   && isset($_POST['itemChoiceD']) && $_POST['itemChoiceD'] =="") {
				$_POST['itemChoices'] = $_POST['itemChoiceA'].";".$_POST['itemChoiceB'].";".$_POST['itemChoiceC'];
				// A, B
			} elseif (isset($_POST['itemChoiceA']) && $_POST['itemChoiceA'] !=""
				   && isset($_POST['itemChoiceB']) && $_POST['itemChoiceB'] !=""
				   && isset($_POST['itemChoiceC']) && $_POST['itemChoiceC'] ==""
				   && isset($_POST['itemChoiceD']) && $_POST['itemChoiceD'] =="") {
				$_POST['itemChoices'] = $_POST['itemChoiceA'].";".$_POST['itemChoiceB'];
			} else {
				//echo "Please provide answers for at least 2 choices, A and B.";
				header('Location: /admin/?series&edit='.$_GET['edit'].'&answers');
				return;
			}
			
			//		[itemChoiceA] => 3 sizes
			//		[itemChoiceB] => 4 sizes
			//		[itemChoiceC] => 5 sizes
			//		[itemChoiceD] =>
			//		[itemChoices] => 3 sizes;4 sizes;5 sizes
			
//			echo "<pre>";
//			print_r($_POST);
//			exit;   
			
			if ($_GET['edit']) {
				//echo "Edit is on....";
				$series_model->update($_GET['edit'], $_POST); 
				header('Location: /admin/?series&edit='.$_GET['edit'].'&saved');
            } else {
//				echo "<pre>";
//				print_r($_POST);
//				exit;

				$_POST = Array(
					"is_active" =>  $_POST['is_active'],
				    "title" => $_POST['title'],
					"description" => $_POST['description']
				);

				$series_model->insert($_POST);
				header('Location: /admin/series');
            }
            
            exit;
        }

        require('views/admin/edit_series.tpl.php');
    } 
    // TRIVIA ENDS
    
    function editPromo_code() {
        $pcode_model = new promocodeModel();

        if (!empty($_GET['edit']))
           $pcode = $pcode_model->getPromo_code($_GET['edit']);

        if ($_POST) {
            if ($_GET['edit']) {
                $pcode_model->updatePromo_code($_GET['edit'], $_POST); 
                 header('Location: /admin/?pcode&edit='.$_GET['edit']); 
            } else {
                $pcode_model->insertPromo_code($_POST);
                header('Location: /admin/promocodes');
            }
            exit;
        }

        require('views/admin/edit_pcode.tpl.php');
    }       

    function editTable() {
        $table_model = new tableModel();

        if (!empty($_GET['edit']))
           $table = $table_model->getTable($_GET['edit']);

        if ($_POST) {
            if ($_GET['edit']) {
                $table_model->updateTable($_GET['edit'], $_POST); 
                 header('Location: /admin/?table&edit='.$_GET['edit'].'&saved'); 
            } else {
                $table_model->insertTable($_POST);
                header('Location: /admin/tables');
            }
            exit;
        }

        require('views/admin/edit_table.tpl.php');
    }       

    function editMenu() {
        $menu_model = new menusModel();

		if (!empty($_GET['edit']))
			$menu = $menu_model->getMenu($_GET['edit']);

        if ($_POST) {
			if ($_GET['edit']) {
				$menu_model->updateMenu($_GET['edit'], $_POST); 
                 header('Location: /admin/?menu&edit='.$_GET['edit']); 
            } else {
				$menu_model->insertMenu($_POST);
                header('Location: /admin/menus');
            }
            exit;
        }

        require('views/admin/edit_menu.tpl.php');
    }   
    
    /*************************************/
	/********    MANAGED SERVICES  *******/
	/*************************************/     
    
	function editService(){
		$servicesModel = new servicesModel();
		$requestsModel = new requestsModel();
		
		$requestCategories = $requestsModel->getCategories();

		if (!empty($_GET['edit']))
			$service = $servicesModel->getService($_GET['edit']);
			//print_r($ticket);

		if ($_POST) {
			
			if ($_GET['edit']) {
				$servicesModel->updateService($_GET['edit'], $_POST);
				$service_id = $_GET['edit'];
			} else {
				$servicesModel->insertService($_POST);
			}
			//header('Location: /admin/?ticket&edit='.$sub_id.'&saved');
			header('Location: /admin/services?edit='.$service_id.'&saved');
			//header('Location: /admin/');
			exit;
		}

		require('views/admin/edit_service.tpl.php');
	}	
	
    /*************************************/
	/********    FAQS - ACCORDION  *******/
	/*************************************/     
    
	function editFAQ(){
		$faqsModel = new faqsModel();

		if (!empty($_GET['edit']))
			$faq = $faqsModel->getItem($_GET['edit']);
			//print_r($faq);

		if ($_POST) {
			if ($_GET['edit']) {
				$faqsModel->update($_GET['edit'], $_POST);
				$faq_id = $_GET['edit'];
			} else {
				$faqsModel->insert($_POST);
			}
			//header('Location: /admin/?ticket&edit='.$sub_id.'&saved');
			header('Location: /admin/faqs?edit='.$faq_id.'&saved');
			//header('Location: /admin/');
			exit;
		}

		require('views/admin/edit_faq.tpl.php');
	}	

    /*************************************/
	/********      EDIT ACCOUNT    *******/
	/*************************************/     
    
	function editAccount(){
		$accountsModel = new accountsModel();

		if (!empty($_GET['edit']))
			$account = $accountsModel->getItem($_GET['edit']);
			//print_r($account);

		if ($_POST) {
			if ($_GET['edit']) {
				$accountsModel->update($_GET['edit'], $_POST);
				$account_id = $_GET['edit'];
			} else {
				$accountsModel->insert($_POST);
			}
			//header('Location: /admin/?ticket&edit='.$sub_id.'&saved');
			header('Location: /admin/accounts?edit='.$account_id.'&saved');
			//header('Location: /admin/');
			exit;
		}

		require('views/admin/edit_account.tpl.php');
	}		

    function editFeaturedAccount() {
        $userModel = new userModel();

        if (!empty($_GET['edit']))
           $row = $userModel->getFeaturedAccounts(['id' => $_GET['edit']])[0];

        if (!empty($_GET['deleteFile'])) {
            $userModel->deleteFeaturedAccountImage($_GET['edit'], $_GET['deleteFile']);
            $row = $userModel->getFeaturedAccounts(['id' => $_GET['edit']])[0];
        }

        if ($_POST) {
            if ($_GET['edit']) {
                $userModel->updateFeaturedAccount($_GET['edit'], $_POST);
            } else {
                $userModel->insertFeaturedAccount($_POST);
            }
            header('Location: /admin/');
            exit;
        }

        require('views/admin/edit_featured_account.tpl.php');
    }
    
    function editCheckout() {
        require('views/admin/edit_checkouttext.tpl.php');
    }   

    function edit() {
        require('views/admin/edit.tpl.php');
    }

    function activateUser(){
           if (empty($_POST['uid'])) 
              exit;

        $userModel = new userModel();
        $user = $userModel->getUser($_POST['uid']);

        $userModel->updateUser($user['id'], ['is_activated' => 1]);
       echo "1"; 
       exit; 
    }

    function deleteUser(){
           if (empty($_POST['uid'])) 
              exit;
        
        $usr = $_POST['uid'];

        $userModel = new userModel();
        $userModel->deleteUser($usr);
       echo "1"; 
       exit; 
    }

    function makeAdmin()
    {
        if (empty($_POST['uid']))
            exit;

        $userModel = new userModel();
        $user = $userModel->getUser($_POST['uid']);
        
        $userModel->updateUser($user['id'], ['is_admin' => 1]);
        echo 1;
        exit;
    }   
    
    function removeAdmin()
    {
        if (empty($_POST['uid']))
            exit;

        $userModel = new userModel();
        $user = $userModel->getUser($_POST['uid']);

        $userModel->updateUser($user['id'], ['is_admin' => 0]);
        echo 1;
        exit;
    }   
    // HIDE SQUARE CATEGORY
    function makeHidden()
    {
        if (empty($_POST['id']))
            exit;
        $checkval = $_POST['checked'];
        if($checkval == 1){
            $checked = 0;
        } else {
            $checked = 1;
        }
        
        $squarecategoryModel = new squarecategoryModel();
        $squarecategory = $squarecategoryModel->getSquareCategory($_POST['id']);
        
        $squarecategoryModel->markHidden($squarecategory['id'], $checked);
        
        echo $checked;
        exit;
    }  
    
       // HIDE SQUARE LOCATION
    function makeHiddenLocation()
    {
        if (empty($_POST['id']))
            exit;
        $checkval = $_POST['checked'];
        if($checkval == 1){
            $checked = 0;
        } else {
            $checked = 1;
        }
        
        $squarelocationsModel = new squarelocationsModel();
        $squarelocation = $squarelocationsModel->getSquareLocation($_POST['id']);
        
        $squarelocationsModel->markHidden($squarelocation['id'], $checked);
        
        echo $checked;
        exit;
    }         
    
    // HIDE SQUARE LOCATION
     function hideLocation()
    {
        if (empty($_POST['id']))
            exit;
        $checkval = $_POST['checked'];
        if($checkval == 1){
            $checked = 0;
        } else {
            $checked = 1;
        }
        
        $squarelocationsModel = new squarelocationsModel();
        $squarelocation = $squarelocationsModel->getSquareLocation($_POST['id']);
        
        $squarelocationsModel->markHidden($squarelocation['id'], $checked);
        
        echo $checked;
        exit;
    }       

    function fillCheckboxSettings(array $fields, array $settings)
    {
        foreach ($fields as $field) {
            if (empty($settings[$field]))
                $settings[$field] = "0";
            else
                $settings[$field] = "1";
        }
        return $settings;
    }

    function saveSettings()
    {
        if (empty($_POST['save_settings']) || empty($_POST['settings']))
            exit;

        //$this->platformDump();

        $settings     = $_POST['settings'];
        $optionsModel = new optionsModel();
        $opts_before  = $optionsModel->getList();

        // make sure checkboxes values are set. (0 if empty)
        $checkboxes = [
			'enable_rsvp', 'enable_categories','enable_hours','enable_tables', 'enable_fundraising', 'enable_proposals', 
			'enable_deals', 'enable_questions', 'enable_blog', 'enable_events', 
            'enable_ecommerce', 'enable_opinions', 'enable_ph1', 'enable_ph2', 'enable_spaces', 
            'enable_physical', 'enable_services', 'enable_payment_to_siteowner',
            'enable_homepage_search', 'enable_homepage_slider', 'enable_homepage_nearby',
            'enable_feature_1', 'enable_feature_2', 'enable_feature_3', 'enable_feature_4',
            'enable_feature_5', 'enable_feature_6', 'disable_desktop_version', 'enable_cms_sidebar','enable_alert',
			'enable_custom_section','enable_donate_section', 'enable_slim_white_section', 'enable_testimonials',
			'enable_logos','enable_rotator'
        ];
        $settings   = $this->fillCheckboxSettings($checkboxes, $settings);

        $img_opts = [
            'website_logo',
            'footer_logo',
            'mobile_logo',
            'appintro_logo',
            'homepage_slider_img_1',
            'homepage_slider_img_2',
            'homepage_slider_img_3',
            'website_favicon',
			'mobile_logo_100x100',
            'mobile_logo_57x57',
            'mobile_logo_72x72',
            'mobile_logo_76x76',
            'mobile_logo_114x114',
            'mobile_logo_120x120',
            'mobile_logo_144x144',
            'mobile_logo_152x152',
            'mobile_background',
			'mobile_header',
			'mobile_hdr_logo',  
			'specialty_top',
			'specialty_bottom',         
            'fb_shareimage'
        ];
        foreach ($img_opts as $opt)
            if (!empty($_FILES[$opt]))
                $optionsModel->updateImageOption($_FILES[$opt], $opt);

        foreach ($settings as $setting => $value)
            $optionsModel->update($setting, $value);

        /* delete "emptied" settings / 
        foreach ($opts_before as $opt => $val)
            if (! in_array($opt, array_keys($settings))
                && ! in_array($opt, $checkboxes)
                && ! in_array($opt, $img_opts))
                $optionsModel->delete($opt);
        */

        header("Location: /admin/");
        exit;
    }
    // SAVE SQUARE SETTINGS
    function saveSSettings()
    {
        if (empty($_POST['save_ssettings']) || empty($_POST['ssettings']))
            exit;

        //$this->platformDump();

        $settings     = $_POST['ssettings'];
        $soptionsModel = new soptionsModel();
        $opts_before  = $soptionsModel->getList();

        // make sure checkboxes values are set. (0 if empty)
        $checkboxes = [
            'use_square_loyalty', 'rewards_type'
        ];
        $settings   = $this->fillCheckboxSettings($checkboxes, $settings);

        $img_opts = [
            //'website_logo',
        ];
        foreach ($img_opts as $opt)
            if (!empty($_FILES[$opt]))
                $soptionsModel->updateImageOption($_FILES[$opt], $opt);

        foreach ($settings as $setting => $value)
            $soptionsModel->update($setting, $value);

        header("Location: /admin/");
        exit;
    }
    
     // SAVE CONFIG SETTINGS
    function saveCSettings()
    {
        if (empty($_POST['save_csettings']) || empty($_POST['csettings']))
            exit;

        //$this->platformDump();

        $settings     = $_POST['csettings'];
        $sconfigModel = new sconfigModel();
        $copts_before  = $sconfigModel->getList();

        // make sure checkboxes values are set. (0 if empty)
        $checkboxes = [
            //'use_square_loyalty', 'rewards_type'
        ];
        $settings   = $this->fillCheckboxSettings($checkboxes, $settings);

        $img_opts = [
            'logo',
            'bg',
            'stamp',
        ];
        foreach ($img_opts as $opt)
            if (!empty($_FILES[$opt]))
                $sconfigModel->updateImageOption($_FILES[$opt], $opt);

        foreach ($settings as $setting => $value)
            $sconfigModel->update($setting, $value);

        header("Location: /admin/");
        exit;
    }   

    function test(){
        if(isset($_POST['export_list'])){
            if (is_array($_POST['export_list'])) {
                foreach($_POST['export_list'] as $value){
                    $myarray[]=$value;
                }
            } else {
                $value = $_POST['export_list'];
                echo $value;
            }
        }
        print_r($myarray);
    }
    function exportTable()
    {
        // Database Connection

        $host="localhost";
        $uname="nextf77";
        $pass="Jedifounder1";
        $database = "luxbrande";
        $table = "backing_history";
        $connection=mysql_connect($host,$uname,$pass);

        echo mysql_error();

        //or die("Database Connection Failed");
        $result=mysql_select_db($database)
        or die("database cannot be selected <br>");

        // Fetch Record from Database

        $output = "";
        // Enter Your Table Name
        $sql = mysql_query("SELECT * FROM  $table WHERE  `FromAuthorize` =1 ");
        $columns_total = mysql_num_fields($sql);
        $columns_total=$columns_total-1;//from_authorize column delete.
        // Get The Field Name

        for ($i = 0; $i < $columns_total; $i++) {
        $heading = mysql_field_name($sql, $i);
        $output .= '"'.$heading.'",';
        }
        $output .="\n";

        // Get Records from the table

        while ($row = mysql_fetch_array($sql)) {
        for ($i = 0; $i < $columns_total; $i++) {
        $output .='"'.$row["$i"].'",';
        }
        $output .="\n";
        }

        // Download the file

        $filename = "authorize.csv";
        header('Content-type: application/csv');
        header('Content-Disposition: attachment; filename='.$filename);

        echo $output;
        exit;
    }
    
    function exportFormSubmissions()
    {
        // Database Connection

        $host="localhost";
        $uname="thndevco_master";
        $pass="Z@lxq56~sa47*[5";
        $database = "thndevco_master";
        $table = "form_submissions";
        $connection=mysql_connect($host,$uname,$pass);

        echo mysql_error();

        //or die("Database Connection Failed");
        $result=mysql_select_db($database)
        or die("database cannot be selected <br>");

        // Fetch Record from Database

        $output = "";
        // Enter Your Table Name
        $sql = mysql_query("SELECT * FROM  $table");
        $columns_total = mysql_num_fields($sql);
        //$columns_total=$columns_total-1;//from_authorize column delete.
        // Get The Field Name

        for ($i = 0; $i < $columns_total; $i++) {
        $heading = mysql_field_name($sql, $i);
        $output .= '"'.$heading.'",';
        }
        $output .="\n";

        // Get Records from the table

        while ($row = mysql_fetch_array($sql)) {
        for ($i = 0; $i < $columns_total; $i++) {
        $output .='"'.$row["$i"].'",';
        }
        $output .="\n";
        }

        // Download the file

        $filename = "form_submissions.csv";
        header('Content-type: application/csv');
        header('Content-Disposition: attachment; filename='.$filename);

        echo $output;
        exit;
    }   

    function exportCsvToPayViaAuthorize()
    {
        // Database Connection

        $host="localhost";
        $uname="nextf77";
        $pass="Jedifounder1";
        $database = "luxbrande";
        $table = "users";
        $connection=mysql_connect($host,$uname,$pass);

        echo mysql_error();

        //or die("Database Connection Failed");
        $result=mysql_select_db($database)
        or die("database cannot be selected <br>");

        // Fetch Record from Database

        $output = "";
        //Get array checkboxes

        $id = $_POST['id'];
        $backed_amount = $_POST['backed_amount'];
        $already_paid = $_POST['already_paid'];

        $backedPair = array_combine($id, $backed_amount);
        $paidPair=array_combine($id, $already_paid);
        if(isset($_POST['export_list'])){
            if (is_array($_POST['export_list'])) {
                foreach($_POST['export_list'] as $value){
                    $myarray[]=$value;
                }
            } else {
                $value = $_POST['export_list'];
                echo $value;
            }
        }



        $array= array();

        $array=$myarray;
        //end Get array checkboxes


        $sql = mysql_query("SELECT projects.title,users.id,users.creditcard,users.email,users.name ,projects.id,projects.budget,projects.already_paid,
                users.x_exp_date,users.x_bank_acct_num ,users.x_bank_acct_type ,users.x_bank_aba_code ,users.x_bank_name ,users.x_first_name ,
                users.x_last_name ,users.x_company ,users.x_adress ,users.x_city ,users.x_state ,users.x_zip ,users.x_phone ,users.x_fax ,users.x_email FROM `users`
                INNER JOIN `projects` ON projects.user_id=users.id
                AND projects.id IN (".implode(',',$array).")
                " );
        $columns_total = mysql_num_fields($sql);

        //from_authorize column delete.
        // Get The Field Name

        $output .= 'Invoice Number,Description,Amount,Payment Method,Transaction Type,Authorization Code,Transaction ID,Credit Card Number,Credit Card Expiration Date,Bank Account Number,Bank Account Type,Bank ABA Routing Code,Bank Name,Customer ID,Customer First Name,Customer Last Name,Customer Company,Customer Address,Customer City,Customer State,Customer ZIP,Customer Phone,Customer Fax,Customer Email';
        $output .="\n";
    $invoiceNumber=10001;
        // Get Records from the table
        while ($row = mysql_fetch_array($sql)) {
                $output.= $invoiceNumber;//Invoice Number
                $invoiceNumber++;
                $output .= ',';

                $output .='"Payment to '.$row[0].'"';       //Description
                $output .= ',';

                $output.=$backedPair[$row[5]]-$paidPair[$row[5]]; //Amount.
                $output .= ',';
                if (isset($_POST['payChecked']))    {
                    $projectModel = new projectModel();
                $projectModel->addAmountPaid($row[5], $backedPair[$row[5]]-$paidPair[$row[5]]);//chande amount_paid in db
                }
                $output.="CC";//Payment Method CC or ECHECK. If left blank, this value will default to CC.
                $output .= ',';
                //";//$output .= ',';
                $output.="AUTH_CAPTURE";//Transaction Type
                $output .= ',';

                $output.="";//Authorization Code  Required and  necessary only for  CAPTURE_ONLY type transactions.
                $output .= ',';

                $output.="";//Transaction ID  Required and  necessary only for  CREDIT, VOID or PRIOR_AUTH_CAPTURE
                $output .= ',';

                $output .='"'.$row[2].'"';//Credit Card Number
                $output .= ',';

                $output .='"'.$row[8].'"';//,Credit Card Expiration Date Optional for Credits.
                $output .= ',';

                $output.='"'.$row[9].'"';//Bank Account Number
                $output .= ',';

                $output.='"'.$row[10].'"';//Bank Account Type
                $output .= ',';

                $output.='"'.$row[11].'"';//Bank ABA Routing Code
                $output .= ',';

                $output.='"'.$row[12].'"';//Bank Name
                $output .= ',';

                $output.="";//Customer ID (BANK)'"'.$row[1].'"'
                $output .= ',';

                $output .='"'.$row[13].'"';//Customer First Name
                $output .= ',';

                $output .='"'.$row[14].'"';//Customer Last Name
                $output .= ',';

                $output.='"'.$row[15].'"';//Customer Company
                $output .= ',';

                $output.='"'.$row[16].'"';//Customer Address
                $output .= ',';

                $output.='"'.$row[17].'"';//Customer City
                $output .= ',';

                $output.='"'.$row[18].'"';//Customer State
                $output .= ',';

                $output.='"'.$row[19].'"';//Customer ZIP
                $output .= ',';

                $output.='"'.$row[20].'"';//Customer Phone
                $output .= ',';

                $output.='"'.$row[21].'"';//Customer Fax
                $output .= ',';

                $output .='"'.$row[22].'"';//Customer Email
                $output .= ',';

                //$output .='"'.$row[1].'",';//user id
                //name
                //$output .='"'.$row[5].'",';//proj id
                //$output .='"'.$row[6].'",';//budget
                //$output .='"'.$row[7].'",';//already paid

            $output .="\n";
        }
        // Download the file

        $filename = "upload_authorize.csv";
        header('Content-type: application/csv');
        header('Content-Disposition: attachment; filename='.$filename);

        echo $output;
        exit;
    }
    function usersFees()
    {
        $userModel = new userModel();
        $users = $userModel->getList();

        if (!empty($_POST)) {
            $fees     = $_POST['specific_fees'];
            $disabled = $_POST['disabled_fees'];

            // for each fee set we need to update the user.specific_fee
            // field in the database
            foreach ($fees as $user_id => $fee_pc) {
                $fee_pc = str_replace("%", "", $fee_pc);
                if (!is_numeric($fee_pc))
                    continue;

                $userModel->updateUser($user_id, ['specific_fee' => $fee_pc]);
            }

            foreach ($disabled as $user_id => $fee_pc) {
                $fee_pc = -1;

                $userModel->updateUser($user_id, ['specific_fee' => $fee_pc]);
            }
        }

        require('views/admin/users-fees.tpl.php');
    }

    function upload()
    {
        $response = array('status' => 'error');
        if (!empty($_FILES['ufile'])) {
            do {
                $file = $_FILES['ufile'];
                if ($file['error']) {
                    $response['code'] = 1;
                    break;
                }

                if ($file['size'] > 1024*1024*10) {
                    $response['code'] = 2;
                    break;
                }

                $type = null;
                if (!empty($_POST['type']) && $_POST['type'] == 'image') {
                    $type = 'image';
                }

                $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
                if (in_array($ext, ['php', 'htm', 'html', 'php4', 'php5', 'htaccess'])) {
                    $response['code'] = 3;
                    break;
                }

                if ($type == 'image' && ($ext != 'jpg' && $ext != 'png' && $ext != 'jpeg')) {
                    $response['code'] = 4;
                    break;
                }

                $filename = sha1($file['tmp_name']);

                $destination = "static/uploads/featured/$filename.$ext";
                //if (!file_exists($destination)) {
                    //if ($type == 'image') {
                    //    autoRotateImage($file['tmp_name']);
                    //}

                    move_uploaded_file($file['tmp_name'], $destination);
                //}

                $uploadsModel = new uploadsModel();
                $id = $uploadsModel->insert($destination, $type, $file['name']);

                $response['status'] = 'ok';
                $response['id'] = $id;
            } while (0);
        }

        echo json_encode($response);
        exit;
    }
}
?>