<?php
  /**
   * Products Class
   *
   * @package Digital Downloads Pro
   * @author wojoscripts.com
   * @copyright 2010
   * @version $Id: class_products.php, v2.00 2011-07-10 10:12:05 gewa Exp $
   */
  
  if (!defined("_VALID_PHP"))
      die('. دسترسی مستقیم به این محل مجاز نمی باشد');
  
  final class Product
  {
	  private $pTable = "products";
	  public $pid = null;
      

      /**
       * Product::__construct()
       * 
       * @return
       */
      public function __construct()
      {
		  $this->getPid();

      }
      
	  /**
	   * Product::getPid()
	   * 
	   * @return
	   */
	  private function getPid()
	  {
	  	  global $core, $DEBUG;
		  
		  if (isset($_GET['pid'])) {
			  $_GET['pid'] = sanitize($_GET['pid'],6,true);
			  $pid = (is_numeric($_GET['pid']) && $_GET['pid'] > -1) ? intval($_GET['pid']) : false;
		  
			  if ($pid) {
				  return $this->pid = $pid;
			  } else {
				  if($DEBUG)
				  	$core->error("..نامعتبـر انتخـاب نموده ایـد Id شمـا یک","Core::getPid()");
			  }
		  }
	  }
	  
	  /**
	   * Product::getProducts()
	   * 
	   * @param bool $sort
	   * @return
	   */
	  public function getProducts()
	  {
          global $db, $core, $pager;

		  require_once(BASEPATH . "lib/class_paginate.php");
          $pager = new Paginator();
		  
		  $pager = new Paginator();
		  $counter = countEntries($this->pTable);
		  $pager->items_total = $counter;
		  $pager->default_ipp = $core->perpage;
		  $pager->paginate();
		  
		  if ($counter == 0) {
			$pager->limit = "";
		  }

		  if (isset($_GET['sort'])) {
			  list($sort, $order) = explode("-", $_GET['sort']);
			  $sort = sanitize($sort);
			  $order = sanitize($order);
			  if (in_array($sort, array("title", "cid", "price", "created"))) {
				  $ord = ($order == 'DESC') ? " DESC" : " ASC";
				  $sorting = " p." . $sort . $ord;
			  } else {
				  $sorting = " p.created DESC";
			  }
		  } else {
			  $sorting = " p.created DESC";
		  }

		  $sql = "SELECT p.*, p.id as pid, c.name, c.id as cid," 
		  . "\n DATE_FORMAT(p.created, '" . $core->short_date . "') as cdate,"
		  . "\n (SELECT COUNT(pid) FROM transactions WHERE pid = p.id) as sales"
		  . "\n FROM " . $this->pTable . " as p"
		  . "\n LEFT JOIN categories as c ON c.id = p.cid" 
		  . "\n ORDER BY " . $sorting . $pager->limit;
          $row = $db->fetch_all($sql);
		  
           return ($row) ? $row : 0;

	  }

	  /**
	   * Product:::processProduct()
	   * 
	   * @return
	   */
	  public function processProduct()
	  {
		  global $db, $core;
		  
		  if (empty($_POST['title']))
			  $core->msgs['title'] = "!لطفـا عنوان محصـول را انتخـاب نمائیـد";

		  if (empty($_POST['price']))
			  $core->msgs['price'] = "!قیمـت محصـول مورد نیـاز اسـت";

		  if (empty($_POST['expiry']))
			  $core->msgs['expiry'] = "!انقضـاء محصـول مورد نیـاز اسـت";
			  
		  if (empty($_POST['file_id']))
			  $core->msgs['file_id'] = "!فایـل/پرونده محصـول مورد نیـاز اسـت";
			  			  
		  if (empty($_POST['body']))
			  $core->msgs['body'] = "!محتـوای محصـول مورد نیـار اسـت";

		  if (!empty($_FILES['audio']['name'])) {
			  if (!preg_match("/(\.mp3)$/i", $_FILES['audio']['name']))
				  $core->msgs['audio'] = ".مجـاز می باشـد .mp3 نوع فایـل غیر مجـاز می باشـد. فقـط فرمـت";
		  }
		  
		  if (!empty($_FILES['thumb']['name'])) {
			  if (!preg_match("/(\.jpg|\.png|\.gif)$/i", $_FILES['thumb']['name']))
				  $core->msgs['thumb'] = ".مجـاز می باشـد .jpg, .gif or .png نوع تصـویر غیر مجـاز می باشـد. فقـط فرمـت";
		  }
		    		  
		  if (empty($core->msgs)) {
			  $expiry = ($_POST['expiry_type'] == "days") ? "D" . $_POST['expiry'] : $_POST['expiry'];
			  $ytube = str_replace('http://youtu.be/','',$_POST['youtube']);
			  $data = array(
				  'title' => sanitize($_POST['title']), 
				  'cid' => intval($_POST['cid']),
				  'slug' => (empty($_POST['slug'])) ? paranoia($_POST['title']) : paranoia($_POST['slug']),
				  'price' => floatval($_POST['price']),
				  'description' => sanitize($_POST['description']),
				  'body' => $_POST['body'],
				  'file_id' => intval($_POST['file_id']),
				  'youtube' => sanitize($ytube),
				  'expiry' => sanitize($expiry),
				  'metakeys' => sanitize($_POST['metakeys']), 
				  'metadesc' => sanitize($_POST['metadesc']), 
				  'active' => intval($_POST['active'])
			  );
			  
			  if (!$this->pid) {
				  $data['created'] = "NOW()";
			  }

              // Procces Thumb
			  if (!empty($_FILES['thumb']['name'])) {

				  include(BASEPATH . "lib/class_imageUpload.php");
				  include(BASEPATH . "lib/class_imageResize.php");
		  
		          $imgdir = PRODIMGPATH;
				  $newName = "IMG_" . randName();
				  $ext = substr($_FILES['thumb']['name'], strrpos($_FILES['thumb']['name'], '.') + 1);
				  $name = $newName.".".strtolower($ext);
				  
				  $ddp = new Upload();
				  $ddp->File = $_FILES['thumb'];
				  $ddp->method = 1;
				  $ddp->SavePath = $imgdir;
				  $ddp->ThumbPath = $imgdir . "thumbs/";
				  $ddp->TWidth = $core->thumb_w;
				  $ddp->THeight = $core->thumb_h;
				  $ddp->NewWidth = $core->img_w;
				  $ddp->NewHeight = $core->img_h;
				  $ddp->NewName = $newName;
				  $ddp->OverWrite = true;
				  
				  if ($this->pid) {
					  $thumb = getValue("thumb",$this->pTable,"id = '".$this->pid."'");
					  if (!empty($_FILES['thumb']['name'])) {
						  if ($thumb) {
							  @unlink($ddp->SavePath . $thumb);
							  @unlink($ddp->ThumbPath . $thumb);
						  }
						  $data['thumb'] = $name;
					  } else {
						  $data['thumb'] = $thumb;
					  }
				  } else {
					  if (!empty($_FILES['thumb']['name'])) 
					  $data['thumb'] = $name;
				  }
				  
				  $err = $ddp->UploadFile();				  
				  if (count($err) > 0 and is_array($err)) {
					  foreach ($err as $key => $val) {
						  $msgError = $val;
						  $core->msgError($val,false);
					  }
				  }
			  }

              // Procces Audio
			  $audio = getValue("audio",$this->pTable,"id = '".$this->pid."'");
			  if (!empty($_FILES['audio']['name'])) {
				  $auddir = UPLOADS . "prod_audio/";
				  $aName = "AUD_" . randName();
				  $aext = substr($_FILES['audio']['name'], strrpos($_FILES['audio']['name'], '.') + 1);
				  $audioName = $auddir . $aName.".".strtolower($aext);	
				  if ($audio) {
					  @unlink($auddir . $audio);
				  }
					  move_uploaded_file($_FILES['audio']['tmp_name'], $audioName);

				  $data['audio'] = $aName.".".strtolower($aext);
			  } else {
				$data['audio'] = $audio;
			  }

			  ($this->pid) ? $db->update($this->pTable, $data, "id='" . (int)$this->pid . "'") : $lastid = $db->insert($this->pTable, $data);
			  $message = ($this->pid) ? '<span>!موفقیـت</span>!محصـول با موفقیـت بروز رسـانی شـد' : '<span>!موفقیـت</span>!محصـول با موفقیـت اضـافـه شـد';
			  ($db->affected()) ? $core->msgOk($message) :  $core->msgAlert('<span>!تـوجـه</span>.چیزی برای پـردازش وجـود ندارد');	
			  		  
			  if ($this->pid) {
                  $db->delete("tags", "pid='" . $this->pid . "'");
                  if (!empty($_POST['tags'])) {
                      $tags = explode(",", $_POST['tags']);
					  sort($tags);
                      foreach ($tags as $tag) {
                          $tdata['tag'] = sanitize($tag);
                          $tdata['pid'] = $this->pid;
                          $db->insert("tags", $tdata);
                      }
                  }  
			  }	else {	  
				if (!empty($_POST['tags'])) {
					$tags = explode(",", $_POST['tags']);
					sort($tags);
					foreach ($tags as $tag) {
						$tdata['tag'] = sanitize($tag);
						$tdata['pid'] = $lastid;
						$db->insert("tags", $tdata);
					}
				}
			  }
			  
			  
		  } else
			  print $core->msgStatus();
	  }

	  /**
	   * Product::renderItem()
	   * 
	   * @return
	   */
	  public function renderItem()
	  {
          global $db, $core;
		  
		  $sql = "SELECT p.*, p.id as pid, c.name, c.id as cid,c.slug as cslug," 
		  . "\n DATE_FORMAT(p.created, '" . $core->short_date . "') as cdate,"
		  . "\n (SELECT COUNT(pid) FROM transactions WHERE pid = p.id) as purchased"
		  . "\n FROM " . $this->pTable . " as p"
		  . "\n LEFT JOIN categories as c ON c.id = p.cid"
		  . "\n WHERE p.id = '".$this->pid."'"
		  . "\n AND p.active = '1'";
          $row = $db->first($sql);
		  
          if ($row) {
			  $this->updateHits();
			  $this->updateRecentViews();
              return $row;
          } else
              return 0;

	  }

	  /**
	   * Product::getProductList()
	   * 
	   * @return
	   */
	  public function getProductList()
	  {
		  global $db;
		  		  
		  $sql = "SELECT id, title FROM " . $this->pTable
		  . "\n WHERE active = '1' ORDER BY title";
          $row = $db->fetch_all($sql);
          
		  return ($row) ? $row : 0;
	  }	
	  
	  /**
	   * Product::updateHits()
	   * 
	   * @return
	   */
	  private function updateHits()
	  {
          global $db;
		  
		  $data['hits'] = "INC(1)";
          $db->update($this->pTable, $data, "id = '".$this->pid."'");

	  }

	  /**
	   * Product::updateRecentViews()
	   * 
	   * @return
	   */
	  private function updateRecentViews()
	  {
          global $db, $user;

		  if (!$db->first("SELECT pid FROM recent WHERE user_id = '" . $db->escape($user->sesid) . "' AND pid = '" . $db->escape($this->pid) . "'")) {
			  $data['pid'] = $this->pid;
			  $data['user_id'] = $user->sesid;
			  $db->insert("recent", $data);
		  }
	  }
	  
	  /**
	   * Product::renderRecentViews()
	   * 
	   * @return
	   */
	  public function renderRecentViews()
	  {
          global $db, $user;

		  $sql = "SELECT r.*, p.id as pid, p.title, p.slug" 
		  . "\n FROM recent as r"
		  . "\n LEFT JOIN " . $this->pTable . " as p ON p.id = r.pid"
		  . "\n WHERE r.user_id = '" . $db->escape($user->sesid) . "'"
		  . "\n GROUP BY r.pid ORDER BY p.title LIMIT 10";
		  
          $row = $db->fetch_all($sql);
          
		  return ($row) ? $row : 0;

	  }
	  
	  /**
	   * Product::getVoting()
	   *
	   * @param mixed $vote_up
	   * @param mixed $vote_down
	   * @return
	   */
	  public function getVoting($vote_up, $vote_down)
	  {
		  
            print "<span class=\"thumbsUp\">" 
            . " <span class=\"vote_buttons\" id=\"vote_buttons" . $this->pid . "\">" 
            . " <a href=\"javascript:void(0);\" onclick=\"updateVoteUp(" . $this->pid . ");\" class=\"vote_up\" id=\"vote_up-" . $this->pid . "\">".$vote_up."</a>" 
            . " <a href=\"javascript:void(0);\" onclick= \"updateVoteDown(" . $this->pid . ");\" class=\"vote_down\" id=\"vote_down-" . $this->pid . "\">".$vote_down."</a></span>" 
            . " <span class=\"votes_count\" id=\"votes_count" . $this->pid . "\"></span>" 
            . " </span>";
	  }

	  /**
	   * Product::getRating()
	   *
	   * @param mixed $rating
	   * @return
	   */
	  public function getRating($rating)
	  {
		  
          $data = "<span class=\"rating-star\">"
              . " <span id=\"rating_".$this->pid."\">";
               $data .= "<span class=\"star_1\"><img src=\"".SITEURL."/images/star_blank.png\" onclick=\"updateRating(" . $this->pid . ",1);\" 
			   alt=\"\""; if($rating > 0)   $data .= "class=\"votehover\""; $data .= "/></span>";
               $data .= "<span class=\"star_2\"><img src=\"".SITEURL."/images/star_blank.png\" onclick=\"updateRating(" . $this->pid . ",2);\"
			   alt=\"\""; if($rating > 1.5) $data .= "class=\"votehover\""; $data .= "/></span>";
               $data .= "<span class=\"star_3\"><img src=\"".SITEURL."/images/star_blank.png\" onclick=\"updateRating(" . $this->pid . ",3);\"
			   alt=\"\""; if($rating > 2.5) $data .= "class=\"votehover\""; $data .= "/></span>";
               $data .= "<span class=\"star_4\"><img src=\"".SITEURL."/images/star_blank.png\" onclick=\"updateRating(" . $this->pid . ",4);\"
			   alt=\"\""; if($rating > 3.5) $data .= "class=\"votehover\""; $data .= "/></span>";
               $data .= "<span class=\"star_5\"><img src=\"".SITEURL."/images/star_blank.png\" onclick=\"updateRating(" . $this->pid . ",5);\"
			   alt=\"\""; if($rating > 4.5) $data .= "class=\"votehover\""; $data .= "/></span>";
              $data .= "</span>"
          . " </span>"
          . " <span class=\"star_rating\">"
          . " ( دریافـت <strong>".$rating."</strong> ستـاره )"
          . " </span>";
		  
		  print $data;

	  }
	  	  	  	  
	  /**
	   * Product::getTags()
	   * 
	   * @return
	   */
	  function getTags()
	  {
		  global $db;
		  
		  if ($result = $db->fetch_all("SELECT tag FROM tags WHERE pid = '".$this->pid."'")) {
			  $tags = array();
			  foreach ($result as $row) {
				  $tags[] = $db->escape(sanitize($row['tag']));
			  }
			  unset($row);
			  $tags = implode(",", $tags);
		  } else {
			  $tags = "";
		  }
		  return $tags;
	  }

	  /**
	   * Product::renderTags()
	   * 
	   * @return
	   */
	  public function renderTags()
	  {
		  global $db, $core;
		  
		  $sql = "SELECT * FROM tags WHERE pid = '" .$this->pid . "' ORDER BY tag";
		  $result = $db->fetch_all($sql);
		  
		  if($result) {
			$taglist = '';
			$taglist .= "<div id=\"tags\"><ul>\n";			  
			foreach ($result as $row) {
			  $url = ($core->seo) ? SITEURL . '/tags-' . sanitize($row['tag']) . '.html' : SITEURL . '/tags.php?tag=' . sanitize($row['tag']);
			  $taglist .= "<li><a href=\"" . $url . "\" title=\"" . $row['tag'] . "\" class=\"tooltip\">" . $row['tag'] . "</a></li>\n";
			}
			unset($result);
			$taglist .= "</ul></div>\n";
			
			return $taglist;
		  }
	  }

	  /**
	   * Product::getGalleryImages()
	   * 
	   * @return
	   */
	  public function getGalleryImages()
	  {
		  global $db;
		  		  
		  $sql = "SELECT * FROM photos"
		  . "\n WHERE pid = '".$this->pid."'";
          $row = $db->fetch_all($sql);
          
		  return ($row) ? $row : 0;
	  }	
	  	    
	  /**
	   * Product::getLatestProducts()
	   * 
	   * @return
	   */
	  public function getLatestProducts()
	  {
          global $db, $core;

		  $sql = "SELECT p.*, p.id as pid, c.name, c.id as cid," 
		  . "\n DATE_FORMAT(p.created, '" . $core->short_date . "') as cdate"
		  . "\n FROM " . $this->pTable . " as p"
		  . "\n LEFT JOIN categories as c ON c.id = p.cid" 
		  . "\n ORDER BY p.created DESC LIMIT 0,".$core->featured;
          $row = $db->fetch_all($sql);
		  
           return ($row) ? $row : 0;

	  }
	  	  	  
	  /**
	   * Product::getProductFilter()
	   * 
	   * @return
	   */
      public function getProductFilter()
	  {
		  $arr = array(
				 'title-ASC' => 'Product Title &uarr;',
				 'title-DESC' => 'Product Title &darr;',
				 'cid-ASC' => 'Product Category &uarr;',
				 'cid-DESC' => 'Product Category &darr;',
				 'price-ASC' => 'Product Price &uarr;',
				 'price-DESC' => 'Product Price &darr;',
				 'created-ASC' => 'Product Created &uarr;',
				 'created-DESC' => 'Product Created &darr;',
		  );
		  
		  $filter = '';
		  foreach ($arr as $key => $val) {
				  if ($key == get('sort')) {
					  $filter .= "<option selected=\"selected\" value=\"$key\">$val</option>\n";
				  } else
					  $filter .= "<option value=\"$key\">$val</option>\n";
		  }
		  unset($val);
		  return $filter;
	  } 
	  
	  
      /**
       * Product::getPayments()
       * 
       * @param bool $where
       * @param bool $from
       * @return
       */
      public function getPayments($where = false, $from = false)
      {
		  global $db, $core, $pg;
		  
		  require_once(BASEPATH . "lib/class_paginate.php");

          $pg = new Paginator();
          $counter = countEntries("transactions");
          $pg->items_total = $counter;
          $pg->default_ipp = $core->perpage;
          $pg->paginate();
          
          if ($counter == 0) {
              $pg->limit = null;
          }
		  
          $clause = ($where) ? " WHERE t.price LIKE '%" . intval($where) . "%'" : "";

		  if (isset($_GET['sort'])) {
			  list($sort, $order) = explode("-", $_GET['sort']);
			  $sort = sanitize($sort);
			  $order = sanitize($order);
			  if (in_array($sort, array("uid", "price", "pp", "created"))) {
				  $ord = ($order == 'DESC') ? " DESC" : " ASC";
				  $sorting = " t." . $sort . $ord;
			  } else {
				  $sorting = " t.created DESC";
			  }
		  } else {
			  $sorting = " t.created DESC";
		  }
		  
          if (isset($_POST['fromdate']) && $_POST['fromdate'] <> "" || isset($from) && $from != '') {
              $enddate = date("Y-m-d");
              $fromdate = (empty($from)) ? $_POST['fromdate'] : $from;
              if (isset($_POST['enddate']) && $_POST['enddate'] <> "") {
                  $enddate = $_POST['enddate'];
              }
              $clause .= " WHERE t.created BETWEEN '" . trim($fromdate) . "' AND '" . trim($enddate) . " 23:59:59'";
          } 
		  
          $sql = "SELECT t.*, t.id as id, u.id as uid, u.username, p.id as pid, p.title,"
		  . "\n DATE_FORMAT(t.created, '".$core->long_date."') as cdate"
		  . "\n FROM transactions as t"
		  . "\n LEFT JOIN users as u ON u.id = t.uid" 
		  . "\n LEFT JOIN products as p ON p.id = t.pid" 
		  . "\n " . $clause . " ORDER BY " . $sorting . $pg->limit;
		   
          $row = $db->fetch_all($sql);
          
		  return ($row) ? $row : 0;
      }
	  
      /**
       * Product::getPaymentFilter()
       * 
       * @return
       */
      public function getPaymentFilter()
	  {
		  $arr = array(
				 'uid-ASC' => 'Username &uarr;',
				 'uid-DESC' => 'Username &darr;',
				 'rate_amount-ASC' => 'Amount &uarr;',
				 'rate_amount-DESC' => 'Amount &darr;',
				 'pp-ASC' => 'Processor &uarr;',
				 'pp-DESC' => 'Processor &darr;',
				 'date-ASC' => 'Payment Date &uarr;',
				 'date-DESC' => 'Payment Date &darr;',
		  );
		  
		  $filter = '';
		  foreach ($arr as $key => $val) {
				  if ($key == get('sort')) {
					  $filter .= "<option selected=\"selected\" value=\"$key\">$val</option>\n";
				  } else
					  $filter .= "<option value=\"$key\">$val</option>\n";
		  }
		  unset($val);
		  return $filter;
	  }

	  /**
	   * Product::processTransaction()
	   * 
	   * @return
	   */
	  public function processTransaction()
	  {
		  global $db, $core, $user;
		  
		  if(!$core->id) {
			  if (!isset($_POST['pid']) or empty($_POST['pid']))
				  $core->msgs['pid'] = "..لطفـا محصـول را از لیسـت انتخـاب نمائیـد";
			  
			  if (!isset($_POST['uid']) or empty($_POST['uid']))
				  $core->msgs['uid'] = "..لطفـا نام کاربری را انتخـاب نمائیـد";
	
			  if (empty($_POST['created']))
				  $core->msgs['created'] = "!تاریـخ معاملـه مورد نیـاز اسـت";
		  }
		  if (empty($core->msgs)) {
			  if(!$core->id) {
					$row = $core->getRowById($this->pTable, (int)$_POST['pid']);
					$email = getValue("email", "users", "id='" . (int)$_POST['uid'] . "'");
					$data = array(
						  'txn_id' => "MAN_" . time(), 
						  'pid' => intval($row['id']), 
						  'uid' => intval($_POST['uid']), 
						  'file_date' => time(), 
						  'created' => sanitize($_POST['created']) . " " . date('H:i:s'), 
						  'payer_email' => sanitize($email),
						  'payer_status' => "verified", 
						  'item_qty' => intval($_POST['item_qty']),
						  'price' => floatval($row['price']),
						  'currency' => $core->currency,
						  'pp' => sanitize($_POST['pp']), 
						  'memo' => sanitize($_POST['memo']), 
						  'status' => 1, 
						  'active' => 1
					);
			  }
			  if($core->id) {
				  $edata = array(
						'status' => intval($_POST['status']), 
						'active' => intval($_POST['active']), 
						'downloads' => intval($_POST['downloads'])
				  );
			  }
			  ($core->id) ? $db->update("تراکنـش هـا", $edata, "id='" . (int)$core->id . "'") : $db->insert("transactions", $data);
			  $message = ($core->id) ? '<span>!موفقیـت</span>!رکورد تراکنـش با موفقیـت بروز رسـانی شـد' : '<span>!موفقیـت</span>!رکورد تراکنـش با موفقیـت اضـافـه شـد';
			  ($db->affected()) ? $core->msgOk($message) :  $core->msgAlert('<span>!تـوجـه</span>.چیزی برای پـردازش وجـود ندارد');
			  
			  if (isset($_POST['notify']) && intval($_POST['notify']) == 1) {
				  
				  $username = getValue("username", "users", "id='" . $data['uid'] . "'");
				  require_once(BASEPATH . "lib/class_mailer.php");
				  $mailer = $mail->sendMail();	
							  
				  $row2 = $core->getRowById("email_templates", 9);
				  
				  $body = str_replace(array('[USERNAME]', '[ITEMNAME]', '[PRICE]', '[QTY]', '[SITE_NAME]', '[URL]'), 
				  array($username, $row['title'], $row['price'], $data['item_qty'], $core->site_name, $core->site_url), $row2['body']);
		
				  $message = Swift_Message::newInstance()
							->setSubject($row2['subject'])
							->setTo(array($email => $username))
							->setFrom(array($core->site_email => $core->site_name))
							->setBody(cleanOut($body), 'text/html');
							
				   $mailer->send($message);
			  }
		  } else
			  print $core->msgStatus();
	  }

	  /**
	   * Product::getTransactionRecord()
	   * 
	   * @return
	   */
	  public function getTransactionRecord()
	  {
          global $db, $core;

		  $sql = "SELECT t.*, p.id as pid, p.title, u.id as uid, u.username," 
		  . "\n DATE_FORMAT(t.created, '" . $core->long_date . "') as cdate"
		  . "\n FROM transactions as t"
		  . "\n LEFT JOIN " . $this->pTable . " as p ON p.id = t.pid" 
		  . "\n LEFT JOIN users as u ON u.id = t.uid" 
		  . "\n WHERE t.id = '".$core->id."'";
          $row = $db->first($sql);
		  
           return ($row) ? $row : 0;

	  }
	  	  
	  /**
	   * Product::getGallery()
	   * 
	   * @return
	   */
	  public function getGallery()
	  {
		  global $db;
		  
		  $sql = "SELECT * FROM photos WHERE pid = '" . $this->pid . "'";
          $row = $db->fetch_all($sql);
          
		   return ($row) ? $row : 0;
	  }

	  /**
	   * Product::loadGallery()
	   * 
	   * @return
	   */
	  public function loadGallery()
	  {
		  if($galrow = $this->getGallery()) {
			  foreach ($galrow as $row) {
				  print '<div class="thumbview-gal thumbview">
						<div class="inner">
						<span class="control">
						  <a href="javascript:void(0);" rel="' . $row['thumb'] . '" class="delete" id="item_'. $row['id'].'"> <img src="images/delete2.png" alt="" title="حـذف" class="tooltip img-wrap2"/></a>
						  <a href="javascript:void(0);" rel="' . $row['thumb'] . '" class="edit" id="list_'. $row['id'].'"> <img src="images/edit.png" alt="" title="ویـرایـش" class="tooltip img-wrap2"/></a></span>
						<img src="' . PRODGALURL . 'thumbs/' . $row['thumb'] . '" alt="" title="' . $row['caption'] . '" class="tooltip"/>
						<div class="title">' . sanitize($row['caption'], 35) . '</div>
						</div>
					</div>';
			  }
		  }
	  }

      /**
       * Product::renameGalleryImage()
       * 
	   * @return
       */
	  public function renameGalleryImage()
	  {
		  global $db, $core;
		  
		  if (empty($_POST['caption']))
			  $core->msgs['caption'] = "!عنوان تصـویر مورد نیاز می باشـد";
		  
		  if (empty($core->msgs)) {
				  $data['caption'] = sanitize($_POST['caption']);
				  $db->update("photos", $data, "id = '" . $core->id . "'");

			  ($db->affected()) ? $core->msgOk('<span>!موفقیـت</span>.تغییر عنوان تصـویر با موفقیـت انجـام شـد') :  $core->msgAlert('<span>!تـوجـه</span>.چیزی برای پـردازش وجـود ندارد');
		  } else
			  print $core->msgStatus();
	  }
	  	  
	  /**
	   * Product::processGalleryImage()
	   * 
	   * @return
	   */
	  public function processGalleryImage()
	  {
		  global $db, $core;
		  
		  if (!is_dir(PRODGALPATH))
			  die($core->msgError('!خـطا: مسیـر آپـلــود وجود ندارد'));
		  
		  if (!is_writeable(PRODGALPATH))
			  die($core->msgError('!خـطا: مسیـر آپـلــود قابل نوشتـن نمی باشـد '));

		  if (empty($_POST['caption']))
			  $core->msgs['caption'] = "!عنوان تصـویر را وارد نمائیـد";
			  
		  if (empty($_FILES['thumb']['name']))
			  $core->msgs['thumb'] = "!لطفـا فایـل را برای آپـلــود انتخـاب نمائیـد";
			  
		  if (!empty($_FILES['thumb']['name'])) { 	  
			  if (!preg_match("/(\.jpg|\.png|\.gif|\.bmp|\.jpeg)$/i", $_FILES['thumb']['name']))
				  $core->msgs['thumb'] = '.مجـاز می باشـد jpg,png - gif نوع فایـل غیر مجـاز می باشـد. فقـط';
		  }

		  if (empty($core->msgs)) {
			  
			  include(BASEPATH . "lib/class_imageUpload.php");
			  include(BASEPATH . "lib/class_imageResize.php");
	
			  $imgdir = PRODIMGPATH;
			  $newName = "IMG_" . randName();
			  $ext2 = substr($_FILES['thumb']['name'], strrpos($_FILES['thumb']['name'], '.') + 1);
			  $name = $newName.".".strtolower($ext2);

			  $ddp = new Upload();
			  $ddp->File = $_FILES['thumb'];
			  $ddp->method = 1;
			  $ddp->SavePath = PRODGALPATH;
			  $ddp->ThumbPath = PRODGALPATH . "thumbs/";
			  $ddp->TWidth = $core->thumb_w;
			  $ddp->THeight = $core->thumb_h;
			  $ddp->NewWidth = $core->img_w;
			  $ddp->NewHeight = $core->img_h;
			  $ddp->NewName = $newName;
			  $ddp->OverWrite = true;
			  
			  $err = $ddp->UploadFile();				  
			  if (count($err) > 0 and is_array($err)) {
				  foreach ($err as $key => $val) {
					  $core->msgError('<span>Error!</span>'.$val,false);
				  }
			  }
				  
			  $data = array(
				  'pid' => $this->pid,
				  'caption' => sanitize($_POST['caption']), 
				  'thumb' => sanitize($name),
				  'active' => 1
			  );
			  $db->insert("photos", $data);
			  ($db->affected()) ? $core->msgOk('فایـل با موفقیـت آپـلــود شـد') :  $core->msgError('آپـلــود فایـل ناموفق بـود');
		  } else
			  print $core->msgStatus();
	  }

      /**
       * Product::getUserTransactions()
       * 
       * @return
       */
      public function getUserTransactions()
      {
          global $db, $core, $user;

          $sql = "SELECT t.*, p.id as pid, p.title, p.slug, p.thumb,"
		  . "\n DATE_FORMAT(t.created, '" . $core->long_date . "') as cdate"
		  . "\n FROM transactions as t"
		  . "\n LEFT JOIN " . $this->pTable . " as p ON p.id = t.pid" 
		  . "\n WHERE t.uid = '" . $user->uid . "' AND t.status = '1'"
		  . "\n GROUP BY t.pid ORDER BY t.created DESC";

          $row = $db->fetch_all($sql);
          
          return ($row) ? $row : 0;
      }

      /**
       * Product::getFileToDownload()
       * 
       * @return
       */
      public function getFileToDownload()
      {
          global $db, $core, $user;
		  
          $sql = "SELECT t.*, SUM(t.item_qty) as count, t.created, t.status, t.ip, t.active as tactive, 
		  SUM(t.downloads) as file_downloads, FROM_UNIXTIME(t.file_date,'%M %e %Y, %H:%i') as registered, t.id as tid, MAX(t.file_date) as file_date," 
				 . " \n p.id as pid, p.title, p.description, p.expiry, p.active as pactive, p.price, p.slug, p.metakeys, p.metadesc," 
				 . " \n f.id AS fid, f.alias, f.filesize,"
				 . " \n u.id AS uid"
				 . " \n FROM transactions as t" 
				 . " \n LEFT JOIN " . $this->pTable . " as p ON t.pid = p.id" 
				 . " \n LEFT JOIN files as f ON p.file_id = f.id" 
				 . " \n LEFT JOIN users AS u ON t.uid = u.id"
				 . " \n WHERE t.pid = '" . $this->pid . "' AND t.uid = '" . $user->uid . "' AND t.status = '1'"
				 . " \n GROUP BY p.id";
          
		  $row = $db->first($sql);
          return ($row) ? $row : 0;
      }
	  	  
      /**
       * Product::mostPopProducts()
       * 
       * @return
       */
      public function mostPopProducts()
      {
          global $db, $core;
		  
          $sql = "SELECT p.id as pid, p.title, p.slug, p.thumb"
		  . "\n FROM transactions as t"
		  . "\n LEFT JOIN " . $this->pTable . " as p ON p.id = t.pid" 
		  . "\n GROUP BY t.pid LIMIT 0," . $core->popular;
          
          $row = $db->fetch_all($sql);
          
          return ($row) ? $row : 0;
      }
	  
      /**
       * Product::mostPopular()
       * 
       * @return
       */
      public function mostPopular()
      {
          global $db, $core;
		  
          $sql = "SELECT title, hits FROM " . $this->pTable . " ORDER BY hits DESC LIMIT 0,5";
          $row = $db->fetch_all($sql);
          
          return ($row) ? $row : 0;
      }

      /**
       * Product::mostSold()
       * 
       * @return
       */
      public function mostSold()
      {
          global $db;
		  
          $sql = "SELECT p.title,p.id as pid, p.slug,"
		  . "\n COUNT(t.pid) as total" 
		  . "\n FROM transactions as t"
		  . "\n LEFT JOIN " . $this->pTable . " as p ON p.id = t.pid" 
		  . "\n WHERE t.status = '1'"
		  . "\n GROUP BY t.pid LIMIT 0,5";
          
          $row = $db->fetch_all($sql);
          
          return ($row) ? $row : 0;
      }	  	  	  	  
      /**
       * Product::yearlyStats()
       * 
       * @return
       */
      public function yearlyStats()
      {
          global $db, $core;
		  
          $sql = "SELECT *, YEAR(created) as year, MONTH(created) as month," 
		  . "\n COUNT(id) as total, SUM(price) as totalprice" 
		  . "\n FROM transactions" 
		  . "\n WHERE status = '1'" 
		  . "\n AND YEAR(created) = '" . $core->year . "'" 
		  . "\n GROUP BY year DESC, month DESC ORDER by created";
          
          $row = $db->fetch_all($sql);
          
          return ($row) ? $row : 0;
      }

      /**
       * Product::getYearlySummary()
       * 
       * @return
       */
      public function getYearlySummary()
      {
          global $db, $core;
          
          $sql = "SELECT YEAR(created) as year, MONTH(created) as month," 
		  . "\n COUNT(id) as total, SUM(price) as totalprice" 
		  . "\n FROM transactions"
		  . "\n WHERE status = '1'" 
		  . "\n AND YEAR(created) = '" . $core->year . "'";
          
          $row = $db->first($sql);
          
          return ($row) ? $row : 0;
      }
  }
?>