<?php
include_once "../../includes/connectConfig.php";

	if($_POST)
	{	
			$valid_extensions = array('pdf');
			
			$namea = $_FILES['pics_a']['name'];
			$sizea = $_FILES['pics_a']['size'];
			$extsa = strtolower(pathinfo($namea, PATHINFO_EXTENSION));

			if(!empty($namea) && !(in_array($extsa, $valid_extensions)) || $sizea > 10000000)
			{
				$output["runstt"] = "warant";
				$output["errorform"] = "a";
				$output["errorreason"] = "Check file type or size";
				echo json_encode($output);
				exit;
			}
			else
			{
				$folder = "../../img/shield-calendar/";  
				$num_rn = substr(md5(uniqid(rand())), 0, 7 );
				
				$p_rec = (isset($_POST["pstrec"])) ? test_input($_POST["pstrec"]) : '';
				$ps_title = test_input($_POST["posttitle"]);
				$remar_kbrief =  test_input($_POST['briefremark']);
				
				$comz = htmlentities($ps_title);
				$chg = preg_replace("/[^a-zA-Z0-9]/", "-", $comz);
				$slug_nm = strtolower($chg);
				
				
				$imga = NULL;
				if(!empty($namea))
				{
					$tmpa = $_FILES['pics_a']['tmp_name'];
					list($txta, $exta) = explode(".", $namea);
					$imga = $slug_nm.'.'.$exta;
					$filePatha = $folder.'/'.$imga;
					move_uploaded_file($tmpa, $filePatha);
				}

				if($_POST['post_info'] == "post-calendar")
				{
					//INSERT INTO TABLE
					$prd = $db_con->prepare("INSERT INTO acadcalendar(ac_year, ac_file, ac_remarks) VALUES(:psyr, :acf, :briefac)");
					
					$prd->bindParam(':psyr',$ps_title);
					$prd->bindParam(':acf',$imga);
					$prd->bindParam(':briefac',$remar_kbrief);
					$prd->execute();
					
					$output["runstt"] = "grant";
					$output["errorreason"] = "Calendar Posted Successfully";
					echo json_encode($output);
					exit;
				}
				
				elseif($_POST['post_info'] == "edit-calendar")
				{
					$imgnm = (!empty($namea) && $imga != "") ? $imga : getOne('acadcalendar'," ac_id = '$p_rec' ",'ac_file');
					
					//INSERT INTO TABLE
					$prd = $db_con->prepare("UPDATE acadcalendar SET ac_year=:psyr, ac_file=:acf, ac_remarks=:briefac WHERE ac_id=:prec");
					
					$prd->bindParam(':psyr',$ps_title);
					$prd->bindParam(':acf',$imgnm);
					$prd->bindParam(':briefac',$remar_kbrief);
					$prd->bindParam(':prec',$p_rec);
					$prd->execute();
					
					$output["runstt"] = "grant";
					$output["errorreason"] = "Post Updated";
					echo json_encode($output);
					exit;
				}
				else
				{
					$output["runstt"] = "warant";
					$output["errorreason"] = "";
					echo json_encode($output);
					exit;
				}
			}
	}
?>