<?php
class DB
{
	private $host = "localhost";
	private $user = "root";
	private $pass = "";
	private $dbName = "lead_her";
	private $db;

	//_construct
	public function __construct()
	{
		if (!isset($this->db)) {
			try {
				$con = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->dbName, $this->user, $this->pass);
				$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
				$this->db = $con;
			} catch (PDOException $e) {
				echo $e->getMessage();
			}
		}
	}

	//cleans form data to avoid sql injections
	function clean($str)
	{
		$str = trim($str);
		if (!empty($str)) {
			$str = stripslashes($str);
		}
		$str = htmlspecialchars($str, ENT_QUOTES | ENT_HTML5, 'UTF-8');
		return $str;
	}

	//sellect data from tables
	public function getRows($table, $conditions)
	{
		$sql = 'select';
		$sql .= array_key_exists("select", $conditions) ? $conditions['select'] : '*';
		$sql .= ' from ' . $table;

		//if where condition is used
		if (array_key_exists("where", $conditions) && is_array($conditions['where'])) {
			$sql .= ' where ';
			$i   = 0;
			foreach ($conditions["where"] as $key => $value) {
				$pre = ($i > 0) ? ' and ' : '';
				$sql .= $pre . $key . " ='" . $value . "'";
				$i++;
			}
		} elseif (array_key_exists("where", $conditions) && !is_array($conditions['where'])) {
			$sql .= ' where ' . $conditions['where'];
		}


		//if sorting is specified
		if (array_key_exists("order_by", $conditions)) {
			$sql .= ' order by ' . $conditions['order_by'];
		}

		//we may include the limit, max or start for pagination
		if (array_key_exists("start", $conditions) && array_key_exists("limit", $conditions)) {
			$sql .= ' limit ' . $conditions['start'] . ',' . $conditions['limit'];
		} elseif (!array_key_exists("start", $conditions) && array_key_exists("limit", $conditions)) {
			$sql .= ' limit ' . $conditions['limit'];
		}

		//prepare and execute query
		$query = $this->db->prepare($sql);
		$query->execute();

		//return options
		if (array_key_exists("return_type", $conditions) && $conditions['return_type'] != 'all') {
			switch ($conditions['return_type']) {
				case 'count':
					$data = $query->rowCount();
					break;

				case 'single':
					$data = $query->fetch(PDO::FETCH_ASSOC);
					break;

				default:
					$data = '';
					break;
			}
		} else {
			if ($query->rowCount() > 0) {
				$data = $query->fetchAll();
			}
		}

		return !empty($data) ? $data : false;
	}

	//insert data into a single table
	public function insert($table, $data)
	{
		if (!empty($table) && is_array($data)) {
			$columns	= implode(',', array_keys($data));
			$values		= ":" . implode(',:', array_keys($data));
			$sql		= "insert into " . $table . "(" . $columns . ") values(" . $values . ")";
			$query		= $this->db->prepare($sql);
			foreach ($data as $key => $val) {
				$query->bindValue(':' . $key, $val);
			}
			$insert		= $query->execute();
			return $insert ? $this->db->lastInsertId() : false;
		} else {
			return false;
		}
	}

	//update data
	public function update($table, $data, $conditions)
	{
		if (!empty($data) && is_array($data)) {
			$colSet = '';
			$where = '';
			$i = 0;

			foreach ($data as $key => $value) {
				$pre = ($i > 0) ? ', ' : '';
				$colSet .= $pre . $key . " ='" . $value . "'";
				$i++;
			}

			if (!empty($conditions) && is_array($conditions)) {
				$where .= ' where ';
				$i = 0;
				foreach ($conditions as $key => $value) {
					$pre = ($i > 0) ? ' and ' : '';
					$where .= $pre . $key . " ='" . $value . "'";
					$i++;
				}
			}

			$sql = "update " . $table . " set " . $colSet . $where;
			$query = $this->db->prepare($sql);
			$update = $query->execute();
			return $update ? $query->rowCount() : false;
		} else {
			return false;
		}
	}

	//delete data
	public function delete($table, $conditions)
	{
		$whereSql = '';
		if (!empty($conditions) && is_array($conditions)) {
			$whereSql .= ' where ';
			$i = 0;
			foreach ($conditions as $key => $value) {
				$pre = ($i > 0) ? ' and ' : '';
				$whereSql .= $pre . $key . " = '" . $value . "'";
				$i++;
			}
		}
		$sql = "delete from " . $table . $whereSql;
		$delete = $this->db->exec($sql);
		return $delete ? $delete : false;
	}

	//custom echo 	
	public function custom_echo($x, $length)
	{
		if (strlen($x) <= $length) {
			echo $x;
		} else {
			$y = substr($x, 0, $length) . '...';
			echo $y;
		}
	}

	//changes date/time format
	public function shortDate($date)
	{
		$date = date_create($date);
		return date_format($date, "M d Y");
	}

	function get_random_string_max($length)
	{

		$array = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
		$text = "";

		$length = rand(4, $length);

		for ($i = 0; $i < $length; $i++) {

			$random = rand(0, 61);

			$text .= $array[$random];
		}

		return $text;
	}

	public function formatDate($date)
	{
		$dbdate =  substr($date, 0, 10);

		$now = time(); // or your date as well
		$your_date = strtotime($dbdate);
		$datediff = $now - $your_date;


		$Agelable = "";

		if (round($datediff / (60 * 60 * 24)) == 1) {

			$Agelable = "Today";
			return ($Agelable);
		} elseif (round($datediff / (60 * 60 * 24)) == 0) {
			$Agelable = "Yesterday";
			return ($Agelable);
		} elseif (round($datediff / (60 * 60 * 24)) < 5) {
			$Agelable = date("l", strtotime($dbdate));
			return ($Agelable);
		} elseif (round($datediff / (60 * 60 * 24)) >= 5) {
			$Agelable = date("d-M-Y", strtotime($dbdate));
			return ($Agelable);
		}
	}



	//send email notification
	//
	public function SendMailNotif($email, $message, $subject)
	{

		$email = filter_var($email, FILTER_VALIDATE_EMAIL);


		if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");



		$address = "muscco@muscco.org";


		$e_subject = $subject;


		$content = $message;



		$e_content = $content . PHP_EOL . PHP_EOL;

		$msg = wordwrap($e_content, 70);

		$headers = "From: MUSCCO <muscco@muscco.org>" . PHP_EOL;
		$headers .= "Reply-To: MUSCCO <muscco@muscco.org>" . PHP_EOL;
		$headers .= "MIME-Version: 1.0" . PHP_EOL;
		$headers .= "Content-type:text/html;charset=UTF-8" . PHP_EOL;

		if (mail($address, $e_subject, $msg, $headers)) {
			return true;
		} else {
			return false;
		}
	}
	/********************************************end email function**************************************************/

	//send system notifications
	//notifications within the system
	public function sendSystemNotification($to, $from, $subject, $message)
	{
		$details = array(
			'postedBy' => $from,
			'goingTo' => $to,
			'subject' => $subject,
			'message' => $message
		);
		$send = $this->insert('notifications', $details);
		if ($send) {
			return true;
		} else {
			return false;
		}
	}
	/*****************************************************************************************************/


	/*****************************************************************************************************
Alert function that displays alerts after executing ana action
	 ******************************************************************************************************/
	public function displayAlert($title, $msg, $type, $url)
	{
		echo "<script type='text/javascript'>
              sweetAlert({
                title: '" . $title . "',
                text: '" . $msg . "',
                type: '" . $type . "'
              },
              function () {
                setTimeout('window.location.href = \"" . $url . "\"; ');
              }
        	);
         </script>";
	}
	/*****************************************************************************************************/
}
