<?php

class productphotogallery {

    var $pagename = 'index.php?module=productphotogallery';
    var $int_glcode;
    var $chr_read;
    var $chr_star;
    var $chr_publish;
    var $int_displayorder;
    var $chr_delete = 'Y';
    var $dt_createdate;
    var $dt_modifydate;
    var $oldint_displayorder;
    var $numofrows;
    var $numofpages;
    var $orderby = 'int_displayorder';
    var $ordertype = 'asc';
    var $searchby = '0';
    var $searchtxt;
    var $start = 1;
    var $pagesize = DEFAULT_PAGESIZE;
    var $pagenumber = '1';
    var $lastinsertid;
    var $urlwithpara = '';
    var $urlwithpoutsearch = '';
    var $urlwithoutsort = '';
    var $urlwithoutpaging = '';
    var $configObj;
    // var $sortvar = '<img alt="sorting" src="'.GLOBAL_ADMIN_IMAGES_PATH.'/arrow-up.png" style="vertical-align:middle;">'; // This is for sort image
    var $filterby = '0';
    var $urlwithoutfilter = '';
    var $display_limit_array = array(5, 10, 15, 30);
    var $varpostdata = array();
    var $thumb_width = TRADESHOW_THUMB_WIDTH;
    var $thumb_height = TRADESHOW_THUMB_HEIGHT;

    function productphotogallery($configObj) {
        $this->sortvar = '<img alt="sorting" src="' . GLOBAL_ADMIN_IMAGES_PATH . 'arrow-up.png" style="vertical-align:middle;">';
        $this->configObj = $configObj;
    }

    function intitialize($view = '') {
        $this->searchby = (isset($_REQUEST['searchby'])) ? $_REQUEST['searchby'] : $this->searchby;
        $_REQUEST['searchtxt'] = ($_REQUEST['type'] == 'autosearch') ? $_REQUEST['term'] : $_REQUEST['searchtxt'];
        $this->searchbyVal = (isset($_REQUEST['searchbyVal'])) ? $_REQUEST['searchbyVal'] : $this->searchbyVal;
        $this->searchtxt = (isset($_REQUEST['searchtxt'])) ? $this->configObj->glLibraryObj->rem_special_chars($_REQUEST['searchtxt']) : '';
        $this->searchtxtjs = (isset($_REQUEST['searchtxt'])) ? $this->configObj->glLibraryObj->rem_special_chars_js($_REQUEST['searchtxt']) : '';

        $this->orderby = (isset($_REQUEST['orderby'])) ? $_REQUEST['orderby'] : $this->orderby;
        $this->ordertype = (isset($_REQUEST['ordertype'])) ? $_REQUEST['ordertype'] : $this->ordertype;
        $this->filterby = (isset($_REQUEST['filterby'])) ? $_REQUEST['filterby'] : $this->filterby;

        if (isset($_REQUEST['sorting'])) {
            if ($this->ordertype == "asc") {   // This is for sort image
                $this->ordertype = "desc";

                $this->sortvar = "<img alt=\"sorting\" src=\"" . GLOBAL_ADMIN_IMAGES_PATH . "arrow-down.png\" style=\"vertical-align:middle;\">";
            } else if ($this->ordertype == "desc") {   // This is for sort image
                $this->ordertype = "asc";
                $this->sortvar = "<img alt=\"sorting\" src=\"" . GLOBAL_ADMIN_IMAGES_PATH . "arrow-up.png\" style=\"vertical-align:middle;\">";
            }
        }


        $this->pagesize = (isset($_REQUEST['pagesize'])) ? $_REQUEST['pagesize'] : $this->pagesize;
        $this->pagenumber = (isset($_REQUEST['pagenumber'])) ? $_REQUEST['pagenumber'] : $this->pagenumber;

        $this->start = ($this->pagenumber - 1 ) * $this->pagesize;
    }

    function CountRows() {
        $this->intitialize($view);
        if (trim($this->searchtxt) != '') {
            $whereclause .= ($this->searchby == '0') ? " and var_title like '%$this->searchtxt%'" : " and $this->searchby like '%$this->searchtxt%'";
        }
        if ($this->filterby != '0' && $this->filterby != '') {
            $filterarray = explode('-', $this->filterby);
            $whereclause .=" and $filterarray[0] = '$filterarray[1]'";
        }
        $sqlCountPages = "select count(1) as total from " . DB_PREFIX . "tradeshows where chr_delete = 'N' $whereclause ";
        $rs = $this->configObj->glDbObj->get_sql_row($sqlCountPages);
        $this->numofrows = $rs['total'];
        return $rs['total'];
    }

    function CountAssignedPosition($sql) {
        $this->configObj->glDbObj->resetfields(); // Reset the object
        $rs = $this->configObj->glDbObj->get_sql_row($sql);
        return $rs['total'];
    }

    function Generateurl() {
        $this->urlwithpara = $this->pagename . '&' . 'pagesize=' . $this->pagesize . '&numofrows=' . $this->numofrows . '&orderby=' . $this->orderby . '&ordertype=' . $this->ordertype . '&searchby=' . $this->searchby . '&searchtxt=' . $this->searchtxtjs . '&pagenumber=' . $this->pagenumber . '&filterby=' . $this->filterby;
        $this->urlwithpoutsearch = $this->pagename . '&' . 'pagesize=' . $this->pagesize . '&orderby=' . $this->orderby . '&ordertype=' . $this->ordertype . '&filterby=' . $this->filterby;
        $this->urlwithoutsort = $this->pagename . '&' . 'pagesize=' . $this->pagesize . '&numofrows=' . $this->numofrows . '&searchby=' . $this->searchby . '&searchtxt=' . $this->searchtxtjs . '&pagenumber=' . $this->pagenumber . '&ordertype=' . $this->ordertype . '&filterby=' . $this->filterby;
        $this->urlwithoutpaging = $this->pagename . '&orderby=' . $this->orderby . '&ordertype=' . $this->ordertype . '&searchby=' . $this->searchby . '&searchtxt=' . $this->searchtxtjs . '&filterby=' . $this->filterby;
        $this->urlwithoutfilter = $this->pagename . '&' . 'pagesize=' . $this->pagesize . '&orderby=' . $this->orderby . '&ordertype=' . $this->ordertype . '&searchby=' . $this->searchby . '&searchtxt=' . $this->searchtxtjs;
        $this->configObj->AutoSearchUrl = $this->urlwithpara . "&type=autosearch&searchbyVal=" . $this->searchbyVal;
    }

    function org_generateParam($view = 'tradeshows', $actionurl = 'index.php?module=tradeshows&action=add', $searchArray = array("var_title" => "Username"), $table = 'DB_PREFIX.tradeshows', $position = 'top') {
        $filterPos = ($position == 'top') ? 'FT' : 'FB';

        if ($this->configObj->glSessionObj->value('admin_id') == '1') {
            $filterstar = array('filterarray' => array('chr_read-Y' => 'Read Only',
                    'chr_read-N' => 'Unread Only',
                    'chr_star-Y' => 'Star Only',
                    'chr_star-N' => 'Unstar Only',
                ),
                'filterurl' => $this->urlwithoutfilter,
                'filterposition' => $filterPos,
                'filterby' => $this->filterby
            );
        } else {
            $filterstar = array();
        }

        return array('pageurl' => $this->pagename,
            'heading' => $view,
            'listImage' => 'add-new-user-icon.png',
            'tablename' => $table,
            'position' => $position,
            'actionImage' => 'add-new-button-blue.gif',
            'actionImageHover' => 'add-new-button-blue-hover.gif',
            'actionUrl' => $actionurl,
            'search' => array('searchArray' => $searchArray,
                'searchBy' => $this->searchby,
                'searchText' => $this->searchtxt,
                //'searchUrl'    => $this->urlwithpoutsearch
                'searchUrl' => $this->urlwithpoutsearch
            ),
            'filter' => $filterstar,
            'paging' => array('pagenumber' => $this->pagenumber,
                'noofpages' => $this->noofpages,
                'numofrows' => $this->numofrows,
                'pagingurl' => $this->urlwithpara
            ),
            'display' => array('displayurl' => $this->urlwithoutpaging,
                'pagesize' => $this->pagesize,
                'limitarray' => $this->display_limit_array,
            )
        );
    }

    function org_generateParam_withoutfilter($view = 'tradeshows', $actionurl = 'index.php?module=tradeshows&action=add', $searchArray = array("var_title" => "Username"), $table = 'DB_PREFIX.tradeshows', $position = 'top') {
        $filterPos = ($position == 'top') ? 'FT' : 'FB';
        if ($this->configObj->glSessionObj->value('admin_id') == '1') {
            $filterstar = array('filterarray' => array('chr_read-Y' => 'Read Only',
                    'chr_read-N' => 'Unread Only',
                    'chr_star-Y' => 'Star Only',
                    'chr_star-N' => 'Unstar Only',
                ),
                'filterurl' => $this->urlwithoutfilter,
                'filterposition' => $filterPos,
                'filterby' => $this->filterby
            );
        } else {
            $filterstar = array();
        }
        return array('pageurl' => $this->pagename,
            'heading' => $view,
            'listImage' => 'add-new-user-icon.png',
            'tablename' => $table,
            'position' => $position,
            'actionImage' => 'add-new-button-blue.gif',
            'actionImageHover' => 'add-new-button-blue-hover.gif',
            'actionUrl' => $actionurl,
            'search' => array('searchArray' => $searchArray,
                'searchBy' => $this->searchby,
                'searchText' => $this->searchtxt,
                //'searchUrl'    => $this->urlwithpoutsearch
                'searchUrl' => $this->urlwithpoutsearch
            ),
            'filter' => array('filterarray' => array('chr_read-Y' => 'Read Only',
                    'chr_read-N' => 'Unread Only',
                    'chr_star-Y' => 'Star Only',
                    'chr_star-N' => 'Unstar Only',
                    'chr_publish-Y' => 'Publish Only',
                    'chr_publish-N' => 'Unpublish Only',
                ),
                'filterurl' => $this->urlwithoutfilter,
                'filterposition' => $filterPos,
                'filterby' => $this->filterby
            ),
            'paging' => array('pagenumber' => $this->pagenumber,
                'noofpages' => $this->noofpages,
                'numofrows' => $this->numofrows,
                'pagingurl' => $this->urlwithpara
            ),
            'display' => array('displayurl' => $this->urlwithoutpaging,
                'pagesize' => $this->pagesize,
                'limitarray' => $this->display_limit_array,
            )
        );
    }

    function update_display_order($ids, $values, $oldvalues) {

        $tablename = DB_PREFIX . "productphotogallery";
        for ($i = 0; $i < count($ids); $i++) {
            // Updation Of the Display Order
            if ($values[$i] != $oldvalues[$i]) {
                $this->configObj->glDbObj->resetfields(); // Reset the object
                $this->configObj->glDbObj->resetfields();
                $this->configObj->glDbObj->setQueryType('select');
                $this->configObj->glDbObj->setTable($tablename);
                $this->configObj->glDbObj->addColumn('count(1) as total');
                $this->configObj->glDbObj->setWhere("int_displayorder=" . $values[$i] . " and chr_delete = 'N'");
                //echo $this->configObj->glDbObj->buildQuery();exit;
                $rs = $this->configObj->glDbObj->get_sql_row($this->configObj->glDbObj->buildQuery());
                if ($rs['total'] > 0) {
                    if ($values[$i] > $oldvalues[$i]) {


                        $sql = "UPDATE $tablename SET int_displayorder =
                    CASE int_displayorder
                    WHEN $oldvalues[$i] THEN $values[$i]
                    ELSE int_displayorder - 1
                    END
                    WHERE int_displayorder BETWEEN $oldvalues[$i] AND $values[$i]";
                        $this->configObj->glDbObj->query($sql);
                    } else {

                        $sql = "UPDATE $tablename SET int_displayorder =
                    CASE int_displayorder
                    WHEN $oldvalues[$i] THEN $values[$i]
                    ELSE int_displayorder + 1
                    END
                    WHERE int_displayorder BETWEEN $values[$i] AND $oldvalues[$i] ";

                        $this->configObj->glDbObj->query($sql);
                    }
                } else {
                    $this->configObj->glDbObj->resetfields();
                    $this->configObj->glDbObj->setTable($tablename);
                    $this->configObj->glDbObj->setQueryType('update');
                    $this->configObj->glDbObj->addColumn('int_displayorder');
                    $this->configObj->glDbObj->addValue($values[$i]);
                    $this->configObj->glDbObj->setWhere('int_glcode=' . $ids[$i] . '');
                    //echo "33".$this->configObj->glDbObj->buildQuery();
                    $this->configObj->glDbObj->query($this->configObj->glDbObj->buildQuery());
                }
            }
        }
    }

    function message($msg = '') {
        (string) $display_output = null;
        if ($msg != "") {
            $display_output .="<div class=\"dverrorcustom\"><div class=\"confirmation-div\"><strong>$msg</strong></div></div>";
        }
        return $display_output;
    }

    function get_fk_tml_modules($module) {
        $sql = "SELECT int_glcode from " . DB_PREFIX . "modules WHERE var_modulename='$module' and chr_publish='Y' and chr_delete='N'";
        $rs = $this->configObj->glDbObj->get_sql_row($sql);
        $fk_tml_modules = 0;
        $fk_tml_modules = $rs['int_glcode'];
        return $fk_tml_modules;
    }

    function get_fk_pages_modules_positions($eid) {
        $sql = "SELECT fk_pages_modules_positions from " . DB_PREFIX . "tradeshows WHERE int_glcode = $eid";
        $rs = $this->configObj->glDbObj->get_sql_row($sql);
        $fk_pages_modules_positions = $rs['fk_pages_modules_positions'];
        return $fk_pages_modules_positions;
    }

    function is_photoused($fk_tml_modules) {
        $deleteids = $_REQUEST['dids'];
        $deletearray = explode(',', $deleteids);
        $totaldeletedrecords = count($deletearray);
        $is_assigned = 0;
        $delcount = 0;
        for ($i = 0; $i < $totaldeletedrecords; $i++) {
            $sql = "Update " . DB_PREFIX . "productphotogallery set chr_delete='Y',dt_modifydate=NOW(), var_ipaddress='" . $_SERVER['REMOTE_ADDR'] . "',var_adminuser='" . ADMIN_NAME . "' where int_glcode='$deletearray[$i]'";
            $this->configObj->glDbObj->query($sql);
            $delcount++;
            $this->configObj->glLibraryObj->insertinlogmanager(93, DB_PREFIX . 'productphotogallery', 'var_image', $deletearray[$i], 'D');
        }
        $this->load_productphotogallery();
    }

    function loadCount() {
        $this->numofrows = $this->countFunction;
        $this->noofpages = intval($this->numofrows / $this->pagesize);
        $this->noofpages = (($this->numofrows % $this->pagesize) > 0) ? ($this->noofpages + 1) : ($this->noofpages);
        $this->configObj->glTplObj->set('numofrows', $this->numofrows);
        $this->Generateurl();
        //	$this->Generateurl();
    }

    function load_productphotogallery() {
        if ($_REQUEST['task'] == 'orderupdate') {
            $updateids = $_REQUEST['uids'];
            $updatevalues = $_REQUEST['uvals'];
            $updateoldvalues = $_REQUEST['uoldvals'];
            $upidsarray = explode(',', $updateids);
            $upvalsarray = explode(',', $updatevalues);
            $upoldvalsarray = explode(',', $updateoldvalues);

            $this->update_display_order($upidsarray, $upvalsarray, $upoldvalsarray);
        }
        $this->pagename = 'index.php?module=productphotogallery'; // Attribute of Page Name

        $this->configObj->glTplObj->set('photoTab', true);

        $this->configObj->glTplObj->set('numofrows', $this->numofrows);
        if ($_REQUEST['ajax'] != 'Y') {
            $this->orderby = 'int_displayorder';
        }

        $this->loadCount_photo('CountPhotogalleryRows');
        //$this->Generateurl();
        $result = $this->selectall_productphotogallery();
        $this->configObj->glTplObj->set('result', $result);


        $view = 'Photo Gallery';
        $this->configObj->glTplObj->set('name', $tradeshows_title['var_title']);
        $actionurl = 'index.php?module=productphotogallery&action=add';

        $searchArray = array("var_title" => "Banner Title");

        $table = DB_PREFIX . 'phototogallery';

        $parmas = $this->org_generateParam_withoutfilter($view, $actionurl, $searchArray, $table);

        $this->configObj->glTplObj->set('headerpanel', $this->configObj->glLibraryObj->generateHeaderPanel($parmas));
        $this->configObj->glTplObj->set('pagingTop', $this->configObj->glLibraryObj->generatePagingPannel($parmas));
        $this->configObj->glTplObj->set('pagingBottom', $this->configObj->glLibraryObj->generatePagingPannel($this->org_generateParam_withoutfilter($view, $actionurl, $searchArray, $table, 'bottom')));

        // Set the sorting image
        $tmpsetsortvar = 'setsortimg' . $this->orderby;
        $$finalsortvar = $tmpsetsortvar;
        $this->configObj->glTplObj->set($$finalsortvar, $this->sortvar);
        //For Note
        $notemessagebox = $this->configObj->glLibraryObj->notemessage("Note : ", "Adding Photo are incremental, once you add a new photo it will display as first photo and previous photo will move down in the order.");
        $this->configObj->glTplObj->set('notemessagebox', $notemessagebox);
        if ($_REQUEST['msg'] == 'add') {
            $messagebox = $this->configObj->glLibraryObj->message("The record has been successfully saved.");
            $this->configObj->glTplObj->set('messagebox', $messagebox);
        }

        if ($this->configObj->isAjaxSet) {
            echo $this->configObj->glTplObj->process('productphotogallery.tpl.php');
            exit;
        } else {
            $this->configObj->adminContentPanel = $this->configObj->glTplObj->process('productphotogallery.tpl.php');
        }
    }

    function select_productphotogallery($id) {
        $dtformat = DEFAULT_DATEFORMAT;

        $this->configObj->glDbObj->resetfields();
        $this->configObj->glDbObj->setQueryType('select');
        $this->configObj->glDbObj->setTable(DB_PREFIX . 'productphotogallery');
        $this->configObj->glDbObj->addColumn("*,DATE_FORMAT(dt_createdate, '" . $dtformat . "') as testidate");
        $this->configObj->glDbObj->setWhere("int_glcode =" . $id);
        $row = $this->configObj->glDbObj->get_sql_row($this->configObj->glDbObj->buildQuery());
        return $row;
    }

    function selectall_productphotogallery() {
 
        $dtformat = DEFAULT_DATEFORMAT;
        if ($_REQUEST['ajax'] != 'Y' || $_REQUEST['action'] == 'makeDefalutImage') {
            $this->orderby = 'int_displayorder';
        }
        $this->configObj->glDbObj->resetfields(); // Reset the object
        $this->configObj->glDbObj->setQueryType('select');    // Set the Table
        $this->configObj->glDbObj->setTable(DB_PREFIX . 'productphotogallery');
        $this->configObj->glDbObj->addColumn("*,DATE_FORMAT(dt_createdate, '" . $dtformat . "') as testidate");
        $whereclause = "chr_delete = 'N' ";
        $orderby = (isset($_REQUEST['orderby'])) ? 'order by ' . $this->orderby . ' ' . $this->ordertype : 'order by int_displayorder';
        if (trim($this->searchtxt) != '') {
            $whereclause .= ($this->searchby == '0') ? " and var_title like \"%" . mysql_real_escape_string($this->searchtxt) . "%\" " : " and $this->searchby like \"%" . mysql_real_escape_string($this->searchtxt) . "%\"";
        }
        if ($this->filterby != '0' && $this->filterby != '') {
            $filterarray = explode('-', $this->filterby);
            $whereclause .=" and $filterarray[0] = '$filterarray[1]'";
        }
        if ($_REQUEST['type'] == 'autosearch') {
            $orderby = (isset($_REQUEST['orderby'])) ? 'order by ' . $this->orderby . ' ' . $this->ordertype : 'order by int_displayorder';
            $searchbyVal = (!empty($this->searchbyVal)) ? " and {$this->searchbyVal} like '%" . $this->searchtxt . "%' " : "";
            $autoSearchQry = "select int_glcode ,var_title AutoVal FROM " . DB_PREFIX . "productphotogallery as pg where $whereclause $searchbyVal group by var_title $orderby";
            $this->configObj->glLibraryObj->GetAutoSearch($autoSearchQry);
        }
        $this->configObj->glDbObj->setWhere($whereclause);
        $this->configObj->glDbObj->setOrderBy($this->orderby . ' ' . $this->ordertype);
        $this->configObj->glDbObj->setLimit($this->start . ', ' . $this->pagesize);

        $rs = $this->configObj->glDbObj->query($this->configObj->glDbObj->buildQuery());
        return $rs;
    }

    function loadCount_photo($function) {
        $this->intitialize();
        $this->{$function}();
        $this->noofpages = intval($this->numofrows / $this->pagesize);
        $this->noofpages = (($this->numofrows % $this->pagesize) > 0) ? ($this->noofpages + 1) : ($this->noofpages);
        $this->configObj->glTplObj->set('numofrows', $this->numofrows);
        $this->Generateurl();
    }

    function CountPhotogalleryRows() {
        $this->intitialize();
        if (trim($this->searchtxt) != '') {
            $whereclause .= ($this->searchby == '0') ? " and var_title like '%" . $this->configObj->glDbObj->addSlashes($this->searchtxt) . "%'" : " and $this->searchby like '%" . $this->configObj->glDbObj->addSlashes($this->searchtxt) . "%'";
        }

        if ($this->filterby != '0' && $this->filterby != '') {
            $filterarray = explode('-', $this->filterby);
            $whereclause .=" and $filterarray[0] = '$filterarray[1]'";
        }
        $sqlCountPages = "select count(1) as total from " . DB_PREFIX . "productphotogallery where chr_delete = 'N' $whereclause";
        $rs = $this->configObj->glDbObj->get_sql_row($sqlCountPages);
        $this->numofrows = $rs['total'];
        return $rs['total'];
    }

    function insert_photo() {
       
        $sess = time();
        
//        if ($this->varpostdata['h_save'] == 'T') {
//            $this->configObj->glLibraryObj->updatedisplay_order('productphotogallery', 1);
//            if ($_FILES['varphotoname']['name'] != '') {
//                //for removing space in name
//                $file_extension = $this->configObj->glLibraryObj->file_extension($_FILES['varphotoname']['name']);
//                $photo = basename($_FILES['varphotoname']['name']);
//                $photofile = str_replace(' ', '-', $photo);
//                $phototitle = explode('.', $photofile);
//                $var_title = $phototitle[0];
//
//                $_FILES['varphotoname']['name'] = $photofile;
//                $thumb_width = PHOTOGALLERY_THUMB_WIDTH;
//                $thumb_hight = PHOTOGALLERY_THUMB_HEIGHT;
//
//                $var_thumb = $this->upload_image('varphotoname', $thumb_width, $thumb_hight, 'thumb_', $sess, $thumb_width, $thumb_hight, 'thumb_');
//                $this->imagename = $var_thumb;
//                if ($var_thumb == 'false') {
//                    $this->chr_validimage = 'N';
//                } else {
//                    $this->chr_validimage = 'Y';
//                }
//            }
            
            $count=count($_FILES['var_image']['name']);
        for($i=0;$i < $count;$i++) {
        $this->configObj->glLibraryObj->updatedisplay_order('productphotogallery',1);
            $sess = time();
            $pdf = basename($_FILES['var_image']['name'][$i]);
            $photofile = str_replace(' ', '-', $pdf);
            $phototitle = explode('.', $photofile);
            $var_title = $phototitle[0];
            $_FILES['var_image']['name'][$i] = $photofile;
            $thumb_width = PHOTOGALLERY_THUMB_WIDTH;
            $thumb_hight = PHOTOGALLERY_THUMB_HEIGHT;
            $var_thumb = $this->upload_image('var_image', $thumb_width, $thumb_hight, 'thumb_', $sess, $thumb_width, $thumb_hight, 'thumb_',$i);
            $this->imagename = $var_thumb;
            
            
            $check_album_cover = "select count(1) as total from ".DB_PREFIX."productphotogallery where fk_product = '".$_REQUEST['fk_product']."' and chr_delete = 'N'";
            
            $rs1 = $this->configObj->glDbObj->get_sql_row($check_album_cover);

            if($rs1['total'] != '0')
            {
                $chr_cover = 'N';
            }
            else
            {
                $chr_cover = 'Y';
            }
           
             
            $this->configObj->glDbObj->resetfields();
            $this->configObj->glDbObj->setQueryType('insert');
            $this->configObj->glDbObj->setTable(DB_PREFIX . 'productphotogallery');

            $this->configObj->glDbObj->addColumn('fk_product');
            $this->configObj->glDbObj->addColumn('varphotocaption');
            $this->configObj->glDbObj->addColumn('var_image');
            $this->configObj->glDbObj->addColumn('chr_defaultimage');
            $this->configObj->glDbObj->addColumn('chr_delete');
            $this->configObj->glDbObj->addColumn('chr_publish');
            $this->configObj->glDbObj->addColumn('dt_createdate');
            $this->configObj->glDbObj->addColumn('dt_modifydate');
            $this->configObj->glDbObj->addColumn('int_displayorder');

            $this->configObj->glDbObj->addValue($this->varpostdata['fk_product']);
            $this->configObj->glDbObj->addValue($var_title);
            $this->configObj->glDbObj->addValue($this->imagename);
            $this->configObj->glDbObj->addValue($chr_cover);
            $this->configObj->glDbObj->addValue('N');
            $this->configObj->glDbObj->addValue('Y');
            $this->configObj->glDbObj->addValue('NOW()');
            $this->configObj->glDbObj->addValue('NOW()');
            $this->configObj->glDbObj->addValue('1');
//            echo 'hello';
//            echo $this->configObj->glDbObj->buildQuery(); exit;
            $this->configObj->glDbObj->query($this->configObj->glDbObj->buildQuery());

            $this->lastinsertid = mysql_insert_id();
            $this->configObj->glLibraryObj->insertinlogmanager(93, DB_PREFIX . 'productphotogallery', 'var_image', $this->lastinsertid, 'I');
             echo $this->imagename; 
        }
            return true;
    }

    function update_photos() {
        $sess = time();
        if ($this->varpostdata['int_displayorder'] != $this->varpostdata['old_displayorder']) {
            $tablename = DB_PREFIX . 'productphotogallery';
            $this->configObj->glDbObj->resetfields();
            $this->configObj->glDbObj->setQueryType('select');
            $this->configObj->glDbObj->setTable(DB_PREFIX . 'productphotogallery');
            $this->configObj->glDbObj->addColumn('count(1) as total');
            $this->configObj->glDbObj->setWhere("int_displayorder=" . $this->varpostdata['int_displayorder'] . " and chr_delete = 'N' ");
            $rs = $this->configObj->glDbObj->get_sql_row($this->configObj->glDbObj->buildQuery());

            if ($rs['total'] > 0) {
                if ($this->varpostdata['int_displayorder'] > $this->varpostdata['old_displayorder']) {
                    $this->configObj->glDbObj->resetfields();
                    $this->configObj->glDbObj->setTable($tablename);
                    $this->configObj->glDbObj->setQueryType('update');
                    $this->configObj->glDbObj->addColumn('int_displayorder');
                    $this->configObj->glDbObj->UnsetQuotes();
                    $this->configObj->glDbObj->addValue('int_displayorder - 1');
                    $this->configObj->glDbObj->SetQuotes();
                    $this->configObj->glDbObj->setWhere('int_displayorder > ' . $this->varpostdata['old_displayorder'] . ' and int_displayorder <= ' . $this->varpostdata['int_displayorder'] . ' ');
                    $this->configObj->glDbObj->query($this->configObj->glDbObj->buildQuery());
                } else {
                    $this->configObj->glDbObj->resetfields();
                    $this->configObj->glDbObj->setTable(DB_PREFIX . 'productphotogallery');
                    $this->configObj->glDbObj->setQueryType('update');
                    $this->configObj->glDbObj->addColumn('int_displayorder');
                    $this->configObj->glDbObj->UnsetQuotes();
                    $this->configObj->glDbObj->addValue('int_displayorder + 1');
                    $this->configObj->glDbObj->SetQuotes();
                    $this->configObj->glDbObj->setWhere('int_displayorder >= ' . $this->varpostdata['int_displayorder'] . ' and  int_displayorder < ' . $this->varpostdata['old_displayorder'] . ' ');
                    $this->configObj->glDbObj->query($this->configObj->glDbObj->buildQuery());
                }
            }
        }

        if ($_FILES['var_image']['name'] != '') {
            //for removing space in name
            $file_extension = $this->configObj->glLibraryObj->file_extension($_FILES['var_image']['name']);
            $pdf = basename($_FILES['var_image']['name']);
            $pdffile = str_replace(' ', '-', $pdf);

            $_FILES['var_image']['name'] = $pdffile;
            $this->imagename = $_FILES['var_image']['name'];
            $this->thumb_width = PHOTOGALLERY_THUMB_WIDTH;
            $this->thumb_height = PHOTOGALLERY_THUMB_HEIGHT;
            $var_thumb = $this->upload_image('var_image', $this->thumb_width, $this->thumb_height, 'thumb_', $sess, $this->thumb_width, $this->thumb_height, 'thumb_');
            $this->imagename = $var_thumb;
            $uploaddir = 'upimages/productphotogallery/images/thumb';
            $uploadfile = $uploaddir . $this->varpostdata['hidvar_photo'];
            $uploadthumb = $uploaddir . "thumb_" . $this->varpostdata['hidvar_photo'];
            if (file_exists($uploadfile)) {
                unlink($uploadfile);
            }

            if (file_exists($uploadthumb)) {
                unlink($uploadthumb);
            }
        } else {
            $this->imagename = $this->varpostdata['hidvar_photo'];
        }

        $this->configObj->glDbObj->resetfields();
        $this->configObj->glDbObj->setQueryType('update');
        $this->configObj->glDbObj->setTable(DB_PREFIX . 'productphotogallery');
        // Set the Columns
        $this->configObj->glDbObj->addColumn('var_title');
        $this->configObj->glDbObj->addColumn('fk_product');
        $this->configObj->glDbObj->addColumn('var_image');
        //$this->configObj->glDbObj->addColumn('chr_crop');
        $this->configObj->glDbObj->addColumn('chr_validthumb');
        $this->configObj->glDbObj->addColumn('int_displayorder');
        $this->configObj->glDbObj->addColumn('chr_defaultimage');
        $this->configObj->glDbObj->addColumn('dt_createdate');
        $this->configObj->glDbObj->addColumn('chr_publish');
        $this->configObj->glDbObj->addColumn('chr_home');
        $this->configObj->glDbObj->addColumn('chr_read');

        $this->configObj->glDbObj->addValue($this->varpostdata['var_title']);
        $this->configObj->glDbObj->addValue($this->varpostdata['fk_product']);
        $this->configObj->glDbObj->addValue($this->imagename);
        $this->configObj->glDbObj->addValue($this->chr_validthumb);
        $this->configObj->glDbObj->addValue($this->varpostdata['int_displayorder']);
        $this->configObj->glDbObj->addValue($default);
        $this->configObj->glDbObj->addValue('NOW()');
        $this->configObj->glDbObj->addValue($this->varpostdata['chr_home']);
        $this->configObj->glDbObj->addValue('Y');
        $this->configObj->glDbObj->addValue('1');
        $this->configObj->glDbObj->setWhere('int_glcode=' . $this->varpostdata['eid']);
        $this->configObj->glDbObj->query($this->configObj->glDbObj->buildQuery());
        $this->configObj->glDbObj->buildQuery();
        $this->lastinsertid = $this->varpostdata['eid'];

        $this->configObj->glLibraryObj->insertinlogmanager(93, DB_PREFIX . 'productphotogallery', 'var_image', $this->varpostdata['eid'], 'U');
        return true;
    }

    function get_var_imagepath($eid, $fieldname, $tablename) {
        $sql = "select " . $fieldname . " from " . $tablename . " where int_glcode=$eid AND chr_delete='N'";
        $rs = $this->configObj->glDbObj->get_sql_row($sql);
        $var_imagepath = $rs[$fieldname];
        return $var_imagepath;
    }

    function update_image_crop() {
        $this->configObj->glDbObj->resetfields();
        $this->configObj->glDbObj->setQueryType('update');
        $tablename = DB_PREFIX . 'productphotogallery';
        $this->configObj->glDbObj->setTable($tablename);
        $this->configObj->glDbObj->addColumn('chr_crop');
        $this->configObj->glDbObj->addColumn('dt_modifydate');
        $this->configObj->glDbObj->addvalue('Y');
        $this->configObj->glDbObj->addValue('NOW()');
        $this->configObj->glDbObj->setWhere('int_glcode=' . $_REQUEST['eid']);
        $this->configObj->glDbObj->query($this->configObj->glDbObj->buildQuery());
        return true;
    }

    function get_cropstatus($eid, $fieldname, $tablename) {
        $sql = "select " . $fieldname . " from " . $tablename . " where int_glcode=$eid AND chr_delete='N'";
        $rs = $this->configObj->glDbObj->get_sql_row($sql);
        $cropstatus = $rs[$fieldname];
        return $cropstatus;
    }

    function get_albumcmb($fk) {

        $sql = 'select int_glcode,var_title from ' . DB_PREFIX . 'product where chr_delete="N" and chr_publish="Y" order by int_displayorder asc';
        $rec = $this->configObj->glDbObj->query($sql);

        $html.='<select id="fk_albums" name="fk_albums" class="more-textarea" onchange="window.location.href=\'index.php?module=productphotogallery&fk_product=\'+this.value">';
        while ($row = $this->configObj->glDbObj->fetch_array($rec)) {
            if ($row['int_glcode'] == $fk) {
                $selected = 'selected="selected"';
            } else {
                $selected = '';
            }
            $html.='<option value="' . $row['int_glcode'] . '" ' . $selected . '>' . $row['var_title'] . '</option>';
        }
        $html.='</select>';
        return $html;
    }

    function select_photo($id) {

        $this->configObj->glDbObj->resetfields(); // Reset the object
        $this->configObj->glDbObj->setQueryType('select');    // Set the Table
        $this->configObj->glDbObj->setTable(DB_PREFIX . 'productphotogallery');
        $this->configObj->glDbObj->addColumn('*');
        $this->configObj->glDbObj->setWhere('int_glcode =' . $id);
        //echo $this->configObj->glDbObj->buildQuery();
        $row = $this->configObj->glDbObj->get_sql_row($this->configObj->glDbObj->buildQuery());
        return $row;
    }

    function make_default_image($id, $fk_tradeshows) {
        $sql = "update " . DB_PREFIX . "productphotogallery set chr_defaultimage='Y' where int_glcode='" . $id . "' and fk_tradeshows='" . $fk_tradeshows . "'";
        $this->configObj->glDbObj->query($sql);
        $sql = "update " . DB_PREFIX . "productphotogallery set chr_defaultimage='N' where int_glcode != '" . $id . "' and fk_tradeshows='" . $fk_tradeshows . "'";
        $this->configObj->glDbObj->query($sql);
        return true;
    }

    function upload_image($filefield, $thumb_width, $thumb_height, $prefix, $sess, $large_width, $large_height, $prefix2 = '',$i=1) {
        $file_photo = basename($_FILES[$filefield]['name'][$i]);
        $imagename = $sess . $file_photo;
        $uploaddir = '../upimages/productphotogallery/images/thumb/';
        $file_photo = $sess . basename($_FILES[$filefield]['name'][$i]);
        $file = $uploaddir . $file_photo;
        $tmp = $_FILES[$filefield]['tmp_name'][$i];
        $uploadedfile = $_FILES[$filefield]['tmp_name'][$i];

        // Create an Image from it so we can do the resize
        $image_info = getimagesize($uploadedfile);

        switch ($image_info['mime']) {
            case 'image/gif':
                $img_create = 'ImageCreateFromGIF';
                break;
            case 'image/jpeg':
                $img_create = 'ImageCreateFromJPEG';
                break;
            case 'image/png':
                $img_create = 'ImageCreateFromPNG';
                break;
            case 'image/bmp':
                $img_create = 'ImageCreateFromBMP';
                break;
        }

        // $src = imagecreatefromjpeg($uploadedfile);
        $src = @$img_create($uploadedfile);
        // Capture the original size of the uploaded image
        list($width, $height) = getimagesize($uploadedfile);
        $newwidth = $width;
        $newheight = $height;
        $tmp = imagecreatetruecolor($newwidth, $newheight);
        $background_color = imagecolorallocate($tmp, 255, 255, 255);
        imagefill($tmp, 0, 0, $background_color);
        // this line actually does the image resizing, copying from the original // image into the $tmp image
        imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

        // now write the resized image to disk.
        imagejpeg($tmp, $file, 90);
        imagedestroy($src);
        imagedestroy($tmp); // NOTE: PHP will clean up the temp file it created when the request  // has completed.
        $source1 = $uploaddir . $file_photo;

        //$sess = time();
        $thumbfilename = $prefix . $sess . $file_photo;
        $target1 = $uploaddir . $prefix . $file_photo;
        $target2 = $uploaddir . $prefix2 . $file_photo;

        if ($large_width > 0) {
            $returnthumbmsg1 = $this->configObj->glLibraryObj->generate_thumb($source1, $thumb_width, false, false, $target1, false, null, $thumb_width, $thumb_height);
        }
        if ($large_width > 0) {
            $returnthumbmsg2 = $this->configObj->glLibraryObj->generate_thumb($source1, $thumb_width, false, false, $target2, false, null, $large_width, $large_height);
        }
        if ($returnthumbmsg1 == 'INVALID' || $returnthumbmsg2 == 'INVALID') {
            $this->chr_validthumb = 'N';
            $this->chr_validthumbdetail = 'N';
        } else {
            $this->chr_validthumb = 'Y';
            $this->chr_validthumbdetail = 'Y';
        }
        return $imagename;
    }

    function getPhotosByAlbum($albumID) {

        $photoArry = array();
        $sql = "select int_glcode,varphotocaption,var_image,chr_defaultimage,chr_publish,var_primary,chr_home,chr_delete  
                FROM " . DB_PREFIX . "productphotogallery where chr_delete='N'  and fk_product=" . $albumID . "
                order by int_displayorder";
        $rs = $this->configObj->glDbObj->query($sql);
        while ($row = $this->configObj->glDbObj->fetch_assoc($rs)) {
            $photoArry[] = $row;
        }
//        echo "<pre>";
//        print_r($photoArry);
        return $photoArry;
    }

    function set_primary_photo($photoID, $albumID) {
        
        $sql_photogallery = "update " . DB_PREFIX . "productphotogallery set chr_defaultimage='N' where int_glcode NOT IN('" . $photoID . "') and fk_product='" . $albumID . "'";
        $this->configObj->glDbObj->query($sql_photogallery);
        $sql = "Update " . DB_PREFIX . "productphotogallery  set chr_defaultimage = 'Y' WHERE int_glcode ='" . $photoID . "' and fk_product='" . $albumID . "'";
        $rs = $this->configObj->glDbObj->query($sql);
        return $rs;
    }

    function set_publish($photoID, $publish) {
//        echo "in";exit;
        if ($publish == 'N') {
            $publish = 'Y';
        } else {
            $publish = 'N';
        }

        $this->configObj->glDbObj->resetfields();
        $this->configObj->glDbObj->setQueryType('update');
        $tablename = DB_PREFIX . 'productphotogallery';
        $this->configObj->glDbObj->setTable($tablename);
        $this->configObj->glDbObj->addColumn('chr_publish');
        $this->configObj->glDbObj->addColumn('dt_modifydate');

        $this->configObj->glDbObj->addvalue($publish);
        $this->configObj->glDbObj->addValue('NOW()');
        $this->configObj->glDbObj->setWhere('int_glcode =' . $photoID);
//        echo $this->configObj->glDbObj->buildQuery();exit;
        $this->configObj->glDbObj->query($this->configObj->glDbObj->buildQuery());

        return true;
    }

    function home($photoID, $home) {
        if ($home == 'N') {
            $home = 'Y';
        } else {
            $home = 'N';
        }
        $this->configObj->glDbObj->resetfields();
        $this->configObj->glDbObj->setQueryType('update');
        $tablename = DB_PREFIX . 'productphotogallery';
        $this->configObj->glDbObj->setTable($tablename);
        $this->configObj->glDbObj->addColumn('chr_home');
        $this->configObj->glDbObj->addvalue($home);
        $this->configObj->glDbObj->setWhere('int_glcode =' . $photoID);
        $this->configObj->glDbObj->query($this->configObj->glDbObj->buildQuery());
        return true;
    }

    function savePhotoCaption($photoID, $photocaption) {
        $this->configObj->glDbObj->resetfields();
        $this->configObj->glDbObj->setQueryType('update');
        $tablename = DB_PREFIX . 'productphotogallery';
        $this->configObj->glDbObj->setTable($tablename);
        $this->configObj->glDbObj->addColumn('varphotocaption');
        $this->configObj->glDbObj->addColumn('dt_modifydate');
        $this->configObj->glDbObj->addvalue($photocaption);
        $this->configObj->glDbObj->addValue('NOW()');
        $this->configObj->glDbObj->setWhere('int_glcode =' . $photoID);
        $this->configObj->glDbObj->query($this->configObj->glDbObj->buildQuery());
        return true;
    }

    function delete_image($photoID) {

        $sql = "SELECT var_image FROM " . DB_PREFIX . "productphotogallery WHERE int_glcode ='" . $photoID . "'";
        $rs = $this->configObj->glDbObj->query($sql);
        $row = $this->configObj->glDbObj->fetch_assoc($rs);
        if (!empty($row)) {
            $sql = "Update " . DB_PREFIX . "productphotogallery  set  var_ipaddress='" . $_SERVER['REMOTE_ADDR'] . "',var_adminuser='" . ADMIN_NAME . "',chr_delete='Y' WHERE int_glcode ='" . $photoID . "'";
            echo $sql;
            $rs = $this->configObj->glDbObj->query($sql);
        }
        $this->configObj->glLibraryObj->insertinlogmanager(93, DB_PREFIX . 'productphotogallery', 'var_image', $photoID, 'D');

        return $rs;
    }

    function set_photo_displayorder($albumID, $photointglcode) {

        if (!empty($photointglcode)) {

            $intglcodeArry = explode(",", $photointglcode);
            $i = 1;
            foreach ($intglcodeArry as $glcode) {

                $this->configObj->glDbObj->resetfields();
                $this->configObj->glDbObj->setQueryType('update');
                $tablename = DB_PREFIX . 'productphotogallery';
                $this->configObj->glDbObj->setTable($tablename);
                $this->configObj->glDbObj->addColumn('int_displayorder');
                $this->configObj->glDbObj->addColumn('dt_modifydate');


                $this->configObj->glDbObj->addvalue($i);
                $this->configObj->glDbObj->addValue('NOW()');
                $this->configObj->glDbObj->setWhere('int_glcode =' . $glcode . ' AND fk_product =' . $albumID);
                $this->configObj->glDbObj->query($this->configObj->glDbObj->buildQuery());
                
                $i++;
            }
            return true;
        }
    }
    
    function countphotodelete($id)
    {
        $query="select count(0) as total from " . DB_PREFIX . "productphotogallery where fk_product='$id' and chr_delete='N'" ;
        $rs = $this->configObj->glDbObj->get_sql_row($query);
        return $rs['total'];
    }

}
?>

