<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Functions extends CI_Controller
{
	public function __construct()
	{
		parent::__construct();

		// Force SSL if the constant is set but the HTTPS server variable is not set or set but false.
		if(defined("FORCE_SSL") && FORCE_SSL && preg_match('/^http:/', current_url()) && !is_cli())
		{
			if(defined("LOGGING")) { error_log(PRODUCT_NAME . ": Redirecting to HTTPS."); }
			redirect(str_replace("http://", "https://", current_url()), 'auto', 301);
		}
	}

	public function colour_analysis()
	{
		$config = array();
		$config['upload_path'] 		= ABSOLUTE_PATH . '/temp/';
		$config['allowed_types'] 	= 'gif|jpg|jpeg|png';
		$config['max_size']			= '5242880';	//5MB
		$config['encrypt_name']		= false;
		$config['remove_spaces']	= true;
		$config['overwrite'] 		= true;

		$this->load->library('upload', $config);

		if($this->upload->do_upload("image"))
		{
			$upload_data = $this->upload->data();
		}
		else
		{
			http_repsonse_code(402);
			die();
		}

		$file 	= $upload_data["full_path"];

		if($upload_data["file_type"] == "image/jpeg")
		{
			$im = imagecreatefromjpeg($file);
		}
		else if($upload_data["file_type"] == "image/png")
		{
			$im = imagecreatefrompng($file);
		}
		else if($upload_data["file_type"] == "image/gif")
		{
			$im = imagecreatefromgif($file);
		}
		else
		{
			http_repsonse_code(402);
			die();
		}

		$width 	= $upload_data["image_width"]; //$size[0];
		$height = $upload_data["image_height"]; //$size[1];
		$totals = array();

		for($x=0; $x<$width; $x++)
		{
			for($y=0; $y<$height; $y++)
			{
				$rgb 	= imagecolorat($im, $x, $y);
				$colours= imagecolorsforindex($im, $rgb);

				// Ignore pixels with alpha. This prevents transparent backgrounds from tallying up as black.
				// It also avoids JPG noise or anti-aliasing pixels from skewing results.
				if($colours["alpha"] != 0)
				{
					continue;
				}

				// Ignore full-white pixels, as they are likely a background.
				if($colours["red"] == 255 && $colours["green"] == 255 && $colours["blue"] == 255)
				{
					continue;
				}

				$index 	= $colours["red"] . "," . $colours["green"] . "," . $colours["blue"];// . "," . $colours["alpha"];

				if(isset($totals[$index]))
				{
					$totals[$index]++;
				}
				else
				{
					$totals[$index] = 1;
				}
			}
		}

		unlink($file);
		arsort($totals);

		$count = 0;
		$result = array();

		foreach($totals as $key=>$total)
		{
			$parts 			= explode(",", $key);
			$red 			= (int)$parts[0];
			$green 			= (int)$parts[1];
			$blue 			= (int)$parts[2];
			// $alpha 		= (int)$parts[3];
			$result[$count] = array("red" => $red, "green" => $green, "blue" => $blue,
			                        "hex" => "#" .
			                        str_pad(dechex($red), 	2, "0", STR_PAD_LEFT) .
			                        str_pad(dechex($green), 2, "0", STR_PAD_LEFT) .
			                        str_pad(dechex($blue), 	2, "0", STR_PAD_LEFT));

			$count++;

			if($count == 5)
			{
				break;
			}
		}

		http_response_code(200);
		$this->spit_json($result);
	}

	/**
	 * Convert the passed content to JSON and send it to the browser.
	 *
	 * @access protected
	 * @param mixed $content
	 * @return void
	 */
	protected function spit_json($content, $JSON_NUMERIC_CHECK=false)
	{
		header('Content-type: application/json');

		if($JSON_NUMERIC_CHECK)
		{
			echo json_encode( $content, JSON_NUMERIC_CHECK );
		}
		else
		{
			echo json_encode( $content );
		}
	}

	public function recaptcha()
	{
		Mainframe::init();
		$this->load->helper("captcha");
		$data = verify_recaptcha_v3($this->input->post("g-recaptcha-response"), $this->input->post("action"));
		$this->spit_json($data);
	}

    public function publishing()
    {
   		$date = array(date("Y-m-d H:i:s"));
		// Start publishing
		$this->db->query("UPDATE `pages` SET `published`=1 WHERE `start_publishing` IS NOT NULL AND `start_publishing` <= ?", $date);
		$affected_rows1 = $this->db->affected_rows();
		// Stop publishing
		$this->db->query("UPDATE `pages` SET `published`=0 WHERE `stop_publishing` IS NOT NULL AND `stop_publishing` <= ?", $date);
		$affected_rows2 = $this->db->affected_rows();
		Page::$checked = true;

		if($affected_rows1 > 0 || $affected_rows2 > 0)
		{
			$this->cache->clean();
		}
    }
}
