<?php

class JobOffersCities extends DataObject {

    public static $db = array(
        'Title' => 'Text',
        'TemporaryEmail' => 'Varchar(255)',
        'PermanentEmail' => 'Varchar(255)',
        'URLSegment' => 'Varchar(255)'
    );
    public static $has_one = array(
        'JobOffersHolder' => 'JobOffersHolder'
    );
    
    //Set our defaults
    public static $defaults = array(   
        'Title' => 'New City',
        'URLSegment' => 'new-city'
    );
    
    //Add an SQL index for the URLSegment
    public static $indexes = array(
        "URLSegment" => true
    );  

    public function getCMSFields_forPopup() {
        return new FieldSet(
                        new TextField('Title', 'City'),
                        new TextField('TemporaryEmail', 'Temporary job email'),
                        new TextField('PermanentEmail', 'Permanent job email') 
        );
    }
    
    //Set URLSegment to be unique on write
    function onBeforeWrite()
    {       
        // If there is no URLSegment set, generate one from Title
        if((!$this->URLSegment || $this->URLSegment == 'new-city') && $this->Title != 'New City') 
        {
            $this->URLSegment = SiteTree::generateURLSegment($this->Title);
        } 
        else if($this->isChanged('URLSegment')) 
        {
            // Make sure the URLSegment is valid for use in a URL
            $segment = preg_replace('/[^A-Za-z0-9]+/','-',$this->URLSegment);
            $segment = preg_replace('/-+/','-',$segment);
              
            // If after sanitising there is no URLSegment, give it a reasonable default
            if(!$segment) {
                $segment = "city-$this->ID";
            }
            $this->URLSegment = $segment;
        }
  
        // Ensure that this object has a non-conflicting URLSegment value.
        $count = 2;
        while($this->LookForExistingURLSegment($this->URLSegment)) 
        {
            $this->URLSegment = preg_replace('/-[0-9]+$/', null, $this->URLSegment) . '-' . $count;
            $count++;
        }
  
        parent::onBeforeWrite();
    }
          
    //Test whether the URLSegment exists already on another Product
    public function LookForExistingURLSegment($URLSegment)
    {
        return (DataObject::get_one('JobOffersCities', "URLSegment = '" . $URLSegment ."' AND ID != " . $this->ID));
    }
    
    public function currentCity() {
        if(isset($_REQUEST['city']) && !empty($_REQUEST['city'])) {
            $city = Convert::raw2xml($_REQUEST['city']);
            if($city==$this->URLSegment) {
                return true;
            }
        }
        return false;
    }


}

?>
