<?php
require_once("SS_Log.php");

    class SS_Media
    {   
		public $md_id;	
		public $merc_id;	
		public $md_name;
		public $md_type;
		public $md_startDate;
		public $md_endDate;
		public $md_imagePath;
		public $md_image;	
		public $md_remark;
		public $md_create_dt;
		public $md_update_dt;
		public $md_show;
		public $md_status;
		public $md_videoPath;
		public $md_video;
		public $qty_types;
		public $quantity;
		public $features_deal;
		public $hot_deal;
		public $features_pic;
		public $features_pic;
		public $allow_sameperson;
		public $category;
		
		public function __construct ()
        {   
			$this->md_id = 0;
			$this->merc_id = 0;
			$this->md_name = "";
			$this->md_type = 1;
			$this->md_startDate = date("Y-m-d H:i:s");
			$this->md_endDate = date("Y-m-d H:i:s");
			$this->md_imagePath = "";
			$this->md_image = "";
			$this->md_remark = "";
            $this->dt = date("Y-m-d H:i:s");
			$this->md_show = 222;
			$this->md_status = 1;
			$this->md_videoPath = "";
			$this->md_video = "";
			$this->qty_types = "";
			$this->quantity = "";
			$this->features_deal = "";
			$this->hot_deal = "";
			$this->features_pic = "";
        }
		
		public function init( $row ) {
			
			$this->md_id = $row['md_id'];
			$this->merc_id = $row['merc_id'];
			$this->md_name = $row['md_name'];
			$this->md_type = $row['md_type'];
			$this->md_startDate = $row['md_startDate'];
			$this->md_startTime = $row['md_startTime'];
			
			$this->md_endDate = $row['md_endDate'];
			$this->md_endTime = $row['md_endTime'];
			
			$this->md_imagePath = $row['md_imagePath'];
			$this->md_image = $row['md_image'];
            $this->md_videoPath = $row['md_videoPath'];
			$this->md_video = $row['md_video'];
			$this->md_remark = $row['md_remark'];
			$this->md_create_dt = $row['md_create_dt'];
			$this->md_update_dt = $row['md_update_dt'];
			$this->md_show = $row['md_show'];
			$this->md_status = $row['md_status'];
			$this->qty_types = $row['qty_types'];
			$this->quantity = $row['quantity'];
			$this->features_deal = $row['features_deal'];
			$this->hot_deal = $row['hot_deal'];
			$this->features_pic = $row['features_pic'];
			$this->allow_sameperson = $row['allow_sameperson'];
			$this->category = $row['category'];
			
        }
		
		public function validateForm($obj){
			
			$this->images = [0,0];
            $this->exts = [""];
            
            global $imageTypeArray;
			
            $erV = ['',''];
            $proceed = true;
			   if( strlen($_FILES["features_pic"]["name"]) > 0 ) {
                $this->images[0] = 1;
                $fileData = getimagesize($_FILES["features_pic"]["tmp_name"]);
                $fileExt = $imageTypeArray[$fileData[2]];
                $this->exts[0] = strtolower($fileExt);
                if( !($fileExt == "JPG" || $fileExt == "PNG") ){
                    $this->images[0] = 0;
                    $erV[8] .= 'Feature image file type must be jpg or png.<br>';$proceed = false;
                }

                if ($_FILES["features_pic"]["size"] > 100000000 * 100 ) {
                    $this->images[0] = 0;
                    $erV[8] .= 'Feature image must be smaller than 100 MB.<br>';$proceed = false;
                }
            }
	
			
			
	
			

			 return [$proceed, $erV];
		}
		
		public function create($obj){
			
			global $db;
            $ret = [];
            $result = $this->validateForm($obj);
            $proceed = $result[0];
			$erV = $result[1];
			
			if( $proceed ){
				
				$UUID = 0;
				$merc_id = $obj['merc_id'];
			
				$md_name = trim($obj['md_name']);
				$md_type = $obj['md_type'];
	
				$md_startDate = trim($obj['md_startDate']);
				$md_startTime = trim($obj['md_startTime']);
				$md_startDate = $md_startDate.' '.$md_startTime;
				
				$md_endDate = trim($obj['md_endDate']);
				$md_endTime = trim($obj['md_endTime']);
				$md_endDate = $md_endDate.' '.$md_endTime;
				
				$domain = $obj['txtDomain'].'_uploads/promotion/';
				$a = array( ' ', '-', '(', ')' );  
				$qty_types = $obj['qty_types'];
				$quantity = $obj['quantity'];
				$features_deal = $obj['features_deal'];
				$hot_deal = $obj['hot_deal'];
				$allow_sameperson = $obj['allow_sameperson'];
				$category = $obj['category'];
				
			 $filename1 = date("YmdHis") . "_" . $_FILES["features_pic"]["name"];
					
					
				
				
				$md_remark = $obj['md_remark'];
				$md_show = $obj['md_show'];
				$md_status = $obj['md_status'];
				
				$query = "INSERT INTO `"._PREFIX_."promotions` (`md_id`,  `merc_id`,  `md_name`, `md_type`, `md_startDate`, `md_endDate`, `md_imagePath`, `md_image`,  `md_remark`, `md_create_dt`, `md_update_dt`, `md_show`, `md_status`, `md_videoPath`, `md_video`, `qty_types`, `quantity`, `features_deal`, `hot_deal`, `features_pic`, `allow_sameperson`, `category`) VALUES(null,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
				$stmt = $db->prepare($query);
				$stmt->bind_param('isisssssssiissiiiisii', $merc_id, $md_name, $md_type,  $md_startDate, $md_endDate, $filename1, $filename1,  $md_remark, $this->dt, $this->dt, $md_show, $md_status, $filename1, $filename1, $qty_types, $quantity, $features_deal, $hot_deal, $filename1,$allow_sameperson,$category);
				$db->set_charset("utf8");
				$stmt->execute(); 
				
				$last_insert_id = $db->insert_id;
				
				     //move to files folders
		
				   
				
					  $target_file = "../_uploads/promotion/{$filename1}";
                    if (move_uploaded_file($_FILES["features_pic"]["tmp_name"], $target_file)) {}  
			
				
				//insert into log
				$c = new SS_Log();
			    $post = array('log_subject'=>'Create','log_content'=>'Create Promotion '.$md_name);
			    $c->create($post);	
				
				$ret = ['success','Success',"Promotion <u>{$md_name}</u> succesfully created!"];	
				
		    } else $ret = ['danger','Error',"Please fill up the form."];
			
			$this->init( ['md_id'=>$last_insert_id,  'md_name'=>$obj['md_name'], 'md_type'=>$obj['md_type'], 'md_startDate'=>$obj['md_startDate'], 'md_startTime'=>$obj['md_startTime'], 'md_endDate'=>$obj['md_endDate'], 'md_endTime'=>$obj['md_endTime'], 'md_remark'=>$obj['md_remark'], 'md_show'=>$obj['md_show'], 'md_status'=>$obj['md_status'], 'merc_id'=>$obj['merc_id'], 'qty_types'=>$obj['qty_types'], 'quantity'=>$obj['quantity'], 'features_deal'=>$obj['features_deal'], 'hot_deal'=>$obj['hot_deal'], 'features_pic'=>$obj['features_pic'], 'allow_sameperson'=>$obj['allow_sameperson'], 'category'=>$obj['category']] );
			
			array_push($ret, $erV);
            
            return $ret;	
		}
		
		public function update( $obj ) {
			
			global $db;
            $ret = [];
            $result = $this->validateForm($obj);
            $proceed = $result[0];
			$erV = $result[1];
			
			if( $proceed ){
			    
				$md_id = $obj['txtID'];
			
				$merc_id = $obj['merc_id'];
				
				$md_name = trim($obj['md_name']);
				$md_type = $obj['md_type'];
				
				
				$md_startDate = trim($obj['md_startDate']);
				$md_startTime = trim($obj['md_startTime']);
				$md_startDate = $md_startDate.' '.$md_startTime;
				
				$md_endDate = trim($obj['md_endDate']);
				$md_endTime = trim($obj['md_endTime']);
				$md_endDate = $md_endDate.' '.$md_endTime;
					$qty_types = $obj['qty_types'];
				$quantity = $obj['quantity'];
				$features_deal = $obj['features_deal'];
				$hot_deal = $obj['hot_deal'];
					$allow_sameperson = $obj['allow_sameperson'];
				$category = $obj['category'];
				$domain = $obj['txtDomain'].'_uploads/promotion/';
				$a = array( ' ', '-', '(', ')' );  
				
				$eq1 = "";
				$eq2 = "";
				$eq3="";
				
				if(strlen($_FILES["features_pic"]["name"]) > 0) {
				 $filename1 = date("YmdHis") . "_" . $_FILES["features_pic"]["name"];
                    $target_file = "../_uploads/promotion/{$filename1}";
					  $eq3 .= ", `features_pic`='{$filename1}' ";
                    if (move_uploaded_file($_FILES["features_pic"]["tmp_name"], $target_file)) {}
				
				}
				
				
			
				
				$md_remark = $obj['md_remark'];
				$md_show = $obj['md_show'];
				$md_status = $obj['md_status'];
				
				 $query = "UPDATE `"._PREFIX_."promotions` SET `merc_id`=?,  `md_name`=?, `md_type`=?, `md_startDate`=?, `md_endDate`=?, $eq1 $eq2  `md_remark`=?, `md_update_dt`=?, `md_show`=?, `md_status`=?, `qty_types`=?, `quantity`=?, `features_deal`=?, `hot_deal`=?, `allow_sameperson`=?, `ategory`=? $eq3 WHERE `md_id`=?;";
				 $stmt = $db->prepare($query);
				 $stmt->bind_param('isissssiiiiiiiii',  $merc_id, $md_name, $md_type,  $md_startDate,  $md_endDate, $md_remark, $this->dt, $md_show, $md_status, $qty_types, $quantity, $features_deal, $hot_deal, $allow_sameperson	,$category,$md_id);
				 $db->set_charset("utf8");
				 $stmt->execute(); 
				 
				//insert into log
			    $c = new SS_Log();
			    $post = array('log_subject'=>'Updated','log_content'=>'Updated Promotion '.$md_name);
			    $c->create($post);	
				
				$ret = ['success','Success',"Promotion <u>{$md_name}</u> succesfully updated!"];	
				
			} else $ret = ['danger','Error',"Please fill up the form."];
			
			$this->init( ['md_id'=>$obj['txtID'],  'md_name'=>$obj['md_name'], 'md_type'=>$obj['md_type'],  'md_startDate'=>$obj['md_startDate'], 'md_startTime'=>$obj['md_startTime'], 'md_endDate'=>$obj['md_endDate'], 'md_endTime'=>$obj['md_endTime'], 'md_remark'=>$obj['md_remark'], 'md_show'=>$obj['md_show'], 'md_status'=>$obj['md_status'], 'md_imagePath'=>$obj['md_imagePath_fullPath'], 'md_videoPath'=>$obj['md_videoPath_fullPath'], 'merc_id'=>$obj['merc_id'], 'qty_types'=>$obj['qty_types'], 'quantity'=>$obj['quantity'], 'features_deal'=>$obj['features_deal'], 'hot_deal'=>$obj['hot_deal'], 'features_pic'=>$obj['features_pic'], 'allow_sameperson'=>$obj['allow_sameperson'], 'category'=>$obj['category']] );
			
			array_push($ret, $erV);
            
            return $ret;	
		}
		
		
		public function getType(){
            
            $str = "Image";
            if( $this->md_type == 2 ) $str = "Video";
            return $str;
        }
		
		public function getShow(){
            
            if( $this->md_show == 0 ) { $str = "<span class='text-danger'>Expired</span>"; } 
			elseif( $this->md_show == 1 ) { $str = "<span class='text-success'>Showing</span>"; } 
			elseif( $this->md_show == 2 ) { $str = "<span class='text-info'>Coming Soon</span>"; } 

			
            return $str;
        }
		
		public function getStatus(){
            
            $str = "Activated";
            if( $this->md_status == 0 ) $str = "<span class='text-danger'>Disabled</span>";
            return $str;
        }
		
		public function get($md_id){
            global $db;
            $ret = false;
            
            $query = "SELECT * FROM `"._PREFIX_."promotions` WHERE `md_id`=?;";
            $stmt = $db->prepare($query);
            $stmt->bind_param('i', $md_id);
            $stmt->execute();
            $result = get_result($stmt);
            
            if( count($result) == 1 ){
                $this->init(array_shift( $result ));
                $ret = true;
            }
            return $ret;
        }
		
		public function getAll() {
			
            global $db;
            $ret = [];
            
			$query = "SELECT * FROM `"._PREFIX_."promotions` ORDER BY `md_create_dt` DESC;";
            $stmt = $db->prepare($query);
            $stmt->execute();
            $result = get_result($stmt);
            
            while($row = array_shift( $result )){
                $c = new SS_Media();
                $c->init($row);
                array_push($ret, $c);
            }
            return $ret;
            
        }
		
		public function SearchByPackageCode($packcode) {
			
			global $db;
            $ret = [];
			
			$packcode = '%'.$packcode.'%';
			
			$query = "SELECT * FROM `"._PREFIX_."medias` AS m, `"._PREFIX_."packages` AS p WHERE m.`pack_id` = p.`pack_id` AND p.`pack_code` LIKE ? ORDER BY m.`md_create_dt` DESC;";
            $stmt = $db->prepare($query);
			$stmt->bind_param('s', $packcode);
            $stmt->execute();
            $result = get_result($stmt);
			
			while($row = array_shift( $result )){
                $c = new SS_Media();
                $c->init($row);
                array_push($ret, $c);
            }
            return $ret;
			
		}
		
		public function SearchByPackageName($packname) {
			
			global $db;
            $ret = [];
			
			$packname = '%'.$packname.'%';
			
			$query = "SELECT * FROM `"._PREFIX_."medias` AS m, `"._PREFIX_."packages` AS p WHERE m.`pack_id` = p.`pack_id` AND p.`pack_name` LIKE ? ORDER BY m.`md_create_dt` DESC;";
            $stmt = $db->prepare($query);
			$stmt->bind_param('s', $packname);
            $stmt->execute();
            $result = get_result($stmt);
			
			while($row = array_shift( $result )){
                $c = new SS_Media();
                $c->init($row);
                array_push($ret, $c);
            }
            return $ret;
			
		}
		
		
		public function SearchByDeviceSerialNo($devSerialNo) {
			
			global $db;
            $ret = [];
			
			$devSerialNo = '%'.$devSerialNo.'%';
			
			$query = "SELECT * FROM `"._PREFIX_."medias` AS m, `"._PREFIX_."devices` AS d WHERE m.`dev_id` = d.`dev_id` AND d.`dev_serialno` LIKE ? ORDER BY m.`md_create_dt` DESC;";
            $stmt = $db->prepare($query);
			$stmt->bind_param('s', $devSerialNo);
            $stmt->execute();
            $result = get_result($stmt);
			
			while($row = array_shift( $result )){
                $c = new SS_Media();
                $c->init($row);
                array_push($ret, $c);
            }
            return $ret;
			
		}
		
		public function SearchByDeviceName($devName) {
		
			global $db;
            $ret = [];
			
			$devName = '%'.$devName.'%';
			
			$query = "SELECT * FROM `"._PREFIX_."medias` AS m, `"._PREFIX_."devices` AS d WHERE m.`dev_id` = d.`dev_id` AND d.`dev_name` LIKE ? ORDER BY m.`md_create_dt` DESC;";
            $stmt = $db->prepare($query);
			$stmt->bind_param('s', $devName);
            $stmt->execute();
            $result = get_result($stmt);
			
			while($row = array_shift( $result )){
                $c = new SS_Media();
                $c->init($row);
                array_push($ret, $c);
            }
            return $ret;
			
		}
		
		public function SearchByMerchantName($merchantName) {
		
			global $db;
            $ret = [];
			
			$merchantName = '%'.$merchantName.'%';
			
			$query = "SELECT * FROM `"._PREFIX_."promotions` AS m, `"._PREFIX_."merchants` AS mer WHERE m.`merc_id` = mer.`merc_id` AND mer.`merc_company` LIKE ? ORDER BY m.`md_create_dt` DESC;";
            $stmt = $db->prepare($query);
			$stmt->bind_param('s', $merchantName);
            $stmt->execute();
            $result = get_result($stmt);
			
			while($row = array_shift( $result )){
                $c = new SS_Media();
                $c->init($row);
                array_push($ret, $c);
            }
            return $ret;
			
		}
		
		public function SearchByDate($dateFrom, $dateTo) {
		     
			global $db;
            $ret = [];
		
			/* $query = "SELECT * FROM `form_submit` WHERE date(`createdate`) BETWEEN ? AND ? AND `groupid`=? AND (`group0`=? OR `group1`=? OR `group2`=? OR `group3`=?);";*/
			
			$query = "SELECT * FROM `"._PREFIX_."promotions` WHERE DATE(`md_startDate`) BETWEEN ? AND ? AND DATE(`md_endDate`) BETWEEN ? AND ? ORDER BY `md_create_dt` DESC;";
            $stmt = $db->prepare($query);
			$stmt->bind_param('ssss', $dateFrom, $dateTo, $dateFrom, $dateTo);
            $stmt->execute();
            $result = get_result($stmt);
            
            while($row = array_shift( $result )){
                $c = new SS_Media();
                $c->init($row);
                array_push($ret, $c);
            }
            return $ret;
		}
		
		public function getMerchantInMedia( $merc_id ){
			
            global $db;
            $TotMerchant = 0;
            
            $query = "SELECT merc_id FROM `"._PREFIX_."promotions` WHERE `merc_id`=?;";
            $stmt = $db->prepare($query);
            $stmt->bind_param('i', $merc_id);
            $stmt->execute();
			$result = $stmt->get_result();
			$numRows = $result->num_rows; 
			
			$TotMerchant = $numRows;
			
            return $TotMerchant;
        }
		
		
		public function delete( $md_id ){
			
			global $db;
            $ret = false;
			
			//select file to unlink
			$query = "SELECT md_image FROM `"._PREFIX_."promotions` WHERE `md_id` IN ($md_id);";
			$stmt = $db->prepare($query);
			//$stmt->bind_param('s',$md_id);
			$stmt->execute();
			$result = $stmt->get_result();
			$numRows = $result->num_rows;
			//$row = $result->fetch_assoc();
			
			while($row = $result->fetch_assoc()) {
				unlink("../_uploads/promotion/".$row['md_image']);
			
			} 
			 
			$query = "DELETE FROM `"._PREFIX_."promotions` WHERE `md_id` IN ($md_id);";
            $stmt = $db->prepare($query);
            //$stmt->bind_param('s', $md_id);
            $stmt->execute();
			 
			 //insert into log
			$c = new SS_Log();
			$post = array('log_subject'=>'Deleted','log_content'=>'Deleted Promotion');
			$c->create($post);	
			
			$ret = ['success','Success',"Promotion succesfully deleted!"];	
			
			return $ret;
		}
		
	}