<?php

class JobOffersHolder extends Page {

    public static $db = array(
		'NumberToDisplay'   => 'Int',
        'DefaultTemporaryEmail' => 'Varchar(255)',
        'DefaultPermanentEmail' => 'Varchar(255)'
	);

	public static $allowed_children = array(  );

    public static $has_many = array (
            //'City' => 'JobOffersCities',
            'JobOffers' => 'JobOffersData'
    );

    public static $defaults = array(
		'NumberToDisplay' => 9
	);


    public $FilterSearch = null;
    public $FilterCity = null;
    public $FilterType = null;
    public $FilterSector = null;
    public $FilterPeriod = null;

    public function getCMSFields() {
		$fields = parent::getCMSFields();
//        $fields->addFieldToTab("Root.Content.Cities", new DataObjectManager(
//                $this,
//                'City',
//                'JobOffersCities',
//                array(
//                    'Title' => 'City',
//                    'TemporaryEmail' => 'Temporary Job Email',
//                    'PermanentEmail' => 'Permanent Job Email'),
//                'getCMSFields_forPopup'
//        ));
        $fields->addFieldToTab('Root.Content.Main',
                new TextField('NumberToDisplay',
                        _t('JobOffersHolder.NUMBER_TO_DISPLAY', '
                            Number to display per page')
                        ),
                'Content');
        $fields->addFieldToTab('Root.Content.Main',
                new TextField('DefaultTemporaryEmail',
                        _t('JobOffersHolder.DEFAULT_TEMPORARY_EMAIL', '
                            Default Temporary Email (in case email in advert is empty)')
                        ),
                'Content');
        $fields->addFieldToTab('Root.Content.Main',
                new TextField('DefaultPermanentEmail',
                        _t('JobOffersHolder.DEFAULT_PERMANENT_EMAIL', '
                            Default Permanent Email (in case email in advert is empty)')
                        ),
                'Content');
        $fields->removeByName('Content', true);
		return $fields;
	}

    public function JobOffers($number=null) {

        $number = $this->NumberToDisplay;

        $start = isset($_REQUEST['start']) ? (int) $_REQUEST['start'] : 0;
        $filter = $this->Filter();
        $currentLocale = Translatable::get_current_locale();
        $showLocale = 'show'.  strtoupper(substr($currentLocale, 0, 2));
        $showLocale = (string)$showLocale;
        $where = "ValidToDate>=CURDATE() AND {$showLocale}=1";
        if($filter->Search) {
            $where .= " AND (
                        Title LIKE '%".$filter->Search."%' OR
                        Company LIKE '%".$filter->Search."%' OR
                        Description LIKE '%".$filter->Search."%' OR
                        AdditionalInfo LIKE '%".$filter->Search."%' OR
                        OfferType LIKE '%".$filter->Search."%'
                        )";
        }
        if($filter->City) {
            $where .= " AND City='".$filter->City."'";
        }
        if($filter->Sector) {
            $where .= " AND Sector='".$filter->Sector."'";
        }
        if($filter->Type) {
            $type = (int)$filter->Type-1;
            $where .= " AND Type='".$type."'";
        }
        if($filter->Period) {
            if($filter->Period == 1) {
                $where .= " AND PublishDate=CURDATE()";
            } elseif($filter->Period == 7) {
                $where .= " AND PublishDate>=DATE_ADD(CURDATE(), INTERVAL -7 DAY)";
            } else {
                $where .= " AND PublishDate>=DATE_ADD(CURDATE(), INTERVAL -30 DAY)";
            }
        }

        $offers = DataObject::get("JobOffersData",
                                    $where,
                                    '"PublishDate" DESC, "Title" ASC', '',
                                    $start . ',' . $number);

		return $offers;

    }

    /*
     * filter get parameters
     */
    public function Filter() {

        $params = new DataObjectSet();
        $params->Search = (isset($_REQUEST['search']) && !empty($_REQUEST['search'])) ? Convert::raw2sql($_REQUEST['search']) : false;
        $params->City   = (isset($_REQUEST['city']) && !empty($_REQUEST['city'])) ? Convert::raw2sql($_REQUEST['city']) : false;
        $params->Period = (isset($_REQUEST['period']) && !empty($_REQUEST['period'])) ? Convert::raw2sql($_REQUEST['period']) : false;
        $params->Sector = (isset($_REQUEST['sector']) && !empty($_REQUEST['sector'])) ? Convert::raw2sql($_REQUEST['sector']) : false;
        $params->Type   = (isset($_REQUEST['type']) && !empty($_REQUEST['type']) && (int)$_REQUEST['type']>0) ? Convert::raw2sql((int)$_REQUEST['type']) : false;
        //print_r($params);
        return $params;

    }

    /*
     * checking job type - 1 = temporary(0 in system), 2 - permanent(1 in system)
     */
    public function FilterCheckedType($type=2) {
        $FilterType = (isset($_REQUEST['type']) && !empty($_REQUEST['type']) && (int)$_REQUEST['type']>0) ? Convert::raw2sql((int)$_REQUEST['type']) : false;
        return ($FilterType == (int)$type);
    }

    /*
     * checking filtered period
     */
    public function FilterCheckedPeriod($period=30) {
        $FilterPeriod = (isset($_REQUEST['period']) && !empty($_REQUEST['period']) && (int)$_REQUEST['period']>0) ? Convert::raw2sql((int)$_REQUEST['period']) : false;
        return ($FilterPeriod == (int)$period);
    }

    /*
     * Expand or collapse additional filter
     */
    public function AdvancedFilter() {
         $filter = $this->Filter();
         return ($filter->City || $filter->Period || $filter->Sector || $filter->Type) ? true : false;
    }

    /*
     * @field - database column
     * select distinct active values from specified column
     */
    public function ActiveParam($field='City') {

        $currentLocale = Translatable::get_current_locale();
        $showLocale = 'show'.  strtoupper(substr($currentLocale, 0, 2));
        $showLocale = (string)$showLocale;
        $where = "ValidToDate>=CURDATE() AND {$showLocale}=1";
        $baseTable = ClassInfo::baseDataClass('JobOffersData');
        $query = new SQLQuery("Distinct \"$field\"", "\"$baseTable\"", $where, '', "\"$field\"");

        $results = $query->execute()->column();
        $params = new DataObjectSet();

        if($results) {
            $filter = $this->Filter();
            $filter = $filter->$field;
            foreach($results as $res) {
                $param = new DataObjectSet();
                $param->Title = (string)$res;
                $param->Active = ((string)$filter==(string)$res);
                $params->push($param);
            }
        }
        return $params;

    }

    public function JobOfferByURLParam() {

        $URLSegment = Convert::raw2sql(Director::urlParam("ID"));
        $currentLocale = Translatable::get_current_locale();
        $showLocale = 'show'.  strtoupper(substr($currentLocale, 0, 2));

        $showLocale = (string)$showLocale;

        return DataObject::get_one("JobOffersData", "URLSegment = '{$URLSegment}' AND ValidToDate>=CURDATE() AND $showLocale=1");
    }

    public function setChildURL($type = 1){
        return Director::absoluteURL($this->URLSegment . "/?type={$type}");
    }

    public function isTypeOf($type = 1){
        return (isset($_GET['type']) && $_GET['type'] == $type) ? true : false;
    }

}

class JobOffersHolder_Controller extends Page_Controller {

	public static $allowed_actions = array ('view', 'CVForm');

    public function init() {
		parent::init();
		// Requirements::javascriptTemplate('joboffers/javascript/joboffers.js', array());
	}

    public function view() {

//        $URLSegment = Convert::raw2sql(Director::urlParam("ID"));
//        $currentLocale = Translatable::get_current_locale();
//        $showLocale = 'show'.  strtoupper(substr($currentLocale, 0, 2));
//
//        $showLocale = (string)$showLocale;
//
//        $offer = DataObject::get_one("JobOffersData", "URLSegment = '{$URLSegment}' AND ValidToDate>=NOW() AND $showLocale=1");
        $offer = $this->JobOfferByURLParam();
        if ($offer) {
            $data = array(
                $this,
                "JobOffers" => $offer
            );
            return $this->customise($data)->renderWith(array('JobOffer', 'JobOffer'));
        } else {
            Director::redirect($this->Link());
        }
        //return $URLSegment;

    }

	public function MetaTitle() {

		if($this->urlParams['Action'] == 'view' && $this->ClassName=='JobOffersHolder') {
            $jobOffer = $this->JobOfferByURLParam();
			$offercity = _t('LangEditor.JOB_OFFER_META_TITLE_CITY', 'Job Offers');
			$title = $jobOffer->OfferType.' - '.$jobOffer->Title.' - '.$offercity.' '.$jobOffer->City;
			//$title = $jobOffer->OfferType.' - '.$jobOffer->Title;
		} else {
			$title = ($this->MetaTitle) ? $this->MetaTitle : $this->Title;
		}
        return $title;
		//return $title . ' - ' . $this->SiteConfig()->Title;
	}


	public function MetaDescription(){

		if($this->urlParams['Action'] == 'view' && $this->JobOfferByURLParam() && $this->JobOfferByURLParam()->Description) {

			$description = str_replace(array('\r\n', '\t', '\n\r'),array(' ',' ', ' '),strip_tags($this->JobOfferByURLParam()->Description));

			$value = trim($description);
			$limit = 157;
			return (strlen($value) > $limit) ? substr($value, 0, $limit) . '...' : $value;
			//return $this->JobOfferByURLParam()->Description;
		} else {
			return $this->MetaDescription;
		}
	}

	public function FacebookMetaTags() {
		$tags = '';
		if($this->urlParams['Action'] == 'view' && $this->JobOfferByURLParam()) {
			$offer = $this->JobOfferByURLParam();
			//$tags .= "<meta property=\"og:title\" content=\"".Convert::raw2att($this->MetaTitle())."\" />";
			$tags .= "<meta property=\"og:type\" content=\"website\" />";
			//$tags .= "<meta property=\"og:description\" content=\"".Convert::raw2att($this->MetaDescription())."\" />";
			if($offer) {
				$tags .= "<meta property=\"og:url\" content=\"".$this->AbsoluteLink()."view/".$offer->URLSegment."\" />";
				//$tags .= "<meta property=\"og:image\" content=\"".$this->BaseHref()."mysite/img/logo_small.gif\" />";
				/*if($offer->LogoID) {
					$tags .= "<meta property="og:image" content="http://ia.media-imdb.com/rock.jpg" />";
				}*/
			}
			$tags .= "<meta property=\"og:site_name\" content=\"".$this->SiteConfig()->Title."\" />";

			return $tags;
			//$tags .= "<meta name=\"description\" content=\"" . Convert::raw2att($this->MetaDescription()) . "\" />\n";
		}
	}


    function CVForm() {
        $offer = $this->JobOfferByURLParam();
        unset($_SESSION['FormInfo']['CVForm_CVForm']['errors']);
        return new CVForm($this, 'CVForm');
    }

}

?>
