<?php
  /**
   * Copyright 2011 Zazavi - http://www.zazavi.com
   * Zazavi is free software released under the terms of the GNU General Public License.
   * You should have received a copy of the license.  If not, see <http://www.gnu.org/licenses/>.
   */
  
  if (!defined("_VALID_PHP"))
      die('Direct access to this location is not allowed.');
	  
  class Forms
  {
	  public $formid = null;
	  public $fieldid = null;
	  private $fTable = "forms";
	  private $lTable = "flds";
      
      
      /**
       * Forms::__construct()
       * 
       * @return
       */
      function __construct()
      {
          $this->getFormId();
		  $this->getFieldId();
      }

	  /**
	   * Forms::getFormId()
	   * 
	   * @return
	   */
	  private function getFormId()
	  {
	  	  global $core;
		  if (isset($_GET['formid'])) {
			  $formid = (is_numeric($_GET['formid']) && $_GET['formid'] > -1) ? intval($_GET['formid']) : false;
			  $formid = sanitize($formid);
			  
			  if ($formid == false) {
				  $core->error("You have selected an Invalid FormId","Forms::getFormId()");
			  } else
				  return $this->formid = $formid;
		  }
	  }

	  /**
	   * Forms::getFieldId()
	   * 
	   * @return
	   */
	  private function getFieldId()
	  {
	  	  global $core;
		  if (isset($_GET['fieldid'])) {
			  $fieldid = (is_numeric($_GET['fieldid']) && $_GET['fieldid'] > -1) ? intval($_GET['fieldid']) : false;
			  $fieldid = sanitize($fieldid);
			  
			  if ($fieldid == false) {
				  $core->error("You have selected an Invalid FieldId","Forms::getFieldId()");
			  } else
				  return $this->fieldid = $fieldid;
		  }
	  }

	  /**
	   * Forms::getForms()
	   * 
	   * @return
	   */
	  public function getForms()
	  {
		  global $db, $core;
		  
		  $sql = "SELECT * FROM " . $this->fTable;
          $row = $db->fetch_all($sql);
          
		  if ($row) {
              return $row;
          } else
              return 0;
	  }

	  /**
	   * Forms::getSingleForm()
	   * 
	   * @return
	   */
	  public function getSingleForm($form_id)
	  {
		  global $db;

		  $sql = "SELECT * FROM " . $this->fTable
		  . "\n WHERE id = " . $form_id
		  . "\n AND active = '1'";
		  $row = $db->first($sql);
		  
		  if ($row) {
			  return $row;
		  } else
			  return 0;
	  }
	  
	  /**
	   * Forms::processForm()
	   * 
	   * @return
	   */
	  public function processForm()
	  {
		  global $db, $core;
		  if (empty($_POST['name']))
			  $core->msgs['name'] = "Please Enter Form Name";

		  if (empty($_POST['subject']))
			  $core->msgs['subject'] = "Please Enter Form Subject";
			  
		  if (empty($_POST['mailto']))
			  $core->msgs['mailto'] = "Please Enter Form Mail To";
			  
		  if (empty($_POST['submit']))
			  $core->msgs['submit'] = "Please Enter Form Submit Label";

		  if (empty($_POST['thankyou']))
			  $core->msgs['thankyou'] = "Please Enter Form Submit Message";
			  			  	  
		  if (empty($core->msgs)) {
			  $data = array(
				  'name' => sanitize($_POST['name']), 
				  'subject' => sanitize($_POST['subject']),
				  'thankyou' => sanitize($_POST['thankyou']),
				  'mailto' => sanitize($_POST['mailto']),
				  'submit' => sanitize($_POST['submit_lbl']),
				  'captcha' => intval($_POST['captcha']),
				  'active' => intval($_POST['active'])
			  );

			  
			  ($this->formid) ? $db->update($this->fTable, $data, "id='" . (int)$this->formid . "'") : $db->insert($this->fTable, $data);
			  $message = ($this->formid) ? '<span>Sucess!</span>Form updated successfully!': '<span>Sucess!</span>Form added successfully!';
			  
			  ($db->affected()) ? $core->msgOk($message) :  $core->msgAlert(_SYSTEM_PROCCESS);
		  } else
			  print $core->msgStatus();
	  }

      /**
       * Form::drawForm()
       * 
       * @return
       */ 	  
	  public function drawForm($form_id)
	  {
		  if ($customrows = $this->getFields($form_id, true)) {
			  foreach ($customrows as $frow) {
				  $req = ($frow["fld_req"] == 1) ? " required" : "";
				  $size = ($frow["fld_size"]) ? " size=\"" . $frow["fld_size"] . "\"" : "";
				  $title = ($frow["fld_req"] == 1 && $frow['fld_msg']) ? " title=\"" . $frow['fld_msg'] . "\"" : "";
				  
				  $display = '';
				  
				  switch ($frow["fld_type"]) {
					  case 0:
						  $display = '<span class="inputwrap"><input type="text" value="' . $frow['fld_val'] . '" name="' . $frow["name"] . '" class="inputbox' . $req . '"' . $size . $title . ' /></span>';
						  break;
						  
					  case 1:
						  $display = '<span class="inputwrap"><textarea rows="5" cols="40" name="' . $frow["name"] . '" class="inputbox' . $req . '"' . $title . '>' . $frow['fld_val'] . '</textarea></span>';
						  break;
						  
					  case 2:
						  $select_arr = explode("::", $frow['fld_val']);
						  reset($select_arr);
						  $display = '<span class="inputwrap"><select name="' . $frow["name"] . '" style="width:250px;" class="select' . $req . '"' . $title . '>';
						  foreach ($select_arr as $select) {
							  $display .= "<option value=\"" . $select . "\">" . $select . "</option>\n";
						  }
						  $display .= "</select></span>\n";
						  unset($select);
						  break;
						  
					  case 3:
						  $multiple_arr = explode("::", $frow["fld_val"]);
						  reset($multiple_arr);
						  $display = '<span class="inputwrap"><select name="' . $frow["name"] . '[]" ' . $size . ' multiple="multiple" style="width:250px;" 
						  class="select' . $req . '"' . $title . '>';
						  foreach ($multiple_arr as $mselect) {
							  $display .= "<option value=\"" . $mselect . "\">" . $mselect . "</option>\n";
						  }
						  $display .= "</select></span>\n";
						  unset($mselect);
						  break;
						  
					  case 5:
						  $radio_arr = explode("::", $frow["fld_val"]);
						  reset($radio_arr);
						  foreach ($radio_arr as $rselect) {
							  $display .= '<span class="inputwrap radio"><input type="radio" value="' . $rselect . '" name="' . $frow["name"] . '" /> 
							  '.$rselect . '&nbsp;&nbsp;</span>&nbsp;';
						  }
						  unset($rselect);
						  break;
						  
					  case 4:
						  $checkbox_arr = explode("::", $frow["fld_val"]);
						  reset($checkbox_arr);
						  foreach ($checkbox_arr as $cselect) {
							  $display .= '<span class="inputwrap checkbox"><input type="checkbox" value="' . $cselect . '" name="' . $frow["name"] . '[]" /> 
							  ' . $cselect . '&nbsp;&nbsp;</span>&nbsp;';
						  }
						  unset($cselect);
						  break;
					  case 6:
						  $display = $frow["fld_val"];
						  break;
				  }
				  print "<tr>\n";
				  print "<td width=\"250\"><strong>" . $frow["title"] . ":</strong>";
				  if ($frow["fld_req"] == 1)
					  print " " . required();
				  print "</td>\n";
				  print " <td>" . $display;
				  if ($frow["fld_tip"])
					  print " " . tooltip($frow["fld_tip"]);
				  print "</td>\n";
				  print "</tr>\n";
			  }
			  unset($frow);
		  }
	  }
	  		  
	  /**
	   * Forms::getFields()
	   * 
	   * @return
	   */
	  public function getFields($form_id = false, $active_field = false)
	  {
		  global $db, $core;
		  $id = ($form_id) ? $form_id : $this->formid;
		  $active = ($active_field) ? " AND active = '1'" : '' ;
		  $sql = "SELECT * FROM " . $this->lTable
		  ." \n WHERE form_id = '".$id."'$active"
		  ." \n ORDER BY position";
          $row = $db->fetch_all($sql);
          
		  if ($row) {
              return $row;
          } else
              return 0;
	  }

	  /**
	   * Forms::getFields()
	   * 
	   * @return
	   */
	  public function getFieldLabels($label)
	  {
		  switch($label) {
			  case 0:
			  $display = "Text Field";
			  break;
			  case 1:
			  $display = "Text Area";
			  break;
			  case 2:
			  $display = "Select List";
			  break;
			  case 3:
			  $display = "Multiple List";
			  break; 
			  case 4:
			  $display = "Checkbox";
			  break;
			  case 5:
			  $display = "Radio Button";
			  break; 
			  case 6:
			  $display = "Label";
			  break; 
		  }
		  
		  return $display;
	  }

      /**
       * Form::getFieldList()
       * 
       * @return
       */ 	  
      public function getFieldList()
	  {
		  $arr = array(
				'0' => 'Text Field',
				'1' => 'Text Area',
				'2' => 'Select List',
				'3' => 'Multiple List',
				'4' => 'Checkbox',
				'5' => 'Ratio Button',
				'6' => 'Label'
				);
		  
		  $list = '';
		  foreach ($arr as $key => $val) {
              if ($key == (int)$_GET['fid']) {
                  $list .= "<option selected=\"selected\" value=\"" . $key . "\">" . $val . "</option>\n";
              } else
                  $list .= "<option value=\"" . $key . "\">" . $val . "</option>\n";
          }
          unset($val);
          return $list;
      }
	  /**
	   * Forms::getDefaultFields()
	   * 
	   * @return
	   */
	  public function getDefaultFields()
	  {
		$display = "<ul id=\"default-fields\">";
		$display .= "<li><a href=\"loader.php?do=fields&amp;action=add&amp;formid=".$this->formid."&amp;fid=0\">Text Field</a></li>";
		$display .= "<li><a href=\"loader.php?do=fields&amp;action=add&amp;formid=".$this->formid."&amp;fid=1\">Text Area</a></li>";
		$display .= "<li><a href=\"loader.php?do=fields&amp;action=add&amp;formid=".$this->formid."&amp;fid=2\">Select List</a></li>";
		$display .= "<li><a href=\"loader.php?do=fields&amp;action=add&amp;formid=".$this->formid."&amp;fid=3\">Multiple List</a></li>";
		$display .= "<li><a href=\"loader.php?do=fields&amp;action=add&amp;formid=".$this->formid."&amp;fid=4\">Checkbox</a></li>";
		$display .= "<li><a href=\"loader.php?do=fields&amp;action=add&amp;formid=".$this->formid."&amp;fid=5\">Radio Button</a></li>";
		$display .= "<li><a href=\"loader.php?do=fields&amp;action=add&amp;formid=".$this->formid."&amp;fid=6\">Label</a></li>";
		$display .= "</ul>";
		  
		return $display;
	  }	  

	  /**
	   * Forms::processFields()
	   * 
	   * @return
	   */
	  public function processFields()
	  {
		  global $db, $core;
		  
		  if ($_POST['title'] == "")
			  $core->msgs['title'] = "Please Enter Value for Field Label";
		  
		  if (empty($core->msgs)) {
			  $data = array(
				  'title' => sanitize($_POST['title']), 
				  'form_id' => intval($this->formid), 
				  'fld_type' => intval($_POST['fld_type']), 
				  'name' => paranoia($_POST['title']), 
				  'fld_tip' => sanitize($_POST['fld_tip']), 
				  'fld_val' => sanitize($_POST['fld_val']), 
				  'fld_size' => (isset($_POST['fld_size'])) ? intval($_POST['fld_size']) : "NULL",
				  'fld_msg' => sanitize($_POST['fld_msg']), 
				  'fld_req' => intval($_POST['fld_req'])
			  );
			  
			  ($this->fieldid) ? $db->update($this->lTable, $data, "id='" . (int)$this->fieldid . "'") : $db->insert($this->lTable, $data);
			  $message = ($this->fieldid) ? '<span>Sucess!</span>Field updated successfully!' : '<span>Sucess!</span>Field added successfully!';
			  
			  ($db->affected()) ? $core->msgOk($message) :  $core->msgAlert(_SYSTEM_PROCCESS);
				 
		  } else
			 print $core->msgStatus();
	  }	  

	  /**
	   * Forms::sendForm()
	   * 
	   * @return
	   */
	  public function sendForm($page_id)
	  {
		  global $db, $core, $content, $msgAlert;
		  
		  $frow = $core->getRowById("forms", (int)$page_id);
		  $customrows = $this->getFields($frow['id'], true);
		  
		  foreach ($customrows as $lrow) {
			  if ($lrow['fld_req'] == 1 && empty($_POST[$lrow['name']])) {
				  $core->msgs[] .= $lrow['fld_msg'];
			  }
		  }
		  
		  if($frow['captcha']) {
			  if ($_POST['code'] == "")
				  $core->msgs['code'] = _CF_TOTAL_R;
			  
			  if ($_POST['code'] != "8")
				  $core->msgs['code'] = _CF_TOTAL_ERR;
		  }
		  if (empty($core->msgs)) {
			  $customrows = $this->getFields($frow['id'], true);
			  $val = '';
			  $titleval = '';
			  $dataval = '';
			  foreach ($customrows as $prow) {
				  if ($prow['fld_type'] != 6) {
					  $array = (isset($_POST[$prow['name']])) ? $_POST[$prow['name']] : '&nbsp;';
					  $total = count($array);
					  $value = '';
					  $i = 1;
					  
					  if (is_array($array)) {
						  foreach ($array as $action) {
							  if ($i == $total) {
								  $value .= $action;
							  } else
								  $value .= $action . ",";
							  $i++;
						  }
					  } else
						  $value = $array;
					  
					  $val .= "<tr><td valign=\"top\"><p>" . sanitize($prow['title']) . "</p></td> <td><p>" . sanitize($value) . "</p></td></tr>";
					  $titleval .= $prow['title'] . "[^]";
					  $dataval .=  sanitize($value) . "[^]";
				  }
			  }
	  
			  ob_start();
			  require(ZAZAVILITE . 'mailer/form.tpl.php');
			  $html_message = ob_get_contents();
			  ob_end_clean();
			  
			  require(ZAZAVILITE . "lib/class_mailer.php");
			  $mailer = $mail->sendMail();
			  $message = Swift_Message::newInstance()
						->setSubject($frow['subject'])
						->setTo(array($frow['mailto'] => $core->site_name))
						->setFrom(array($core->site_email => $core->site_name))
						->setBody($html_message, 'text/html'
			  );
			  
			  if ($mailer->send($message)) {
				  $core->msgAlert(_FORM_WAS_SENT);
			  } else
				  $core->msgAlert(_SYSTEM_PROCCESS);

		  } else
			  print $core->msgStatus();
	  }	  

	  /**
	   * Forms::viewFormData()
	   * 
	   * @return
	   */
	  public function viewFormData($id)
	  {
		  global $db;
		  $sql = "SELECT * FROM " . $this->dTable
		  ." \n WHERE id = '".(int)$id."'";
          $row = $db->first($sql);
          
		  if ($row) {
              return $row;
          } else
              return 0;
	  }
  }
?>