<?php
defined($security_key) or exit;

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

//CONTENT FROM API (POST)
$post_content = json_decode(decode_payload($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
$clause = '';
$clause_insert ='';
$input_insert = '';

//remove blanks from array
if (isset($post_content['servicetool'])){
    $post_content['servicetool'] = array_map('trim', $post_content['servicetool']);
    $post_content['servicetool'] = array_filter($post_content['servicetool'], 'strlen');
}
if (isset($post_content['assigned_users'])){
    $post_content['assigned_users'] = array_map('trim', $post_content['assigned_users']);
    $post_content['assigned_users'] = array_filter($post_content['assigned_users'], 'strlen');
}
if (isset($post_content['ignore_list'])){
    $post_content['ignore_list'] = array_map('trim', $post_content['ignore_list']);
    $post_content['ignore_list'] = array_filter($post_content['ignore_list'], 'strlen');
}

$post_content['updatedby'] = $username;

if ($id != ''){
    
    //DEFINE ACCOUNTHIERARCHY
    $stmt = $pdo->prepare('SELECT * FROM contracts WHERE rowID = ?');
    $stmt->execute([$id]);
    $contract_data = $stmt->fetch();
     
    $contract_old = json_decode($contract_data['accounthierarchy']);
    $salesid_new = (($post_content['salesid'] != '' && $post_content['salesid'] != $contract_old->salesid)? $post_content['salesid'] : $contract_old->salesid);
    $soldto_new = (($post_content['soldto'] != '' && $post_content['soldto'] != $contract_old->soldto)? $post_content['soldto'] : $contract_old->soldto);
    $shipto_new = (($post_content['shipto'] != '' && $post_content['shipto'] != $contract_old->shipto)? $post_content['shipto'] : $contract_old->shipto);
    $location_new = (($post_content['location'] != '' && $post_content['location'] != $contract_old->location)? $post_content['location'] : $contract_old->location);
    
    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
    );
    } 
    elseif ($permission == 3) {
        //ADMIN ONLY ARE ALLOWED TO CHANGE SOLD
        $account = array(
            "salesid"=>$contract_old->salesid,
            "soldto"=>$soldto_new,
            "shipto"=>$shipto_new,
            "location"=>$location_new
        );
    }
    else {
        $account = array(
            "salesid"=>$contract_old->salesid,
            "soldto"=>$contract_old->soldto,
            "shipto"=>$shipto_new,
            "location"=>$location_new
        );
    }

    //CHECK FOR CHANGES IN ASSIGNED_USERS
    if (isset($post_content['assigned_users'])){
        $assigned_users_current = json_decode($contract_data['assigned_users'],true);
        $assigned_users_new = $post_content['assigned_users'];

        // Find deleted items (items in current but not in new)
        $deletedItems = array_diff($assigned_users_current, $assigned_users_new);
        // Find added items (items in new but not in current)
        $addedItems = array_diff($assigned_users_new, $assigned_users_current);
        
        //When deleted items are found
        if (!empty($deletedItems)){            
            foreach ($deletedItems as $item){
            //CALL TO API FOR General information
            $api_url = '/v2/users/username='.$item;
            $responses = ioApi($api_url,'',$clientsecret);
                if (!empty($responses)){
                    $response = json_decode($responses,true);
                    
                    //If response is not null update the service flag of the user
                    if (count($response) != 0){
                        $id_removed_user = $response[0]['id'];
                        //Remove serviceflag from user
                        $sql = 'UPDATE users SET service = "", updatedby = ? WHERE id = ? ';
                        $stmt = $pdo->prepare($sql);
                        $stmt->execute([$username,$id_removed_user]); 
                    } 
                }
            }
        }
        
    }
}    
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']
        );
    } 
    elseif ($permission == 3){
        $account = array(
            "salesid"=>$partner->salesid,
            "soldto"=>$post_content['soldto'],
            "shipto"=>$post_content['shipto'],
            "location"=>$post_content['location']
        );
    }else {
        $account = array(
            "salesid"=>$partner->salesid,
            "soldto"=>$partner->soldto,
            "shipto"=>$post_content['shipto'],
            "location"=>$post_content['location']
        );
    }
}

// CREATE ACCOUNTHIERARCHY JSON FROM ACCOUNT ARRAY
$post_content['accounthierarchy'] = json_encode($account, JSON_UNESCAPED_UNICODE);

if ($command == 'insert' && !isset($post_content['delete'])){
    $post_content['created'] = $date;
    $post_content['createdby'] = $username;
}

//remove blanks from array
if (isset($post_content['servicetool'])){
    $post_content['servicetool'] = json_encode($post_content['servicetool'], JSON_UNESCAPED_UNICODE);
}
if (isset($post_content['ignore_list'])){
    $post_content['ignore_list'] = json_encode($post_content['ignore_list'], JSON_UNESCAPED_UNICODE);
    //ONLY ADMINS ARE ALLOWED TO UPDATE IGNORE LIST 
    if ($permission != 3 && $permission != 4){
        unset($post_content['ignore_list']);
    }
}
if (isset($post_content['assigned_users'])){
    //Check for all users in array if exist then update service or create
    foreach ($post_content['assigned_users'] as $user_assigned){
        //CALL TO API FOR General information
        $responses = ioApi('/v2/users/username='.$user_assigned,'',$clientsecret);
            if (!empty($responses)){
                $response = json_decode($responses,true);
                
                //If response is not null update the service flag of the user
                if (count($response) != 0){
                    $id_exist_user = $response[0]['id'];
                    $generate_service = bin2hex(random_bytes(25));
                    $sql = 'UPDATE users SET service = ? , updatedby = ? WHERE id = ? ';
                    $stmt = $pdo->prepare($sql);
                    if (isset($post_content['status']) && $post_content['status'] != 2){
                        //Add serviceflag from user
                        $stmt->execute([$generate_service,$username,$id_exist_user]);
                    }
                    else {
                        //Remove serviceflag from user when status is Closed
                        $stmt->execute(['',$id_exist_user]);
                    }
                } else {
                    //Decode the account structure of the contract and create user
                    $ah_array = json_decode($post_content['accounthierarchy'],true);
                    $data = json_encode(array("username" => $user_assigned, "email"=> $user_assigned,"view" => 2 ,"settings"=>"service","service"=> 1,"userkey"=> 1, "salesid" => $ah_array['salesid'], "soldto" => $ah_array['soldto'],"shipto" => $ah_array['shipto'],"location" => $ah_array['location']), JSON_UNESCAPED_UNICODE);
                    //call the API to create user
                    ioApi('/v2/users',$data,$clientsecret);
                }
            }
        }

    // UPDATE TO JSON
    $post_content['assigned_users'] = json_encode($post_content['assigned_users'], JSON_UNESCAPED_UNICODE);
}

//CREATE NEW ARRAY AND MAP TO CLAUSE
if(isset($post_content) && $post_content!=''){   
    foreach ($post_content as $key => $var){
        if ($key == 'submit' || $key == 'delete' || $key == 'rowID'|| $key == 'id' || str_contains($key, 'old_')|| $key == 'salesid' || $key == 'soldto' || $key == 'shipto' || $key == 'location'){
            //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' && !isset($post_content['delete']) && isAllowed('contract',$profile,$permission,'U') === 1){
    $sql = 'UPDATE contracts SET '.$clause.' WHERE rowID = ? '.$whereclause.'';
    $execute_input[] = $id;
    $stmt = $pdo->prepare($sql);
    $stmt->execute($execute_input);  

} 
elseif ($command == 'insert' && !isset($post_content['delete']) && isAllowed('contract',$profile,$permission,'C') === 1){    
        $sql = 'INSERT INTO contracts ('.$clause_insert.') VALUES ('.$input_insert.')';
        $stmt = $pdo->prepare($sql);
        $stmt->execute($execute_input);
}
elseif ($command == 'delete' && isAllowed('contract',$profile,$permission,'D') === 1){
    $stmt = $pdo->prepare('DELETE FROM contracts WHERE rowID = ? '.$whereclause.'');
    $stmt->execute([ $id ]); 

    //Add deletion to changelog
    changelog($dbname,'contracts',$id,'Delete','Delete',$username);
} else
{
    //do nothing
}

?>