<?php
defined($security_key) or exit;

//------------------------------------------
// equipments
//------------------------------------------
//Connect to DB
$pdo = dbConnect($dbname);

//CONTENT FROM API (POST)
$post_content = json_decode($input,true);

//SoldTo is empty
if (empty($partner->soldto) || $partner->soldto == ''){$soldto_search = '%';} else {$soldto_search = '-%';}

//default whereclause
$whereclause = '';

list($whereclause,$condition) = getWhereclause('',$permission,$partner,'');

//SET PARAMETERS FOR QUERY
$id = $post_content['rowID'] ?? ''; //check for rowID
$command = ($id == '')? 'insert' : 'update';  //IF rowID = empty then INSERT
if (isset($post_content['delete'])){$command = 'delete';} //change command to delete
$date = date('Y-m-d H:i:s');

//CREATE EMPTY STRINGS
$owner_equipment = 0;
$clause = '';
$clause_insert ='';
$input_insert = '';


if ($id != ''){
    //DEFINE ACCOUNTHIERARCHY
    $stmt = $pdo->prepare('SELECT * FROM equipment WHERE rowID = ?');
    $stmt->execute([$id]);
    $equipment_data = $stmt->fetch();
     
    $equipment_old = json_decode($equipment_data['accounthierarchy']);

    $salesid_new = ((isset($post_content['salesid']) && $post_content['salesid'] != '' && $post_content['salesid'] != $equipment_old->salesid)? $post_content['salesid'] : $equipment_old->salesid);
    $soldto_new = ((isset($post_content['soldto']) &&$post_content['soldto'] != '' && $post_content['soldto'] != $equipment_old->soldto)? $post_content['soldto'] : $equipment_old->soldto);
    $shipto_new = ((isset($post_content['shipto']) &&$post_content['shipto'] != '' && $post_content['shipto'] != $equipment_old->shipto)? $post_content['shipto'] : $equipment_old->shipto);
    $location_new = ((isset($post_content['location']) &&$post_content['location'] != '' && $post_content['location'] != $equipment_old->location)? $post_content['location'] : $equipment_old->location);
    $section_new = ((isset($post_content['section']) &&$post_content['section'] != '' && $post_content['section'] != $equipment_old->section)? $post_content['section'] : $equipment_old->section);
    
    $owner_equipment = (($equipment_data['createdby'] == $username)? 1 : 0);

    if ($permission == 4){
        //ADMIN+ ONLY ARE ALLOWED TO CHANGE SALES AND SOLD
        $account = array(
        "salesid"=>$salesid_new,
        "soldto"=>$soldto_new,
        "shipto"=>$shipto_new,
        "location"=>$location_new,
        "section"=>$section_new
    );
    } 
    elseif ($permission == 3) {
        //ADMIN ONLY ARE ALLOWED TO CHANGE SOLD
        $account = array(
            "salesid"=>$equipment_old->salesid,
            "soldto"=>$soldto_new,
            "shipto"=>$shipto_new,
            "location"=>$location_new,
            "section"=>$section_new
        );
    }
    else {
        $account = array(
            "salesid"=>$equipment_old->salesid,
            "soldto"=>$equipment_old->soldto,
            "shipto"=>$shipto_new,
            "location"=>$location_new,
            "section"=>$section_new
        );
    }
}    
else {
    //ID is empty => INSERT / NEW RECORD
    if ($permission == 4){
        $account = array(
            "salesid"=>$post_content['salesid'],
            "soldto"=>$post_content['soldto'],
            "shipto"=>$post_content['shipto'],
            "location"=>$post_content['location'],
            "section"=>$post_content['section']

        );
    } 
    elseif ($permission == 3){
        $account = array(
            "salesid"=>$partner->salesid,
            "soldto"=>$post_content['soldto'],
            "shipto"=>$post_content['shipto'],
            "location"=>$post_content['location'],
            "section"=>$post_content['section']

        );
    }else {
        $account = array(
            "salesid"=>$partner->salesid,
            "soldto"=>$partner->soldto,
            "shipto"=>$post_content['shipto'],
            "location"=>$post_content['location'],
            "section"=>$post_content['section']

        );
    }
}
//CHECK IF PARTNER HAS PARTNER RECORD - IF NOT CREATE AND USE
foreach ($account as $key => $value){
	if ($key != "section"){
        //CHECK for id- pattern
		if (empty($value) ||$value == '' || preg_match('/\-.*/',$value)){
			//Do Nothing
		}
		else {
			//No partner ID found
			switch ($key) {
				case 'salesid':
					$p_type = 'SalesID';
					break;
				case 'soldto':
					$p_type = 'SoldTo';
					break;
				case 'shipto':
					$p_type = 'ShipTo';
					break;
				case 'location':
					$p_type = 'Location';
					break;
			}
            //Create partner and push to array account
			$account[$key] = createPartner($partner->salesid,$partner->soldto,$value,$p_type,$userkey);	
		}
	}
}
// CREATE ACCOUNTHIERARCHY JSON FROM ACCOUNT ARRAY
$accounthierarchy = json_encode($account, JSON_UNESCAPED_UNICODE);

$post_content['updatedby'] = $username;

//ADD STANDARD PARAMETERS TO ARRAY BASED ON INSERT OR UPDATE
if ($command == 'update'){

    //RESET WARRANTY AND SERVICE DATES WHEN STATUS IS CHANGED TO SEND(3)
    if (isset($post_content['status']) && $post_content['status'] == 3 && $equipment_data['status'] != 3)
    {
        $post_content['service_date'] = $date;
        $post_content['warranty_date'] = $date;

    }
    //UPDATE CHANGELOG BASED ON STATUS CHANGE
    if (isset($post_content['status']) && $post_content['status'] != $equipment_data['status'])
    {
        changelog($dbname,'equipment',$equipment_data['rowID'],'status',$post_content['status'],$username);
    }
    //UPDATE CHANGELOG BASED ON ORDER_REF change
    if (isset($post_content['order_ref']) && $post_content['order_ref'] != $equipment_data['order_ref'])
    {
        changelog($dbname,'equipment',$equipment_data['rowID'],'order_ref',$post_content['order_ref'],$username);
    }
    //UPDATE CHANGELOG BASED ON hw_version CHANGE
    if (isset($post_content['hw_version']) && $post_content['hw_version'] != $equipment_data['hw_version'])
    {
        changelog($dbname,'equipment',$equipment_data['rowID'],'hw_version',$post_content['hw_version'],$username);
    }
    //UPDATE CHANGELOG BASED ON sw_version CHANGE
    if (isset($post_content['sw_version']) && $post_content['sw_version'] != $equipment_data['sw_version'])
    {
        changelog($dbname,'equipment',$equipment_data['rowID'],'sw_version',$post_content['sw_version'],$username);
    }

    $post_content['accounthierarchy'] = $accounthierarchy;

    //CHECK for special permissions
    if (isAllowed('equipment_manage_edit',$profile,$permission,'U') === 0 && $owner_equipment === 0 ){
        $post_content['status'] = $equipment_data['status'];
        $post_content['serialnumber'] = $equipment_data['serialnumber'];
        $post_content['service_date'] = $equipment_data['service_date'];
        $post_content['warranty_date'] = $equipment_data['warranty_date'];
    } 
   
}
elseif ($command == 'insert'){
    $post_content['created'] = $date;
    $post_content['createdby'] = $username;
    $post_content['accounthierarchy'] = $accounthierarchy;
    $post_content['service_date'] = $date;
    $post_content['warranty_date'] = $date;   
}
else {
    //do nothing
}

//CREAT NEW ARRAY AND MAP TO CLAUSE
if(isset($post_content) && $post_content!=''){   
    foreach ($post_content as $key => $var){
        if ($key == 'submit' || $key == 'rowID' || str_contains($key, 'old_') || $key == 'salesid' || $key == 'soldto' || $key == 'shipto' || $key == 'location' || $key == 'section' || str_contains($key, 'productcode') || str_contains($key, 'productname')){
            //do nothing
        }
        else {
            $criterias[$key] = $var;
            $clause .= ' , '.$key.' = ?';
            $clause_insert .= ' , '.$key.'';
            $input_insert .= ', ?'; // ? for each insert item
            $execute_input[]= $var; // Build array for input
        }
    }
}

//CLEAN UP INPUT
$clause = substr($clause, 2); //Clean clause - remove first comma
$clause_insert = substr($clause_insert, 2); //Clean clause - remove first comma
$input_insert = substr($input_insert, 1); //Clean clause - remove first comma

//QUERY AND VERIFY ALLOWED
if ($command == 'update' && (isAllowed('equipment_manage',$profile,$permission,'U') === 1 || isAllowed('equipments_mass_update',$profile,$permission,'U') === 1 || $owner_equipment === 1)){
    $sql = 'UPDATE equipment SET '.$clause.' WHERE rowID = ? '.$whereclause.'';
    $execute_input[] = $id;
    $stmt = $pdo->prepare($sql);
    $stmt->execute($execute_input);
} 
elseif ($command == 'insert' && isAllowed('equipment_manage',$profile,$permission,'C') === 1){
    $sql = 'INSERT INTO equipment ('.$clause_insert.') VALUES ('.$input_insert.')';
    $stmt = $pdo->prepare($sql);
    $stmt->execute($execute_input);
}
elseif ($command == 'delete' && (isAllowed('equipment_manage',$profile,$permission,'D') === 1 || $owner_equipment === 1)){
    //delete equipment
    $stmt = $pdo->prepare('DELETE FROM equipment WHERE rowID = ? '.$whereclause.'');
    $stmt->execute([ $id ]);
    //delete history related to equipment 
    $stmt = $pdo->prepare('DELETE FROM equipment_history WHERE equipmentid = ?');
    $stmt->execute([ $id ]); 
    //Add deletion to changelog
    changelog($dbname,'equipment',$id,'Delete','Delete',$username);
} else
{
    //do nothing
}

?>