<?php
defined($security_key) or exit;

//------------------------------------------
// Transactions
//------------------------------------------
//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,'');


//WEBSHOP UPDATE CAN SEND TXN_ID ONLY
if (isset($post_content['txn_id']) && $post_content['txn_id'] != '' && !isset($post_content['id'])){
    
    //CHECK IF TXN_ID is send and valid 
    $sql = 'SELECT * FROM transactions WHERE txn_id = ?';
    $stmt = $pdo->prepare($sql);
    //Excute Query
    $stmt->execute([$post_content['txn_id']]);
    
    //Get results
    if ($messages = $stmt->fetch(PDO::FETCH_ASSOC)){
        //UPDATE ID TO TXN_ID RELATED ID
        $post_content['id'] = $messages['id'];
        unset($post_content['txn_id']);
    }
}

//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

//CHECK FOR ERRORS
$errors = validateTransactionData($post_content);

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

    //CHECK IF PAYMENT STATUS is PAID (1)
    if(isset($post_content['payment_status']) && $post_content['payment_status'] == 1){
     
        //check if GIFTCARD ID IS PROVIDED AND NOT EMPTY
        if(isset($post_content['giftcard_categoryID']) && $post_content['giftcard_categoryID'] != ''){
            
            //CHECK FOR GIFTCARDS IN ORDER AND CREATE WHEN AVAILABLE AND NOT CREATED YET
            createGiftCart($pdo, $post_content['id'], $post_content['giftcard_categoryID'],$partner_product);

            //remove giftcard_categoryID from $post_content array
            unset($post_content['giftcard_categoryID']);
        }

        if(isset($post_content['giftcard_categoryID'])){
            //remove giftcard_categoryID from $post_content array
            unset($post_content['giftcard_categoryID']);
        }
 
    }

}
elseif ($command == 'insert'){
    $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('transactions',$profile,$permission,'U') === 1){
    $sql = 'UPDATE transactions SET '.$clause.' WHERE id = ? '.$whereclause.'';
    $execute_input[] = $id;
    $stmt = $pdo->prepare($sql);
    $stmt->execute($execute_input);
    
    //RETURN UPDATED ID
    $messages = json_encode(array('transaction_id'=> $id), JSON_UNESCAPED_UNICODE);
    //Send results
    echo $messages;
} 
elseif ($command == 'insert' && empty($errors) && isAllowed('transactions',$profile,$permission,'C') === 1){
    $sql = 'INSERT INTO transactions ('.$clause_insert.') VALUES ('.$input_insert.')';
    $stmt = $pdo->prepare($sql);
    $stmt->execute($execute_input);
}
elseif ($command == 'delete' && isAllowed('transactions',$profile,$permission,'D') === 1){
    $stmt = $pdo->prepare('DELETE FROM transactions WHERE id = ? '.$whereclause.'');
    $stmt->execute([ $id ]); 

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

?>