<?php
defined($security_key) or exit;

//------------------------------------------
// Products
//------------------------------------------
//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
$whereclause = '';

switch ($permission) {    
    case '4':
        $whereclause = '';
        break;
    case '3':
        $whereclause = '';
        break;  
    default:
        $condition = '__salesid___'.$partner->salesid.'___soldto___'.substr($partner->soldto, 0, strpos($partner->soldto, "-")).$soldto_search;
        $whereclause = ' AND accounthierarchy like "'.$condition.'"';
        break;
} 

//ENSURE PRODUCTROWID IS SEND
if (isset($post_content['productrowid']) && $post_content['productrowid'] != ''){

    //CHECK IF ALLOWED TO CRUD VERSIONS
    $sql = "SELECT * FROM products WHERE rowID = ? '.$whereclause.'";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$post_content['productrowid']]);
    $product_data = $stmt->fetch();
    $product_owner = ($product_data['rowID'])? 1 : 0;

    //IF PRODUCT IS OWNED THEN CRUD is ALLOWED
    if ($product_owner === 1 ){
        //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 ($command == 'insert'){

            if(isset($post_content['software'])){
                //CHECK FOR FILETYPE
                $version = $post_content['software'];
                $version_file_type = strtolower(substr($version, -4)); // filetype
                
                //CHECK IF FILETYPE IS ADDED
                if ($version_file_type[0] == '.'){
                    
                    //BASED ON FILE TYPE DO THE FOLLOWING
                    switch ($version_file_type) {
                        case '.hex':
                            //USE FULL NAME EXCLUDING 
                            $version = substr($version, 0, -4);
                        break;
                        
                        default:
                            if (($pos = strpos($version, "_")) !== FALSE) {
                                $version = substr($version, $pos+1);
                                $version = substr($version, 0, -4); //remove filetype
                            }  
                        break;
                    }
                }
                //SET CORRECT VERSION
                $post_content['version'] = $version;
            }

            if (($pos = strpos($post_content['software'], "_")) !== FALSE) {
                $version = substr($post_content['software'], $pos+1);
                $version = substr($version, 0, -4); //remove filetype
                $post_content['version'] = $version;
            }

            $post_content['latest'] = 1; //New software is always latest
            $post_content['created'] = $date;
            $post_content['createdby'] = $username;
        }

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

        //SET HW VERSION
        $hw_eq_version = (isset($criterias['hw_version']))? $criterias['hw_version']:'';

        //QUERY AND VERIFY ALLOWED
        if ($command == 'update' && isAllowed('products_software',$profile,$permission,'U') === 1){
            
            //REMOVE LATEST FLAG FROM OTHER WHEN SEND
            if ($criterias['latest'] == 1){
                $sql = 'UPDATE products_software SET latest = 0 WHERE productrowid = ? AND hw_version = ?';
                $stmt = $pdo->prepare($sql);
                $stmt->execute([$post_content['productrowid'], $hw_eq_version ]);
            }
            
            $sql = 'UPDATE products_software SET '.$clause.' WHERE rowID = ? '.$whereclause.'';
            $execute_input[] = $id;
            $stmt = $pdo->prepare($sql);
            $stmt->execute($execute_input);
        } 
        elseif ($command == 'insert' && isAllowed('products_software',$profile,$permission,'C') === 1){
             
            //REMOVE LATEST FLAG FROM OTHER
            $sql = 'UPDATE products_software SET latest = 0 WHERE productrowid = ? AND hw_version = ?';
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$post_content['productrowid'], $hw_eq_version]);
 
             //INSERT NEW ITEM
            $sql = 'INSERT INTO products_software ('.$clause_insert.') VALUES ('.$input_insert.')';
            $stmt = $pdo->prepare($sql);
            $stmt->execute($execute_input);
        }
        elseif ($command == 'delete' && isAllowed('products_software',$profile,$permission,'D') === 1){
            
            //GET FILENAME AND REMOVE FROM SERVER
            $sql = 'SELECT * FROM products_software WHERE rowID = ? '.$whereclause.'';
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$id]);
            //Get results
            $softwares = $stmt->fetchAll(PDO::FETCH_ASSOC);
     
            foreach ($softwares as $software){
                $software_file = dirname(__FILE__,4)."/firmware/".$software['software'];
                $file = glob($software_file, GLOB_BRACE); 
                if (!empty($file)){ 
                    unlink($software_file); 
                }
            }
            
            $stmt = $pdo->prepare('DELETE FROM products_software WHERE rowID = ? '.$whereclause.'');
            $stmt->execute([ $id ]); 

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