<?php
defined($security_key) or exit;

//------------------------------------------
// Invoice
//------------------------------------------
//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
list($whereclause,$condition) = getWhereclause('',$permission,$partner,'');


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

//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'){

}
elseif ($command == 'insert' && (isset($post_content['txn_id']) && $post_content['txn_id'] != '')){

    //GET RELATED TRANSACTION DETAILS
    $sql = 'SELECT * FROM transactions WHERE id = ? ';
    $stmt = $pdo->prepare($sql);
    //Excute Query
    $stmt->execute([$post_content['txn_id']]);
    //Get results
    if ($messages = $stmt->fetch(PDO::FETCH_ASSOC)) {
         //ADD ADDITIONAL POST CONTENT
        $post_content['payment_amount'] = $messages['payment_amount'];
        $post_content['shipping_amount'] = $messages['shipping_amount'];
        $post_content['discount_amount'] = $messages['discount_amount'];
        $post_content['tax_amount'] = $messages['tax_amount'];
        $post_content['payment_status'] = $messages['payment_status'];
        $post_content['accounthierarchy'] = $partner_product;
    }  
}
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'){
            //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('invoice',$profile,$permission,'U') === 1){
    $sql = 'UPDATE invoice SET '.$clause.' WHERE id = ? '.$whereclause.'';
    $execute_input[] = $id;
    $stmt = $pdo->prepare($sql);
    $stmt->execute($execute_input);
} 
elseif ($command == 'insert' && isAllowed('invoice',$profile,$permission,'C') === 1){
    $sql = 'INSERT INTO invoice ('.$clause_insert.') VALUES ('.$input_insert.')';
    $stmt = $pdo->prepare($sql);
    $stmt->execute($execute_input);

    //GET LAST_ID
    $last_id = $pdo->lastInsertId();
    $messages = json_encode(array('invoice_id'=> $last_id), JSON_UNESCAPED_UNICODE);
    //Send results
    echo $messages;
}
elseif ($command == 'delete' && isAllowed('invoice',$profile,$permission,'D') === 1){
    $stmt = $pdo->prepare('DELETE FROM invoice WHERE id = ? '.$whereclause.'');
    $stmt->execute([ $id ]); 

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

?>