<?php
session_start();
require_once '../../Server/connection.php';
$valid['success'] = array('success' => false, 'messages' => array());
include('../includes/session.php');
$status  = $_POST['status'];
  
  if($status=='Renew Contract'){
	  
  $contract_id = $_POST['contractId'];
  
  $sql1 = "SELECT * FROM staff_contracts where contract_id='$contract_id'";
$result1 = $conn->query($sql1);
while($row1 = $result1->fetch_array()){
$staff_id = $row1['staff_id'];
		         }
	  
  $contract_start = $_POST['cont_start'];
  $contStart = date('d-m-Y', strtotime($contract_start));
  $cont_dur_id = $_POST['cont_dur_id'];  
  $contEnd = date('Y-m-d', strtotime($contStart.' +$cont_dur_id month')); 
  
  
  $fSql120 = "INSERT INTO staff_contracts (staff_id,contract_start,contract_end,cont_dur_id,cont_status) 
				VALUES ('$staff_id','$contStart','$contEnd','$cont_dur_id','Renew Contract')";

  $resFSql120 = $conn->query($fSql120);
  
  if($resFSql120) {
	 	$valid['success'] = true;
		$valid['messages'] = "Successfully Renewed";	
	} else {
	 	$valid['success'] = false;
	 	$valid['messages'] = "Error while Renewing Contract";
	}
	
	$conn->close();

	echo json_encode($valid);
	  
  }else{
	  
	 $contract_id = $_POST['contractId'];
	 $remarks = addslashes($_POST['remarks']);
	 
	 $termDate = date("d-m-Y");
	 $term_Date = date('Y-m-d', strtotime($termDate));

     $sql1 = "SELECT * FROM staff_contracts where contract_id='$contract_id'";
$result1 = $conn->query($sql1);
while($row1 = $result1->fetch_array()){
$staff_id = $row1['staff_id'];
		         }	 
	  
	$fSql122 = "INSERT INTO staff_termination (staff_id,termination_date,remarks) 
				VALUES ('$staff_id','$term_Date','$remarks')";

	 $resFSql122 = $conn->query($fSql122);
	 
	 if($resFSql122){
					
			$staff_termId = $conn->insert_id;
			
	 $sql4 = "UPDATE staff SET status_id=2 WHERE staff_id  = '$staff_id'";
	 $result4 = $conn->query($sql4); 

     $sql41 = "UPDATE staff_contracts SET staff_termId='$staff_termId',cont_status='Terminate Contract' WHERE contract_id  = '$contract_id'";
	 $result41 = $conn->query($sql41); 

     if($result4&&$result41) {
	 	$valid['success'] = true;
		$valid['messages'] = "Successfully Terminated";	
	} else {
	 	$valid['success'] = false;
	 	$valid['messages'] = "Error while Terminating Contract";
	}
	
	$conn->close();

	echo json_encode($valid);	 
			
	 }

     }

