<?php

/**
 * @name          : Joomla Social Pinboard
 ** @version	  : 2.0
 * @package       : apptha
 * @since         : Joomla 1.5
 * @author        : Apptha - http://www.apptha.com
 * @copyright     : Copyright (C) 2011 Powered by Apptha
 * @license       : http://www.gnu.org/licenses/gpl-3.0.html GNU/GPL
 * @abstract      : Social Pinboard Component pinedit model
 * @Creation Date : March 2013
 * @Modified Date : March 2013
 * */
// No direct Access
defined('_JEXEC') or die('Restricted access');
jimport('joomla.application.component.model');

class wishlogueModelwishedit extends WishlogueModel {

	///rgs.
	function categoryNames() {
		$db = JFactory::getDBO();
		$query = "SELECT category_name, category_id FROM #__pin_categories WHERE status = 1 AND published != -2 ORDER BY category_name";
		$db->setQuery($query);
		$categoryNames = $db->loadObjectList();
		return $categoryNames;
	}

	function currencyList() {
		$db = JFactory::getDBO();
		$query = "SELECT * FROM #__pin_currency ORDER BY currency_id";
		$db->setQuery($query);
		$currencyList = $db->loadObjectList();
		return $currencyList;
    }

	function subcatalogueList() {
		$db = JFactory::getDBO();
		$user = JFactory::getUser();
		$memberId = $user->get('id');
		$pinid = JRequest::getVar('pinId');

		$query = " SELECT `pin_category_id` FROM `#__pin_pins` WHERE `pin_id` = $pinid ";
		$db->setQuery($query);
		$catId = $db->loadResult();

		$query = "SELECT `admin_subcatalogue` FROM `#__pin_boards` 
					WHERE `board_category_id` = $catId AND 
					`status` = 1 AND published != -2 AND user_id = $memberId AND admin_subcatalogue > 0";
		$db->setQuery($query);
		$exceptionalSubcatalogues = $db->loadColumn();

		if( count($exceptionalSubcatalogues) <= 0 ){
			$exceptionalSubcatalogues = array(-5);
		}
		$excSubcatalogues = implode(',', $exceptionalSubcatalogues);

		$query = "SELECT CONCAT('1*', `subcatalogue_id`) AS subcatalogue_id, `subcatalogue_name` 
					FROM `#__pin_subcatalogues` WHERE 
					`subcatalogue_id` NOT IN ( $excSubcatalogues ) AND 
					`catalogue_id` = $catId AND `status` = 1";
		$db->setQuery($query);
		$subcatalogueNames = $db->loadObjectList();

		$query = "SELECT CONCAT('2*', `board_id`) AS subcatalogue_id, `board_name` AS subcatalogue_name 
				FROM `#__pin_boards` WHERE `board_category_id` = $catId AND 
				`status` = 1 AND published != -2 AND user_id = $memberId ";
		$db->setQuery($query);
		$boardNames = $db->loadObjectList();

		return array_merge($subcatalogueNames, $boardNames);
	}

	///rgs..

    function editPins() {
        $db = $this->getDBO();
        $user = JFactory::getUser();
        $pinid = JRequest::getVar('pinId');
        $userId = $user->get('id');

        $query = "SELECT `price`, `wish_item`, `wish_retailer`, `wish_product_url`, `wish_currency`, `wish_quantity`, `wish_size`, `wish_style`, `wish_color`, `pin_id`, `pin_board_id`, `pin_user_id`, `pin_category_id`, `pin_description`, `pin_type_id`, `pin_url`, `pin_image`, `pin_repin_id`, `pin_real_pin_id`, `pin_repin_count`, `pin_likes_count`, `pin_comments_count`, `pin_views`, `link_type`, `status`, `published`, `gift`, `price`, `created_date`, `wish_status`, `wish_status_user` 
                  FROM #__pin_pins
                  WHERE status=1
                  AND pin_id=" . $pinid . "
                  AND `pin_user_id`=$userId";
        $db->setQuery($query);
        $pinEdit = $db->loadObjectList();
        return $pinEdit;
    }

    function editPinboards() {
        $db = $this->getDBO();
        $user = JFactory::getUser();
        $userId = $user->get('id');
        $query = "select board_name,board_id,cuser_id from #__pin_boards where (user_id=" . $userId . " OR cuser_id =" . $userId . " OR FIND_IN_SET( " . $userId . ", cuser_id ) >0) and status=1";
        $db->setQuery($query);
        $editPinboards = $db->loadObjectList();
        return $editPinboards;
    }

    function updatePins() {
        $db = $this->getDBO();
        $user = JFactory::getUser();
        $userId = $user->get('id');
        $btnEditpin = JRequest::getVar('SavePin');
        $editpindesc = addslashes(JRequest::getVar('description_pin_edit'));
        $editpinlink = JRequest::getVar('pinlink');
        if ($editpinlink != '') {
            if (preg_match("#https?://#", $editpinlink) === 0) {
                $editpinlink = 'http://' . $editpinlink;
            }
        }
		$update='';
        // check video url is youtube
		if(strpos($editpinlink,'youtube') > 0)
		{
			$imgstr = explode("v=", $editpinlink);
			$imgval = explode("&", $imgstr[1]);
			$img = "http://img.youtube.com/vi/" . $imgval[0] . "/1.jpg";
                        $update='`pin_image`="' . $img . '",`link_type`="youtube",';
		}
		else if(strpos($editpinlink,'youtu.be') > 0)
		{
			$imgstr = explode("/", $editpinlink);
			$img = "http://img.youtube.com/vi/" . $imgstr[3] . "/1.jpg";
                        $editpinlink="http://www.youtube.com/watch?v=".$imgstr[3];
                        $update='`pin_image`="' . $img . '",`link_type`="youtube",';
		}

		// check video url is youtube
		else if(strpos($editpinlink,'vimeo') > 0)
		{
		 $split=explode("/",$editpinlink);
                 if( ini_get('allow_url_fopen') ) {
			$doc = new DOMDocument();
			$doc->load('http://vimeo.com/api/v2/video/'.$split[3].'.xml');
			$videotags = $doc->getElementsByTagName('video');
			foreach ($videotags as $videotag)
			{
				$imgnode = $videotag->getElementsByTagName('thumbnail_medium');
				$img = $imgnode->item(0)->nodeValue;
			}
                        $update='`pin_image`="' . $img . '",`link_type`="vimeo",';
                }else{
                        $url="http://vimeo.com/api/v2/video/" . $split[3] . ".xml";
                        $curl = curl_init($url);
                        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
                        $result = curl_exec($curl);
                        curl_close($curl);
                        $xml = simplexml_load_string($result);
                        $img = $xml->video->thumbnail_medium;
                        $update='`pin_image`="' . $img . '",`link_type`="vimeo",';
                }
                }

        $editpincategory = JRequest::getVar('board_category');
        $pid = JRequest::getVar('pinId');
        $value = (explode(" ", $editpindesc));

        $count = count($value);
        $query = "SELECT setting_currency from #__pin_site_settings";
        $db->setQuery($query);
        $currency = $db->loadResult();

        for ($i = 0; $i <= $count - 1; $i++) {
            if (preg_match("/^[" . $currency . "]|[0-9]+[.]+$/", $value[$i])) {
                $price = $value[$i];
                $price = (explode($currency, $price));
                    $price=$price[1];
                if ($price != '' && $price) {
                    $query = "SELECT setting_currency from #__pin_site_settings";
                    $db->setQuery($query);
                    $currency = $db->loadResult();

                    if (preg_match("/[" . $currency . "]/", $value[$i])) {
                        $query = "SELECT setting_currency from #__pin_site_settings";
                        $db->setQuery($query);
                        $currency = $db->loadResult();
                        $is_price = explode($currency, $value[$i]);
                        if (is_numeric($is_price[1])) {
                            $gift = '1';
                        }
                    }
                } else {
                    $gift = '0';
                }
            }
        }

        if (isset($btnEditpin)) {

			$BoardName = explode( '*', JRequest::getVar('boardname') );		
			if ($BoardName[0] == 1) {

				$admin_subcatalogue = $BoardName[1];

				$query = "SELECT `catalogue_id`, `subcatalogue_name` 
					FROM `#__pin_subcatalogues` 
					WHERE `subcatalogue_id` = $admin_subcatalogue ";
				$db->setQuery($query);
				$SubCatalogueDet = $db->loadObject();

				if (count($SubCatalogueDet) <= 0) {
					return false;
				} else {
					$subCatalogueName = $SubCatalogueDet->subcatalogue_name;
					$cater = $SubCatalogueDet->catalogue_id;

					$select = "SELECT board_id FROM #__pin_boards WHERE 
								board_name = '$subCatalogueName' AND board_category_id = $cater AND user_id = $userId";
					$db->setQuery($select);
					$subCatalogueId = $db->loadResult();
					if( $subCatalogueId <= 0 ) {
						$query = 'INSERT INTO `#__pin_boards` 
						(`board_category_id` , `board_id` , `user_id`           , `board_name`                            , `board_access` , `status` , `created_date` , `updated_date` , `admin_subcatalogue`) VALUES 
						(' . $cater . '      , ""         , "' . $userId . '" , "' . addslashes($subCatalogueName) . '" , "1"            , "1"      , now()          , now()          , ' . $admin_subcatalogue . ')';
						$db->setQuery($query);
						if (!$db->query()) {
							$this->setError($db->getErrorMsg());
							return false;
						}
						$subCatalogueId = $db->insertid();
					}
				}
			} else {
				$subCatalogueId = $BoardName[1];
				$select = "select board_category_id from #__pin_boards where board_id=" . addslashes($subCatalogueId);
				$db->setQuery($select);
				$catid = $db->loadObjectList();
				$cater = $catid[0]->board_category_id;
			}
	
			$wishItem = JRequest::getVar('wish_item');
			$wishRetailer = JRequest::getVar('wish_retailer');
			$wishProductURL = JRequest::getVar('wish_product_url');
			$wishPrice = JRequest::getVar('price');
			$wishQuantity = JRequest::getVar('wish_quantity');
			$wishStyle = JRequest::getVar('wish_style');
			$wishSize = JRequest::getVar('wish_size');
			$wishColor = JRequest::getVar('wish_color');
			$wishCurrency = JRequest::getVar('wish_currency');

			$wishNotGrant = JRequest::getVar('wish_notgrant');
			$wishOwnGrant = JRequest::getVar('wish_owngrant');

			if ($wishItem == '' || $wishItem == null || $wishItem == JTEXT::_('COM_WISHLOGUE_WISH_ITEM')) {
				$wishItem = 'N/A';
			}
			if ($wishRetailer == '' || $wishRetailer == null || $wishItem == JTEXT::_('COM_WISHLOGUE_WISH_RETAILER')) {
				$wishRetailer = 'N/A';
			}
			if ($wishProductURL == '' || $wishProductURL == null || $wishProductURL == JTEXT::_('COM_WISHLOGUE_WISH_PRODUCT_URL')) {
				$wishProductURL = 'N/A';
			}
			if ($wishCurrency == '' || $wishCurrency == null || $wishCurrency == JTEXT::_('COM_WISHLOGUE_WISH_CURRENCY')) {
				$wishCurrency = 'USD';
			}
			if ($wishPrice == '' || $wishPrice == null || $wishPrice == JTEXT::_('COM_WISHLOGUE_WISH_PRICE')) {
				$wishPrice = '0';
			}
			if ($wishQuantity == '' || $wishQuantity == null || $wishQuantity == JTEXT::_('COM_WISHLOGUE_WISH_QUANTITY')) {
				$wishQuantity = '1';
			}
			if ($wishSize == '' || $wishSize == null || $wishSize == JTEXT::_('COM_WISHLOGUE_WISH_SIZE')) {
				$wishSize = 'N/A';
			}
			if ($wishStyle == '' || $wishStyle == null || $wishStyle == JTEXT::_('COM_WISHLOGUE_WISH_STYLE')) {
				$wishStyle = 'N/A';
			}
			if ($wishColor == '' || $wishColor == null || $wishColor == JTEXT::_('COM_WISHLOGUE_WISH_COLOR')) {
				$wishColor = 'N/A';
			}
			if ($editpindesc == '' || $editpindesc == null || $editpindesc == JTEXT::_('COM_WISHLOGUE_WISH_NOTES')) {
				$editpindesc = 'N/A';
			}

			$wishGrantChange = '';
			if( $wishNotGrant == 'ON' ) {
				$wishGrantChange = ' , `wish_status` = "Not Granted", `wish_status_user` = 0 ';
			} else if( $wishOwnGrant == 'ON' ) {
				$wishGrantChange = ' , `wish_status` = "Granted", `wish_status_user` = ' . $userId . ' ';
			}

			$query = 'UPDATE `#__pin_pins` 
						SET pin_category_id = ' . $cater . ', `wish_item` = "' . $wishItem . '", `wish_retailer` = "' . $wishRetailer . '", `wish_product_url` = "' . $wishProductURL . '", `wish_currency` = "' . $wishCurrency . '", `wish_quantity` = "' . $wishQuantity . '", `wish_size` = "' . $wishSize . '", `wish_style` = "' . $wishStyle . '", `wish_color` = "' . $wishColor . '",
						'.$update.' `pin_user_id`="' . $userId . '",`pin_description` ="' . $editpindesc . '",`pin_url`="' . $editpinlink . '",`pin_board_id`="' . $subCatalogueId . '" ,gift="' . $gift . '", price="' . $wishPrice . '" ' . 
						 $wishGrantChange . 
						' WHERE `pin_id`=' . $pid;
            $db->setQuery($query);
            $db->query();
            $msg = "Wish settings has been successfully saved";
            $app = JFactory::getApplication();
            $app->redirect(JRoute::_('index.php?option=com_wishlogue&view=wish&pinid=' . $pid), $msg, '');
        }
    }

    function deletePin() {

        $db = $this->getDBO();
        $user = JFactory::getUser();
        $userId = $user->get('id');
        $pinid = JRequest::getVar('pinId');
        $btnDelpin = JRequest::getVar('delete_pin');
        $editpinboard = JRequest::getVar('boardname');
        $app = JFactory::getApplication();
        if (isset($btnDelpin)) {

            $query = 'UPDATE `#__pin_pins` SET `status`=0,`published`=-2 WHERE `pin_id`=' . $pinid;
            $db->setQuery($query);
            $db->query();
            $app->redirect(JRoute::_('index.php?option=com_wishlogue&view=cataloguedisplay'));
        }
    }

}

?>
