<?php
    require_once("SS_Core.php");
    require_once("SS_ProdCat.php");
    require_once("SS_Brand.php");
    require_once("resize_image.php");

    class SS_Prod extends SS_Core
    {
        public $id;
        public $SKU;
        public $is_mastervariant;
        public $variant;
        public $name;
        public $desc;
        public $details;
        public $howto;
        public $brand_id;
        public $pc_id;
        public $rsp;
        public $ext;
        public $slug;
        public $images;
        
        public function __construct ()
        {
            $this->dt = date("Y-m-d H:i:s");
            $this->id = 0;
            $this->is_mastervariant = 0;
            $this->variant = 0;
            $this->SKU = "";
            $this->name = "";
            $this->desc = "";
            $this->howto = "";
            $this->details = "";
            $this->brand_id = 0;
            $this->pc_id = 0;
            $this->ext = "";
            $this->rsp = 0;
            $this->slug = "";
            $this->initX();
        }
        
        public function init( $row ){
            $this->id = $row['id'];
            $this->is_mastervariant = $row['is_mastervariant'];
            $this->variant = $row['variant'];
            $this->SKU = $row['sku'];
            $this->name = $row['name'];
            $this->ext = $row['ext'];
            $this->desc = $row['desc'];
            $this->slug = $row['slug'];
            $this->howto = $row['howto'];
            $this->details = $row['details'];
            $this->status = $row['status'];
            
            $this->brand_id = $row['brand_id'];
            $this->pc_id = $row['pc_id'];
            $this->rsp = $row['rsp'];
            $this->create_dt = $row['create_dt'];
            $this->update_dt = $row['update_dt'];
        }
        
        public function validateForm($obj){
            $this->images = [0,0];
            $this->exts = ["",""];
            
            global $imageTypeArray;
            
            $erV = ['','','','','','','','','',''];
            $proceed = true;
            //print_r($obj);
            if( $obj['txtSKU'] == "" ) {$erV[0] = 'SKU cannot be empty.';$proceed = false;}
            if( $obj['txtName'] == "" ) {$erV[1] = 'Name cannot be empty.';$proceed = false;}
            //if( $obj['txtDesc'] == "" ) {$erV[2] = 'Description cannot be empty.';$proceed = false;}
            //if( $obj['txtHowTo'] == "" ) {$erV[3] = 'How to cannot be empty.';$proceed = false;}
            //if( $obj['txtDetails'] == "" ) {$erV[4] = 'Details cannot be empty.';$proceed = false;}
            if( $obj['txtBrand'] == "" ) {$erV[5] = 'Please select a brand.';$proceed = false;}
            if( $obj['txtCat'] == "" ) {$erV[6] = 'Please select a category.';$proceed = false;}
            
            if( $obj['txtRSP'] == "" || !is_numeric($obj['txtRSP']) ) {$erV[7] = 'RSP cannot be empty. Only numberic';$proceed = false;}
            
            if( strlen($_FILES["txtLogo"]["name"]) > 0 ) {
                $this->images[0] = 1;
                $fileData = getimagesize($_FILES["txtLogo"]["tmp_name"]);
                $fileExt = $imageTypeArray[$fileData[2]];
                $this->exts[0] = strtolower($fileExt);
                if( !($fileExt == "JPG" || $fileExt == "PNG") ){
                    $this->images[0] = 0;
                    $erV[8] .= 'Product image file type must be jpg or png.<br>';$proceed = false;
                }

                if ($_FILES["txtLogo"]["size"] > 100000000 * 100 ) {
                    $this->images[0] = 0;
                    $erV[8] .= 'Product image must be smaller than 100 MB.<br>';$proceed = false;
                }
            }
            
            
            
            return [$proceed, $erV];
        }
        
        public function slugify($name, $id){
            
            global $db;
            $isOK = false;
            $i = 0;
            while( !$isOK ){
                $isOK = false;
                
                $slug = slugify($name);
                    
                if( $i > 0 ) $slug .= "_{$i}";
                    
                $query = "SELECT * FROM `"._PREFIX_."prods` WHERE `name`=? AND `id`<>?;";
                $stmt = $db->prepare($query);
                $stmt->bind_param('si', $slug, $id );
                $stmt->execute();
                $result = get_result($stmt);
                if( count($result) == 0 ) $isOK = true;
                
                $i++;
            }
            
            return $slug;
        }
        
        
        public function create($obj){
            global $db;
            $ret = [];
            $result = $this->validateForm($obj);
            

            $proceed = $result[0];
            $erV = $result[1];
            
            
            if( $proceed ){
                
                $query = "SELECT * FROM `"._PREFIX_."prods` WHERE `SKU`=?;";
                $stmt = $db->prepare($query);
                $stmt->bind_param('s', $obj['txtSKU']);
                $stmt->execute();
                $result = get_result($stmt);

                if( count($result) == 0 ){

                    

                    $slug = $this->slugify($obj['txtName'], -1);
                    $query = "INSERT INTO `"._PREFIX_."prods` VALUES(null, ?, ?, ?,? ,?,?,?, ?,?,?, ?,?, '', ?,?, '0');";
                    $stmt = $db->prepare($query);
                    $stmt->bind_param('iiiissssssdiss', $obj['txtMasterVariant'],$obj['txtVariantID'], $obj['txtBrand'], $obj['txtCat'], $obj['txtSKU'], $slug, $obj['txtName'], $obj['txtDesc'], $obj['txtHowTo'], $obj['txtDetails'], $obj['txtRSP'], $obj['txtStatus'], $this->dt, $this->dt);
                    $stmt->execute();
                    
$myid = mysqli_insert_id($db);
                    $row = array_shift( $result );
                    $ret = ['success','Success',"Product <u>{$obj['txtName']}</u> succesfully created!"];


                }else{
                    $ret = ['danger','Error',"Product SKU already exist!"];
                    $erV[0] = 'Product SKU already exist.';
                }
            }
            else
                $ret = ['danger','Error',"Please fill up the form."];
            
            $this->init( ['id'=>$myid, 'variant'=>$obj['txtVariantID'],'is_mastervariant'=>$obj['txtMasterVariant'], 'sku'=>$obj['txtSKU'], 'name'=>$obj['txtName'], 'rsp'=>$obj['txtRSP'], 'desc'=>$obj['txtDesc'], 'status'=>$obj['txtStatus'], 'howto'=>$obj['txtHowTo'], 'details'=>$obj['txtDetails'], 'brand_id'=>$obj['txtBrand'], 'pc_id'=>$obj['txtCat'] ]);
            array_push($ret, $erV);
            
            
            
            return $ret;
        }
        
        public function getStatus(){
            
            $str = "Active";
            if( $this->status == 0 ) $str = "Disabled";
            return $str;
        }
        
        public function getBrand(){
            
            $st = new SS_Brand();
            $st->get($this->brand_id);
            return $st->name;
        }
        
        
        public function getVariant($status){
            global $db;
            $ret = [];
            $vid = $this->id;
            
            if( $this->variant > 0 ) $vid = $this->variant;
            
            $query = "SELECT * FROM `"._PREFIX_."prods` WHERE ( (`variant`=? AND `variant`>'0') OR `id`=?) AND (`status`=? OR '-1'=?);";
            $stmt = $db->prepare($query);
            $stmt->bind_param('iiii', $vid, $vid, $status,$status);
            $stmt->execute();
            $result = get_result($stmt);
            
            while($row = array_shift( $result )){
                $c = new SS_Prod();
                $c->init($row);
                array_push($ret, $c);
            }
            return $ret;
        }
        

        
        
        public function update($obj){
            global $db;
            $ret = [];
            $result = $this->validateForm($obj);
            $proceed = $result[0];
            $erV = $result[1];
            
            //$musthave = 0;
            //if( $obj['txtMustHave'] == 1 ) $musthave = 1;
            
            if( $proceed ){
            
                $query = "SELECT * FROM `"._PREFIX_."prods` WHERE `id`=?;";
                $stmt = $db->prepare($query);
                $stmt->bind_param('i', $obj['txtID']);
                $stmt->execute();
                $result = get_result($stmt);

                if( count($result) == 1 ){


                    $query = "SELECT * FROM `"._PREFIX_."prods` WHERE `sku`=? AND `id`<>?;";
                    $stmt = $db->prepare($query);
                    $stmt->bind_param('si', $obj['txtSKU'], $obj['txtID']);
                    $stmt->execute();
                    $result = get_result($stmt);

                    if( count($result) == 0 ){
                        $slug = $this->slugify($obj['txtName'], $obj['txtID']);
                        
                        $eq = "";
                        if( $this->images[0] == 1 ){
                            $ext = $this->exts[0];
                            $target_file = "../_uploads/products/{$obj['txtSKU']}.{$ext}";
                            $target_file2 = "../_uploads/products/{$obj['txtID']}.{$ext}";
                            if (move_uploaded_file($_FILES["txtLogo"]["tmp_name"], $target_file2)) {
                                
                                resizeImg($target_file2, $target_file , 800,800);
                                unlink($target_file2);
                                $eq .= ", `ext`='{$ext}' ";
                            }
                        }

                        $query = "UPDATE `"._PREFIX_."prods` SET `variant`=?, `is_mastervariant`=?, `rsp`=?, `brand_id`=?, `pc_id`=?, `slug`=?, `sku`=?, `name`=?, `desc`=?, `howto`=?, `details`=?, `status`=?, `update_dt`=? {$eq} WHERE `id`=?;";
                        $stmt = $db->prepare($query);
                        $stmt->bind_param('iidiissssssisi', $obj['txtVariantID'],$obj['txtMasterVariant'], $obj['txtRSP'], $obj['txtBrand'], $obj['txtCat'], $slug, $obj['txtSKU'], $obj['txtName'], $obj['txtDesc'], $obj['txtHowTo'], $obj['txtDetails'], $obj['txtStatus'], $this->dt, $obj['txtID']);
                        $stmt->execute();
                        
                        

                        $ret = ['success','Success',"Product <u>{$obj['txtName']}</u> succesfully updated!"];
                    }else{
                        $ret = ['danger','Error',"Product SKU already exist!"];
                        $erV[0] = 'Product SKU already exist.';
                    }

                }else{
                    $ret = ['danger','Error',"Invalid Product ID!"];
                }
            }
            else
                $ret = ['danger','Error',"Please fill up the form."];
            
            $this->init( ['id'=>$obj['txtID'], 'variant'=>$obj['txtVariantID'],'is_mastervariant'=>$obj['txtMasterVariant'], 'ext'=>$ext,'rsp'=>$obj['txtRSP'], 'SKU'=>$obj['txtSKU'], 'name'=>$obj['txtName'], 'sku'=>$obj['txtSKU'], 'desc'=>$obj['txtDesc'], 'status'=>$obj['txtStatus'], 'howto'=>$obj['txtHowTo'], 'details'=>$obj['txtDetails'], 'brand_id'=>$obj['txtBrand'], 'pc_id'=>$obj['txtCat']] );
            array_push($ret, $erV);
            
            
            return $ret;
        }
        public function get($id){
            global $db;
            $ret = false;
            
            $query = "SELECT * FROM `"._PREFIX_."prods` WHERE `id`=?;";
            $stmt = $db->prepare($query);
            $stmt->bind_param('i', $id);
            $stmt->execute();
            $result = get_result($stmt);
            
            if( count($result) == 1 ){
                $this->init(array_shift( $result ));
                $ret = true;
            }
            return $ret;
        }
        
        public function getBySlug($slug){
            global $db;
            $ret = false;
            
            $query = "SELECT * FROM `"._PREFIX_."prods` WHERE `slug`=?;";
            $stmt = $db->prepare($query);
            $stmt->bind_param('s', $slug);
            $stmt->execute();
            $result = get_result($stmt);
            
            if( count($result) == 1 ){
                $this->init(array_shift( $result ));
                $ret = true;
            }
            return $ret;
        }
        
        public function getAllByBrand($status, $bid, $mv){
            global $db;
            $ret = [];

            $brands = "";
            if( $bid != -1 ) $brands = " AND `brand_id`='{$bid}'";
            
            $mvs = "";
            if( $mv != -1 ) $mvs = " AND `is_mastervariant`='{$mv}'";
            
            $query = "SELECT * FROM `"._PREFIX_."prods` WHERE (`status`=? OR '-1'=?) {$brands} {$mvs};";
            $stmt = $db->prepare($query);
            $stmt->bind_param('ii', $status,$status);
            $stmt->execute();
            $result = get_result($stmt);
            
            while($row = array_shift( $result )){
                $c = new SS_Prod();
                $c->init($row);
                array_push($ret, $c);
            }
            return $ret;
        }
        
        public function getAllMasterVariant(){
            global $db;
            $ret = [];
            
            $query = "SELECT * FROM `"._PREFIX_."prods` WHERE `is_mastervariant`='1' ORDER BY `name`;";
            $stmt = $db->prepare($query);
            $stmt->execute();
            $result = get_result($stmt);
            
            while($row = array_shift( $result )){
                $c = new SS_Prod();
                $c->init($row);
                array_push($ret, $c);
            }
            return $ret;
        }
        
        
        public function getAll( $status, $size = -1, $page = 0 ){
            global $db;
            $ret = [];
            
            $strx = "";
            if( $size > -1 ){
                $strx = "LIMIT {$page},{$size}";
            }
            
            $query = "SELECT * FROM `"._PREFIX_."prods` WHERE (`status`=? OR '-1'=?) {$strx};";
            $stmt = $db->prepare($query);
            $stmt->bind_param('ii', $status,$status);
            $stmt->execute();
            $result = get_result($stmt);
            
            while($row = array_shift( $result )){
                $c = new SS_Prod();
                $c->init($row);
                array_push($ret, $c);
            }
            return $ret;
        }
        
        public function removeBestSeller( $obj ){
            global $db;
            
            $query = "SELECT * FROM `"._PREFIX_."prods` WHERE `sku`=?;";
            $stmt = $db->prepare($query);
            $stmt->bind_param('s', $obj['txtID']);
            $stmt->execute();
            $result = get_result($stmt);
            
            if( count($result) == 1 ){
                $row = array_shift( $result );
            
                $query = "DELETE FROM `"._PREFIX_."bestsellers` WHERE `sku`=?;";
                $stmt = $db->prepare($query);
                $stmt->bind_param('s', $obj['txtID']);
                $stmt->execute();
            }
            
            $ret = ['success','Success',"Bestseller <u>{$row['name']}</u> succesfully removed!"];
            return $ret;
        }
        public function removeHotPick( $obj ){
            global $db;
            
            $query = "SELECT * FROM `"._PREFIX_."prods` WHERE `sku`=?;";
            $stmt = $db->prepare($query);
            $stmt->bind_param('s', $obj['txtID']);
            $stmt->execute();
            $result = get_result($stmt);
            
            if( count($result) == 1 ){
                $row = array_shift( $result );
            
                $query = "DELETE FROM `"._PREFIX_."hotpicks` WHERE `sku`=?;";
                $stmt = $db->prepare($query);
                $stmt->bind_param('s', $obj['txtID']);
                $stmt->execute();
            }
            
            $ret = ['success','Success',"Bestseller <u>{$row['name']}</u> succesfully removed!"];
            return $ret;
        }
        
        public function createBestSeller($obj){
            global $db;
            
            $query = "SELECT * FROM `"._PREFIX_."prods` WHERE `sku`=?;";
            $stmt = $db->prepare($query);
            $stmt->bind_param('s', $obj['txtSKU']);
            $stmt->execute();
            $result = get_result($stmt);
            
            if( count($result) == 1 ){
                $row = array_shift( $result );
                
                $query = "INSERT INTO `"._PREFIX_."bestsellers` VALUES(?);";
                $stmt = $db->prepare($query);
                $stmt->bind_param('s', $obj['txtSKU']);
                $stmt->execute();
            }
            
            $ret = ['success','Success',"Bestseller <u>{$row['name']}</u> succesfully added!"];
            return $ret;
        }
        
        public function createHotPick($obj){
            global $db;
            
            $query = "SELECT * FROM `"._PREFIX_."prods` WHERE `sku`=?;";
            $stmt = $db->prepare($query);
            $stmt->bind_param('s', $obj['txtSKU']);
            $stmt->execute();
            $result = get_result($stmt);
            
            if( count($result) == 1 ){
                $row = array_shift( $result );
                
                $query = "INSERT INTO `"._PREFIX_."hotpicks` VALUES(?);";
                $stmt = $db->prepare($query);
                $stmt->bind_param('s', $obj['txtSKU']);
                $stmt->execute();
            }
            
            $ret = ['success','Success',"Bestseller <u>{$row['name']}</u> succesfully added!"];
            return $ret;
        }
        
        public function getProdBySKU($sku){
            global $db;
            $ret = false;
            
            $query = "SELECT * FROM `"._PREFIX_."prods` WHERE `sku`=?;";
            $stmt = $db->prepare($query);
            $stmt->bind_param('s', $sku);
            $stmt->execute();
            $result = get_result($stmt);
            
            if( count($result) == 1 ){
                $this->init(array_shift( $result ));
                $ret = true;
            }
            return $ret;
        }
        
        public function getAllExceptBestseller( $status ){
            global $db;
            $ret = [];
            
            $strx = "AND `sku` NOT IN (SELECT `sku` FROM `"._PREFIX_."bestsellers`)";
            $query = "SELECT `sku`,`name` FROM `"._PREFIX_."prods` WHERE (`status`=? OR '-1'=?) {$strx};";
            $stmt = $db->prepare($query);
            $stmt->bind_param('ii', $status,$status);
            $stmt->execute();
            $result = get_result($stmt);
            
            while($row = array_shift( $result )){
                $c = new SS_Prod();
                $c->init($row);
                array_push($ret, $c);
            }
            return $ret;
        }
        
        public function getAllExceptHotPick( $status ){
            global $db;
            $ret = [];
            
            $strx = "AND `sku` NOT IN (SELECT `sku` FROM `"._PREFIX_."hotpicks`)";
            $query = "SELECT `sku`,`name` FROM `"._PREFIX_."prods` WHERE (`status`=? OR '-1'=?) {$strx};";
            $stmt = $db->prepare($query);
            $stmt->bind_param('ii', $status,$status);
            $stmt->execute();
            $result = get_result($stmt);
            
            while($row = array_shift( $result )){
                $c = new SS_Prod();
                $c->init($row);
                array_push($ret, $c);
            }
            return $ret;
        }
        
        
        
        public function getListingTotal( $status, $bcid, $pcid, $pmcid, $size = -1, $kw = ""){
            global $db;
            $ret = [];
            $search= "";
            if( strlen($kw) > 0 ){
                $search = " AND `name` LIKE '%{$kw}%' ";
            }
            
            $brands= "";
            if( $bcid > 0 ){
                $brands = " AND `brand_id`='{$bcid}' ";
            }
            
            $prodcat = "";
            if( $pcid > 0 ){
                $prodcat = " AND `pc_id`='{$pcid}' ";
            }
            
            $promos = "";
            if( $pmcid > 0 ){
                $promos = " AND `id` IN (SELECT `pid` FROM `"._PREFIX_."promo_list` WHERE `pmcid`='{$pmcid}') ";
            }
            
            $query = "SELECT COUNT(`id`) AS `total` FROM `"._PREFIX_."prods` WHERE `variant`='0' AND (`status`=? OR '-1'=?) {$search} {$brands} {$prodcat}  {$promos};";
            
            $stmt = $db->prepare($query);
            $stmt->bind_param('ii', $status,$status);
            $stmt->execute();
            $result = get_result($stmt);
            $row = array_shift( $result );
            return $row['total'];
        }
        
        public function getListing( $status, $bcid, $pcid = 0, $pmcid =0, $size = -1, $page = 0, $sortby = 3, $kw = "" ){
            global $db;
            $ret = [];
            $page--;
            $strx = "";
            
            
            $search= "";
            if( strlen($kw) > 0 ){
                $search = " AND `name` LIKE '%{$kw}%' ";
            }
            
            
            if( $size > -1 ){
                $s = $page * $size;
                $strx = "LIMIT {$s},{$size}";
            }
            
            $brands= "";
            if( $bcid > 0 ){
                $brands = " AND `brand_id`='{$bcid}' ";
            }
            
            $prodcat = "";
            if( $pcid > 0 ){
                $prodcat = " AND `pc_id`='{$pcid}' ";
            }
            
            $promos = "";
            if( $pmcid > 0 ){
                $promos = " AND `id` IN (SELECT `pid` FROM `"._PREFIX_."promo_list` WHERE `pmcid`='{$pmcid}') ";
            }
            
            $arrSorts = ["",
                "`rsp`","`rsp` DESC",
                "`name`","`name` DESC"
            ];
            
            
            $query = "SELECT * FROM `"._PREFIX_."prods` WHERE `variant`='0' AND (`status`=? OR '-1'=?) {$search} {$brands} {$prodcat}  {$promos} ORDER BY {$arrSorts[$sortby]} {$strx};";
            
            //echo $query;
            
            $stmt = $db->prepare($query);
            $stmt->bind_param('ii', $status,$status);
            $stmt->execute();
            $result = get_result($stmt);
            
            while($row = array_shift( $result )){
                $c = new SS_Prod();
                $c->init($row);
                array_push($ret, $c);
            }
            return $ret;
        }
        
        
        
        
        public function getHotPickListing( $status, $bcid, $pcid, $pmcid, $size = -1, $page = 0, $sortby = 3 ){
            global $db;
            $ret = [];
            $page--;
            $strx = "";
            if( $size > -1 ){
                $s = $page * $size;
                $strx = "LIMIT {$s},{$size}";
            }
            
            $brands= "";
            if( $bcid > 0 ){
                $brands = " AND `brand_id`='{$bcid}' ";
            }
            
            $prodcat = "";
            if( $pcid > 0 ){
                $prodcat = " AND `pc_id`='{$pcid}' ";
            }
            
            $promos = "";
            if( $pmcid > 0 ){
                $promos = " AND `id` IN (SELECT `pid` FROM `"._PREFIX_."promo_list` WHERE `pmcid`='{$pmcid}') ";
            }
            
            $arrSorts = ["",
                "`rsp`","`rsp` DESC",
                "`name`","`name` DESC"
            ];
            
            
            $query = "SELECT * FROM `"._PREFIX_."prods` WHERE (`status`=? OR '-1'=?) AND (`sku` IN (SELECT `sku` FROM `"._PREFIX_."hotpicks`) ) {$brands} {$prodcat}  {$promos} ORDER BY {$arrSorts[$sortby]} {$strx};";
            
            
            
            $stmt = $db->prepare($query);
            $stmt->bind_param('ii', $status,$status);
            $stmt->execute();
            $result = get_result($stmt);
            
            while($row = array_shift( $result )){
                $c = new SS_Prod();
                $c->init($row);
                array_push($ret, $c);
            }
            return $ret;
        }
        
        
        public function getBestSellerListing( $status, $bcid, $pcid, $pmcid, $size = -1, $page = 0, $sortby = 3 ){
            global $db;
            $ret = [];
            $page--;
            $strx = "";
            if( $size > -1 ){
                $s = $page * $size;
                $strx = "LIMIT {$s},{$size}";
            }
            
            $brands= "";
            if( $bcid > 0 ){
                $brands = " AND `brand_id`='{$bcid}' ";
            }
            
            $prodcat = "";
            if( $pcid > 0 ){
                $prodcat = " AND `pc_id`='{$pcid}' ";
            }
            
            $promos = "";
            if( $pmcid > 0 ){
                $promos = " AND `id` IN (SELECT `pid` FROM `"._PREFIX_."promo_list` WHERE `pmcid`='{$pmcid}') ";
            }
            
            $arrSorts = ["",
                "`rsp`","`rsp` DESC",
                "`name`","`name` DESC"
            ];
            
            
            $query = "SELECT * FROM `"._PREFIX_."prods` WHERE (`status`=? OR '-1'=?) AND (`sku` IN (SELECT `sku` FROM `"._PREFIX_."bestsellers`) ) {$brands} {$prodcat}  {$promos} ORDER BY {$arrSorts[$sortby]} {$strx};";
            
            
            
            $stmt = $db->prepare($query);
            $stmt->bind_param('ii', $status,$status);
            $stmt->execute();
            $result = get_result($stmt);
            
            while($row = array_shift( $result )){
                $c = new SS_Prod();
                $c->init($row);
                array_push($ret, $c);
            }
            return $ret;
        }
        
        
        
    }
?>  