<?php
defined($security_key) or exit;

//------------------------------------------
// Products
//------------------------------------------
//Connect to DB
$pdo = dbConnect($dbname);
$pdo2 = 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
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 = '';

if ($id != ''){
    //Define Query
    $stmt = $pdo->prepare('SELECT * FROM account WHERE rowID = ?');
    $stmt->execute([$id]);
    $account_data = $stmt->fetch();
    
    $accounthierarchy_old = json_decode($account_data['accounthierarchy']);
   
    $salesid_new = ((isset($post_content['salesid']) && $post_content['salesid'] != '' && $post_content['salesid']  != $accounthierarchy_old->salesid)? $post_content['salesid'] : $accounthierarchy_old->salesid);
    $soldto_new = ((isset($post_content['soldto']) && $post_content['soldto'] != '' && $post_content['soldto'] != $accounthierarchy_old->soldto)? $post_content['soldto'] : $accounthierarchy_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"=>$accounthierarchy_old->salesid,
            "soldto"=> $soldto_new
        );
    }
}    
else {
    //ID is empty => INSERT / NEW RECORD
    
    //GET PARTNERDETAILS FROM USER
     $sales_user = array(
        "salesid"=>$partner->salesid,
        "soldto"=>$partner->soldto
    );
    $salesID = json_encode($sales_user, JSON_UNESCAPED_UNICODE);
    
    //CHECK IF PARTNER-ID IS EMPTY THEN CHECK IF EXIST OR CREATE
    if (isset($post_content['soldto']) && $post_content['soldto'] ==''){

        //PARTNER ID IS EMPTY => SEARCH IF EXIST
        $stmt = $pdo->prepare('SELECT * FROM partner WHERE partnername = ? AND partnertype = ?');
        $stmt->execute([$post_content['accountdetails']['billcompany'],$partnertype2]);
        $partner_exist = $stmt->fetch();

        if($partner_exist){
            //PARTNER EXIST -> USE IT
            $post_content['soldto'] = $partner_exist['partnerID'].'-'.$partner_exist['partnername'];
        }
        else{
            //PARTNER DOES NOT EXIST -> CREATE IT
            //INSERT NEW PARTNER
            $sql = 'INSERT INTO partner (partnertype, partnername, partnernotes, salesID, createdby) VALUES (?,?,?,?,?)';
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$partnertype2,$post_content['accountdetails']['billcompany'],'created from account',$salesID,$username]);
            $rowID = $pdo->lastInsertId();
            $post_content['soldto'] = $rowID.'-'.$post_content['accountdetails']['billcompany'];
        }
    }
    //CHECK IF PARTNER-ID IS NOT EMPTY THEN USE IT
    $account = array(
        "salesid"=>$post_content['salesid'],
        "soldto"=>$post_content['soldto']
    );

    //CHECK IF COMMUNICATION USER EXIST FOR THIS PARTNER
    if (isset($post_content['accountdetails']['billemail']) && $post_content['accountdetails']['billemail'] !=''){
        //Check if communication record exist
        $rowID = getrowID($dbname,'rowID','communication','partnerID ="'.$post_content['soldto'].'" and email = "'.$post_content['accountdetails']['billemail'].'"');

        if ($rowID){
            //communication record exist
        }
        else
        {
            //communication record does not exist ->create
            $sql = 'INSERT INTO communication (status,partnerID,email,type_1,type_2,type_3,createdby,salesID,coms_type) VALUES (?,?,?,?,?,?,?,?,?)';
            $stmt = $pdo2->prepare($sql);
            $stmt->execute(['1',$post_content['soldto'],$post_content['accountdetails']['billemail'],'1','1','1',$username,$salesID,'1']);
        }
    }

}

//Create JSONs
$accounthierarchy = json_encode($account, JSON_UNESCAPED_UNICODE);
$accountdetails = json_encode($post_content['accountdetails'], JSON_UNESCAPED_UNICODE);

//ADD STANDARD PARAMETERS TO ARRAY BASED ON INSERT OR UPDATE
if ($command == 'update' && !isset($post_content['delete'])){
    $post_content['rowID'] = $id;
    $post_content['accounthierarchy'] = $accounthierarchy;
    $post_content['accountdetails'] = $accountdetails;
}
elseif ($command == 'insert' && !isset($post_content['delete'])){
    $post_content['created'] = $date;
    $post_content['createdby'] = $username;
    $post_content['accounthierarchy'] = $accounthierarchy;
    $post_content['accountdetails'] = $accountdetails;
}
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 == 'accountID'){
            //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('account',$profile,$permission,'U') === 1){
    $sql = 'UPDATE account SET '.$clause.' WHERE rowID = ? '.$whereclause.'';
    $execute_input[] = $id;
    $stmt = $pdo->prepare($sql);
    $stmt->execute($execute_input);  
} 
elseif ($command == 'insert' && !isset($post_content['delete']) && isAllowed('account',$profile,$permission,'C') === 1){    
        $sql = 'INSERT INTO account ('.$clause_insert.') VALUES ('.$input_insert.')';
        $stmt = $pdo->prepare($sql);
        $stmt->execute($execute_input);
}
elseif ($command == 'delete' && isAllowed('account',$profile,$permission,'D') === 1){
    $stmt = $pdo->prepare('DELETE FROM account WHERE rowID = ? '.$whereclause.'');
    $stmt->execute([ $id ]); 

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

?>