<?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
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 = '';

//BUILD UP PARTNERHIERARCHY FROM USER
$partner_product = json_encode(array("salesid"=>$partner->salesid,"soldto"=>$partner->soldto), JSON_UNESCAPED_UNICODE);

//ADD STANDARD PARAMETERS TO ARRAY BASED ON INSERT OR UPDATE
if ($command == 'update'){
    $post_content['updated'] = $date;
    $post_content['updatedby'] = $username ;

}
elseif ($command == 'insert'){
    $post_content['created'] = $date;
    $post_content['createdby'] = $username;
    $post_content['accounthierarchy'] = $partner_product;

}
else {
    //do nothing
}

//CHECK IF CATEGORIES ARE SEND AND UPDATE 
if (isset($post_content['categories'])){

    if ($command != 'insert'){
        //CHANGE OR DELETE SO PRODUCT_ID IS AVAILABLE IN CALL
        $api_url = '/v2/products_categories/';
        $data = json_encode(array("categories" => $post_content['categories'], "product_id" => $id), JSON_UNESCAPED_UNICODE);
        $responses = ioApiv2($api_url,$data,$clientsecret);
    } else {
        //INSERT Product ROWID NOT AVAILABLE YET. store $post_content['categories'] in different variable.
        $categories = $post_content['categories'];
    }

    //REMOVE CATERGORIES FROM POST_CONTENT ARRAY
    unset($post_content['categories']);
}

//CREATe NEW ARRAY AND MAP TO CLAUSE
if(isset($post_content) && $post_content!=''){   
    foreach ($post_content as $key => $var){
        if ($key == 'submit' || $key == 'rowID'){
            //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('products',$profile,$permission,'U') === 1){
    $sql = 'UPDATE products SET '.$clause.' WHERE rowID = ? '.$whereclause.'';
    $execute_input[] = $id;
    $stmt = $pdo->prepare($sql);
    $stmt->execute($execute_input);
} 
elseif ($command == 'insert' && isAllowed('products',$profile,$permission,'C') === 1){
    $sql = 'INSERT INTO products ('.$clause_insert.') VALUES ('.$input_insert.')';
    $stmt = $pdo->prepare($sql);
    $stmt->execute($execute_input);

    $api_url = '/v2/products_categories/';
    $data = json_encode(array("categories" => $categories, "product_id" => $id), JSON_UNESCAPED_UNICODE);
    $responses = ioApiv2($api_url,$data,$clientsecret);

}
elseif ($command == 'delete' && isAllowed('products',$profile,$permission,'D') === 1){
    $stmt = $pdo->prepare('DELETE FROM products WHERE rowID = ? '.$whereclause.'');
    $stmt->execute([ $id ]); 

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

?>