<?php
defined($security_key) or exit;

//------------------------------------------
// Products
//------------------------------------------
//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 to check if data is owned by user
list($whereclause,$condition) = getWhereclauselvl2('partners',$permission,$partner,'');

//SET PARAMETERS FOR QUERY
$id = $post_content['partnerID'] ?? ''; //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 = '';

if ($id != ''){
    //Define Query
    $stmt = $pdo->prepare('SELECT * FROM partner WHERE partnerID = ?');
    $stmt->execute([$id]);
    $partner_data = $stmt->fetch();
    
    $partnername_old = $partner_data['partnerID'].'-'.$partner_data['partnername'];
    $partnername_new = $partner_data['partnerID'].'-'.$post_content['partnername'];
    
    $partnerhierarchy_old = json_decode($partner_data['salesID']);

    $salesid_new = (($post_content['salesid'] != '' && $post_content['salesid'] != $partnerhierarchy_old->salesid)? $post_content['salesid'] : $partnerhierarchy_old->salesid);
    $soldto_new = (($post_content['soldto'] != '' && $post_content['soldto'] != $partnerhierarchy_old->soldto)? $post_content['soldto'] : $partnerhierarchy_old->soldto);
    
    if ($permission == 3 || $permission == 4){
        //ADMIN ONLY ARE ALLOWED TO CHANGE SALES AND SOLD
        $account = array(
            "salesid"=>$salesid_new,
            "soldto"=>$soldto_new
        );
    } else {
        $account = array(
            "salesid"=>$partner->salesid,
            "soldto"=>$partner->soldto
        );
    }
}    
else {
    //ID is empty => INSERT / NEW RECORD
    if ($permission == 3 || $permission == 4){
        //ADMIN ONLY ARE ALLOWED TO CHANGE SALES AND SOLD
        $account = array(
            "salesid"=>$partner->salesid,
            "soldto"=>$post_content['soldto']
        );
    } else {
        $account = array(
            "salesid"=>$partner->salesid,
            "soldto"=>$partner->soldto
        );
    }
   
}
$accounthierarchy = json_encode($account, JSON_UNESCAPED_UNICODE);

//ADD STANDARD PARAMETERS TO ARRAY BASED ON INSERT OR UPDATE
if ($command == 'update' && !isset($post_content['delete'])){
    $post_content['partnerID'] = $id;
    $post_content['salesID'] = $accounthierarchy;
}
elseif ($command == 'insert' && !isset($post_content['delete'])){
    $post_content['created'] = $date;
    $post_content['createdby'] = $username;
    $post_content['salesID'] = $accounthierarchy;
}
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 == 'delete' || $key == 'rowID'|| $key == 'id' || str_contains($key, 'old_')|| $key == 'salesid' || $key == 'soldto'|| $key == 'partnerID'){
            //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('partner',$profile,$permission,'U') === 1){
    $sql = 'UPDATE partner SET '.$clause.' WHERE partnerID = ? '.$whereclause.'';
    $execute_input[] = $id;
    $stmt = $pdo->prepare($sql);
    $stmt->execute($execute_input);

    //Update the partnername in all tables
    if ($partnername_new != $partnername_old){
    $sql_like = '%'.$partnername_old.'%';
    $sql1= 'UPDATE equipment SET accounthierarchy = REPLACE(accounthierarchy, ? , ?) WHERE accounthierarchy LIKE ?';
    $sql2= 'UPDATE communication SET partnerID = REPLACE(partnerID, ? , ?) WHERE partnerID LIKE ?';
    $sql3= 'UPDATE contracts SET accountID = REPLACE(accountID, ? , ?) WHERE accountID LIKE ?';
    $sql4= 'UPDATE orders SET accounthierarchy = REPLACE(accounthierarchy, ? , ?) WHERE accounthierarchy LIKE ?';
    $sql5= 'UPDATE products SET accounthierarchy = REPLACE(accounthierarchy, ? , ?) WHERE accounthierarchy LIKE ?';
    $sql_users = 'UPDATE users SET partnerhierarchy = REPLACE(partnerhierarchy, ? , ?) WHERE partnerhierarchy LIKE ?';
    $sql_partner = 'UPDATE partner SET salesID = REPLACE(salesID, ? , ?) WHERE salesID LIKE ?';
    $sql_account = 'UPDATE account SET accounthierarchy = REPLACE(accounthierarchy, ? , ?) WHERE accounthierarchy LIKE ?';

    //SQL_users
    $stmt = $pdo->prepare($sql_users);
    $stmt->execute([$partnername_old,$partnername_new, $sql_like]);
    //SQL_partners
    $stmt = $pdo->prepare($sql_partner);
    $stmt->execute([$partnername_old,$partnername_new, $sql_like]);
    //SQL_account
    $stmt = $pdo->prepare($sql_account);
    $stmt->execute([$partnername_old,$partnername_new, $sql_like]);
     
    $pdo = dbConnect($dbname);
    //SQL1
    $stmt = $pdo->prepare($sql1);
    $stmt->execute([$partnername_old,$partnername_new, $sql_like]);
    //SQL2
    $stmt = $pdo->prepare($sql2);
    $stmt->execute([$partnername_old,$partnername_new, $sql_like]);
    //SQL3
    $stmt = $pdo->prepare($sql3);
    $stmt->execute([$partnername_old,$partnername_new, $sql_like]);
    //SQL4
    $stmt = $pdo->prepare($sql4);
    $stmt->execute([$partnername_old,$partnername_new, $sql_like]);
    //SQL5
    $stmt = $pdo->prepare($sql5);
    $stmt->execute([$partnername_old,$partnername_new, $sql_like]);
    }
} 
elseif ($command == 'insert' && !isset($post_content['delete']) && isAllowed('partner',$profile,$permission,'C') === 1){
    
    //check if partner exists
    $stmt = $pdo->prepare('SELECT * FROM partner WHERE partnername = ? AND partnertype = ?');
    $stmt->execute([$post_content['partnername'],$post_content['partnertype']]);
    $partner_exist = $stmt->fetch();

    $exists = (isset($partner_exist['partnername']))? 1 : 0;

    if($exists == 0 ){
        $sql = 'INSERT INTO partner ('.$clause_insert.') VALUES ('.$input_insert.')';
        $stmt = $pdo->prepare($sql);
        $stmt->execute($execute_input);
    }
}
elseif ($command == 'delete' && isAllowed('partner',$profile,$permission,'D') === 1){
    $stmt = $pdo->prepare('DELETE FROM partner WHERE partnerID = ? '.$whereclause.'');
    $stmt->execute([ $id ]); 

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

?>