<?php
session_start();
require_once '../utils/errorhandler.php';
require_once '../utils/response.php';
require_once '../model/dbclass.php';
require_once '../model/model.php';
require_once '../model/organisationinfo.php';
require_once '../model/user.php';

date_default_timezone_set('Africa/Lagos');

if ($_SESSION['wuseremail'] === null || !isset($_SESSION['wuseremail'])) {
     exit(badRequest(204,'Invalid session data. Proceed to login'));
}

$permissions = explode("|",$_SESSION["permissions"]);
if(in_array("NO POSTING",$permissions)){
    exit(badRequest(204,'No posting enabled'));
}

if($_FILES["userphotoname"]["name"] !== "" && $_FILES["userphotoname"]["name"] !== null && $_FILES["userphotoname"]["name"] !== "-"){
	$filenamearray = explode(".",$_FILES["userphotoname"]["name"]); 
	$filename1 = $filenamearray[0] . mt_rand(10,111111111) . "." . end($filenamearray);
}else { $filename1 = "-"; }

	$returnvalue = '';
    if($_POST["photofilename"] !== null && $_POST["photofilename"] !== "-"){	
		$allowedExts = array("gif", "jpeg", "jpg","pdf");
		$temp = explode(".", $_FILES["userphotoname"]["name"]);
		$returnvalue .= '' . $_FILES["userphotoname"]["name"];
		$extension = end($temp);
		if ((($_FILES["userphotoname"]["type"] === "image/gif") || ($_FILES["userphotoname"]["type"] === "image/jpeg") || ($_FILES["userphotoname"]["type"] === "image/jpg") || ($_FILES["userphotoname"]["type"] === "image/pjpeg") || ($_FILES["userphotoname"]["type"] === "image/png") || ($_FILES["userphotoname"]["type"] === "application/pdf")) && in_array($extension, $allowedExts)){
			if ($_FILES["userphotoname"]["error"] > 0){
				$returnvalue .= ' | error saving photo'; //echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
			}else{
				/*
				if (file_exists("../images/borrowers/" . $_FILES["userphotoname"]["name"])){
					$returnvalue .= ' | the file exists'; //echo $_FILES["userphoto"]["name"] . " already exists. ";
      		    }else{ */
					move_uploaded_file($_FILES["userphotoname"]["tmp_name"],"../images/" . $filename1);
					$returnvalue .= "Upload Successful";
      		    //}
    		}
		}else{
             $returnvalue .= ' | Invalid file type';	    
		}
      }

$organisation = new OrganisationInfo();
$res = $organisation->getOrganisationInfo("company_id = '" . $_POST["company_id"] . "'");

if($res){
    $organisation_code = $res["organisation_code"];
   if(htmlentities($_REQUEST["companyname"],ENT_QUOTES) !== $res["companyname"]){
       $organisation_code_old = $res["organisation_code"];
        $payload = array(
            "organisation_code" => $organisation_code
            );
        	
        $payload = json_encode($payload);
        
        $curl = curl_init();
        
        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://hems.com.ng/hems/controllers/getlicenceagreement.php",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $payload,
            CURLOPT_HTTPHEADER => array(
              "cache-control: no-cache",
              "content-type: application/json"
            ),
        ));
        
        $response = curl_exec($curl);
        
        if($response && $response["code"] == 200){
            $organisation_name = htmlentities($_REQUEST["companyname"],ENT_QUOTES);
            $organisation_code = base64_encode(($_REQUEST["companyname"] . mt_rand(1000,111111111)));
            
            $payload = array(
                "organisation_code" => $organisation_code,
                "organisation_name" => $organisation_name,
                "organisation_code_old" => $res["organisation_code"]
                );
            	
            $payload = json_encode($payload);
            
            $curl = curl_init();
            
            curl_setopt_array($curl, array(
                CURLOPT_URL => "https://hems.com.ng/hems/controllers/updatelicenceagreement.php",
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_POSTFIELDS => $payload,
                CURLOPT_HTTPHEADER => array(
                  "cache-control: no-cache",
                  "content-type: application/json"
                ),
            ));
            
            $response = curl_exec($curl);            
        }else{
            $organisation_name = htmlentities($_REQUEST["companyname"],ENT_QUOTES);
            $organisation_code = base64_encode(($_REQUEST["companyname"] . mt_rand(1000,111111111)));
            $payload = array(
                "organisation_code" => $organisation_code,
                "organisation_name" => $organisation_name
                );
            	
            $payload = json_encode($payload);
            
            $curl = curl_init();
            
            curl_setopt_array($curl, array(
                CURLOPT_URL => "https://hems.com.ng/hems/controllers/licenceagreement.php",
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 30,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_POSTFIELDS => $payload,
                CURLOPT_HTTPHEADER => array(
                  "cache-control: no-cache",
                  "content-type: application/json"
                ),
            ));
            
            $response = curl_exec($curl);            
        }
   }
    $id = $res["company_id"];
	
	$query = "companyname = '" . ((isset($_REQUEST["companyname"]) && $_REQUEST["companyname"] !== '') ? htmlentities($_REQUEST["companyname"]) : $res["companyname"]) . "',
	address = '" . ((isset($_REQUEST["address"]) && $_REQUEST["address"] !== '') ? $_REQUEST["address"] : $res["address"]) . "',
	telephone = '" . ((isset($_REQUEST["telephone"]) && $_REQUEST["telephone"] !== '') ? $_REQUEST["telephone"] : $res["telephone"]) . "',
	logo = '" . (($filename1 !== '-' && $filename1 !== '') ? $filename1 : $res["logo"]) . "',
	accounting_yearend = '" . ((isset($_REQUEST["accounting_yearend"]) && $_REQUEST["accounting_yearend"] !== '') ? $_REQUEST["accounting_yearend"] : $res["accounting_yearend"]) . "',
	backdated_transaction = '" . ((isset($_REQUEST["backdated_transaction"]) && $_REQUEST["backdated_transaction"] !== '') ? $_REQUEST["backdated_transaction"] : $res["backdated_transaction"]) . "',
	future_transaction = '" . ((isset($_REQUEST["future_transaction"]) && $_REQUEST["future_transaction"] !== '') ? $_REQUEST["future_transaction"] : $res["future_transaction"]) . "',
	default_cashaccount = '" . ((isset($_REQUEST["default_cashaccount"]) && $_REQUEST["default_cashaccount"] !== '') ? $_REQUEST["default_cashaccount"] : $res["default_cashaccount"]) . "',
	default_assetaccount = '" . ((isset($_REQUEST["default_assetaccount"]) && $_REQUEST["default_assetaccount"] !== '') ? $_REQUEST["default_assetaccount"] : $res["default_assetaccount"]) . "',
	default_incomeaccount = '" . ((isset($_REQUEST["default_incomeaccount"]) && $_REQUEST["default_incomeaccount"] !== '') ? $_REQUEST["default_incomeaccount"] : $res["default_incomeaccount"]) . "',
	
	default_taxaccount = '" . ((isset($_REQUEST["default_taxaccount"]) && $_REQUEST["default_taxaccount"] !== '') ? $_REQUEST["default_taxaccount"] : $res["default_taxaccount"]) . "',
	default_glexpenseaccount = '" . ((isset($_REQUEST["default_glexpenseaccount"]) && $_REQUEST["default_glexpenseaccount"] !== '') ? $_REQUEST["default_glexpenseaccount"] : $res["default_glexpenseaccount"]) . "',
	default_glloanaccount = '" . ((isset($_REQUEST["default_glloanaccount"]) && $_REQUEST["default_glloanaccount"] !== '') ? $_REQUEST["default_glloanaccount"] : $res["default_glloanaccount"]) . "',
	default_noncashaccount = '" . ((isset($_REQUEST["default_noncashaccount"]) && $_REQUEST["default_noncashaccount"] !== '') ? $_REQUEST["default_noncashaccount"] : $res["default_noncashaccount"]) . "',
	default_glwagesaccount = '" . ((isset($_REQUEST["default_glwagesaccount"]) && $_REQUEST["default_glwagesaccount"] !== '') ? $_REQUEST["default_glwagesaccount"] : $res["default_glstaffaccount"]) . "',

	default_longtermliabilityaccount = '" . ((isset($_REQUEST["default_longtermliabilityaccount"]) && $_REQUEST["default_longtermliabilityaccount"] !== '') ? $_REQUEST["default_longtermliabilityaccount"] : $res["default_propertyaccount"]) . "',
	default_depreciation = '" . ((isset($_REQUEST["default_depreciation"]) && $_REQUEST["default_depreciation"] !== '') ? $_REQUEST["default_depreciation"] : $res["default_depreciation"]) . "',
	default_liabilityaccount = '" . ((isset($_REQUEST["default_liabilityaccount"]) && $_REQUEST["default_liabilityaccount"] !== '') ? $_REQUEST["default_liabilityaccount"] : $res["default_excessaccount"]) . "',
	default_vattaxaccount = '" . ((isset($_REQUEST["default_vattaxaccount"]) && $_REQUEST["default_vattaxaccount"] !== '') ? $_REQUEST["default_vattaxaccount"] : $res["default_returncashaccount"]) . "',
	default_glsalesaccount = '" . ((isset($_REQUEST["default_glsalesaccount"]) && $_REQUEST["default_glsalesaccount"] !== '') ? $_REQUEST["default_glsalesaccount"] : $res["default_niaaccount"]) . "',
	default_bankaccount = '" . ((isset($_REQUEST["default_bankaccount"]) && $_REQUEST["default_bankaccount"] !== '') ? $_REQUEST["default_bankaccount"] : $res["default_bankaccount"]) . "',
	default_inventory = '" . ((isset($_REQUEST["default_inventory"]) && $_REQUEST["default_inventory"] !== '') ? $_REQUEST["default_inventory"] : $res["default_inventory"]) . "',
	default_payableaccount = '" . ((isset($_REQUEST["default_payableaccount"]) && $_REQUEST["default_payableaccount"] !== '') ? $_REQUEST["default_payableaccount"] : $res["default_payableaccount"]) . "',
	default_receivableaccount = '" . ((isset($_REQUEST["default_receivableaccount"]) && $_REQUEST["default_receivableaccount"] !== '') ? $_REQUEST["default_receivableaccount"] : $res["default_receivableaccount"]) . "',
	
	default_equityaccount = '" . ((isset($_REQUEST["default_equityaccount"]) && $_REQUEST["default_equityaccount"] !== '') ? $_REQUEST["default_equityaccount"] : $res["default_equityaccount"]) . "',

	smssenderid = '" . ((isset($_REQUEST["smssenderid"]) && $_REQUEST["smssenderid"] !== '') ? $_REQUEST["smssenderid"] : $res["smssenderid"]) . "',
	smscharge = " . ((isset($_REQUEST["smscharge"]) && $_REQUEST["smscharge"] > 0) ? $_REQUEST["smscharge"] : $res["smscharge"]) . ",
	automate_smscharge = '" . ((isset($_REQUEST["automate_smscharge"]) && $_REQUEST["automate_smscharge"] !== '') ? $_REQUEST["automate_smscharge"] : $res["automate_smscharge"]) . "',
	smschargeaccount = '" . ((isset($_REQUEST["smschargeaccount"]) && $_REQUEST["smschargeaccount"] !== '') ? $_REQUEST["smschargeaccount"] : $res["smschargeaccount"]) . "',
	vatrate = " . ((isset($_REQUEST["vatrate"]) && $_REQUEST["vatrate"] > 0) ? $_REQUEST["vatrate"] : $res["vatrate"]) . ",
	whtrate = " . ((isset($_REQUEST["whtrate"]) && $_REQUEST["whtrate"] > 0) ? $_REQUEST["whtrate"] : $res["whtrate"]) . ",
	organisation_code = '$organisation_code',
	
	consumptioncharge = " . ((isset($_REQUEST["consumptioncharge"]) && $_REQUEST["consumptioncharge"] > 0) ? $_REQUEST["consumptioncharge"] : $res["consumptioncharge"]) . ",
	servicecharge = " . ((isset($_REQUEST["servicecharge"]) && $_REQUEST["servicecharge"] > 0) ? $_REQUEST["servicecharge"] : $res["servicecharge"]) . ",

	mobile = '" . ((isset($_REQUEST["mobile"]) && $_REQUEST["mobile"] !== '') ? $_REQUEST["mobile"] : $res["mobile"]) . "'";
	
	$result = $organisation->updateOrganisationDetails($query, $id);
	if($result){
        $user = new User();
        $user->addUserActivity($_SESSION["hemsemail"], "Settings info updated at" . date("Y-m-d H:i:s"), date("Y-m-d H:i:s"), "ORGANISATION");
	    
		echo success($result,200, "Successful","Successful");
	}else{
		echo success($result,204, "Failed: " . $result,"ERROR"); 
	}
	
}else{
    
    $organisation_code = base64_encode(($_REQUEST["companyname"] . mt_rand(1000,111111111)));
    $user = $_SESSION["hemsemail"]; // !== null ? $_SESSION["hemsemail"] : 'matthew@gmail.com';
    
	$fields = "companyname,email,address,telephone,mobile,logo,no_of_users,accounting_yearend,backdated_transaction,
	future_transaction,default_cashaccount,default_assetaccount,default_incomeaccount,default_taxaccount,default_glexpenseaccount,
	default_glloanaccount,default_noncashaccount,default_glwagesaccount,default_equityaccount,default_longtermliabilityaccount,
	default_depreciation,default_liabilityaccount,default_vattaxaccount,default_glsalesaccount,
	default_bankaccount,default_inventory,default_payableaccount,default_receivableaccount,
	smssenderid,smscharge,automate_smscharge,smschargeaccount,vatrate,whtrate,apikey,updated_at,tlog,username,organisation_code";
	
	$values = "'" . ((isset($_REQUEST["companyname"]) && $_REQUEST["companyname"] !== '') ? htmlentities($_REQUEST["companyname"],ENT_QUOTES) : '-') . "',
	'" . ((isset($_REQUEST["email"]) && $_REQUEST["email"] !== '') ? $_REQUEST["email"] : 'user@gmail.com') . "',
	'" . ((isset($_REQUEST["address"]) && $_REQUEST["address"] !== '') ? $_REQUEST["address"] : '-') . "',
	'" . ((isset($_REQUEST["telephone"]) && $_REQUEST["telephone"] !== '') ? $_REQUEST["telephone"] : '-') . "',
	'" . ((isset($_REQUEST["mobile"]) && $_REQUEST["mobile"] !== '') ? $_REQUEST["mobile"] : '-') . "',
	'" . $filename1 . "',
	" . ((isset($_REQUEST["no_of_users"]) && intval($_REQUEST["no_of_users"]) > 0) ? $_REQUEST["no_of_users"] : 6) . ",
	'" . ((isset($_REQUEST["accounting_yearend"]) && $_REQUEST["accounting_yearend"] !== '') ? $_REQUEST["accounting_yearend"] : '31 December') . "',
	'" . ((isset($_REQUEST["backdated_transaction"]) && $_REQUEST["backdated_transaction"] !== '') ? $_REQUEST["backdated_transaction"] : 'NO') . "',
	'" . ((isset($_REQUEST["future_transaction"]) && $_REQUEST["future_transaction"] !== '') ? $_REQUEST["future_transaction"] : 'NO') . "',
	'" . ((isset($_REQUEST["default_cashaccount"]) && $_REQUEST["default_cashaccount"] !== '') ? $_REQUEST["default_cashaccount"] : '-') . "',
	'" . ((isset($_REQUEST["default_assetaccount"]) && $_REQUEST["default_assetaccount"] !== '') ? $_REQUEST["default_assetaccount"] : '-') . "',
	'" . ((isset($_REQUEST["default_incomeaccount"]) && $_REQUEST["default_incomeaccount"] !== '') ? $_REQUEST["default_incomeaccount"] : '-') . "',
	
	'" . ((isset($_REQUEST["default_taxaccount"]) && $_REQUEST["default_taxaccount"] !== '') ? $_REQUEST["default_taxaccount"] : '-') . "',
	'" . ((isset($_REQUEST["default_glexpenseaccount"]) && $_REQUEST["default_glexpenseaccount"] !== '') ? $_REQUEST["default_glexpenseaccount"] : '-') . "',
	'" . ((isset($_REQUEST["default_glloanaccount"]) && $_REQUEST["default_glloanaccount"] !== '') ? $_REQUEST["default_glloanaccount"] : '-') . "',
	'" . ((isset($_REQUEST["default_noncashaccount"]) && $_REQUEST["default_noncashaccount"] !== '') ? $_REQUEST["default_noncashaccount"] : '-') . "',
	'" . ((isset($_REQUEST["default_glwagesaccount"]) && $_REQUEST["default_glwagesaccount"] !== '') ? $_REQUEST["default_glwagesaccount"] : '-') . "',
	
	'" . ((isset($_REQUEST["default_equityaccount"]) && $_REQUEST["default_equityaccount"] !== '') ? $_REQUEST["default_equityaccount"] : '-') . "',
	'" . ((isset($_REQUEST["default_longtermliabilityaccount"]) && $_REQUEST["default_longtermliabilityaccount"] !== '') ? $_REQUEST["default_longtermliabilityaccount"] : '-') . "',
	'" . ((isset($_REQUEST["default_depreciation"]) && $_REQUEST["default_depreciation"] !== '') ? $_REQUEST["default_depreciation"] : '-') . "',
	'" . ((isset($_REQUEST["default_liabilityaccount"]) && $_REQUEST["default_liabilityaccount"] !== '') ? $_REQUEST["default_liabilityaccount"] : '-') . "',
	'" . ((isset($_REQUEST["default_vattaxaccount"]) && $_REQUEST["default_vattaxaccount"] !== '') ? $_REQUEST["default_vattaxaccount"] : '-') . "',
	'" . ((isset($_REQUEST["default_glsalesaccount"]) && $_REQUEST["default_glsalesaccount"] !== '') ? $_REQUEST["default_glsalesaccount"] : '-') . "',
	'" . ((isset($_REQUEST["default_bankaccount"]) && $_REQUEST["default_bankaccount"] !== '') ? $_REQUEST["default_bankaccount"] : '-') . "',
	'" . ((isset($_REQUEST["default_inventory"]) && $_REQUEST["default_inventory"] !== '') ? $_REQUEST["default_inventory"] : '-') . "',
	'" . ((isset($_REQUEST["default_payableaccount"]) && $_REQUEST["default_payableaccount"] !== '') ? $_REQUEST["default_payableaccount"] : '-') . "',
	'" . ((isset($_REQUEST["default_receivableaccount"]) && $_REQUEST["default_receivableaccount"] !== '') ? $_REQUEST["default_receivableaccount"] : '-') . "',
	
	'" . ((isset($_REQUEST["smssenderid"]) && $_REQUEST["smssenderid"] !== '') ? $_REQUEST["smssenderid"] : '-') . "',
	" . ((isset($_REQUEST["smscharge"]) && $_REQUEST["smscharge"] > 0) ? $_REQUEST["smscharge"] : 0) . ",
	'" . ((isset($_REQUEST["automate_smscharge"]) && $_REQUEST["automate_smscharge"] !== '') ? $_REQUEST["automate_smscharge"] : '-') . "',
	'" . ((isset($_REQUEST["smschargeaccount"]) && $_REQUEST["smschargeaccount"] !== '') ? $_REQUEST["smschargeaccount"] : '-') . "',
	" . ((isset($_REQUEST["vatrate"]) && $_REQUEST["vatrate"] > 0) ? $_REQUEST["vatrate"] : 0) . ",
	" . ((isset($_REQUEST["whtrate"]) && $_REQUEST["whtrate"] > 0) ? $_REQUEST["whtrate"] : 0) . ",
	'" . ((isset($_REQUEST["apikey"]) && $_REQUEST["apikey"] !== '') ? $_REQUEST["apikey"] : '-') . "',

	'" . date('Y-m-d H:i:s') . "',
	'" . $user . " " . date('Y-m-d H:i:s') . "',
	'" . $user . "',
	'$organisation_code'";
	
	$result = $organisation->registerOrganisation($fields, $values);
	
	if($result){
        $organisation_name = htmlentities($_REQUEST["companyname"],ENT_QUOTES);
        $payload = array(
            "organisation_code" => $organisation_code,
            "organisation_name" => $organisation_name
            );
        	
        $payload = json_encode($payload);
        
        $curl = curl_init();
        
        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://hems.com.ng/hems/controllers/licenceagreement.php",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $payload,
            CURLOPT_HTTPHEADER => array(
              "cache-control: no-cache",
              "content-type: application/json"
            ),
        ));
        
        $response = curl_exec($curl);
        
            
        $user = new User();
        $user->addUserActivity($_SESSION["hemsemail"], "Organisation info created at" . date("Y-m-d H:i:s"), date("Y-m-d H:i:s"), "SETTINGS");
	    
		echo success($result,200, "Successful","Successful");
	}else{
		echo success($result,204, "Failed: " . $result,"ERROR"); 
	}
}

?>
