<?php
defined($security_key) or exit;

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

//CHECK IF PRODUCT ID IS SEND
if (isset($post_content['product_id']) && $post_content['product_id'] != ''){

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

    //IF PRODUCT IS OWNED THEN CRUD is ALLOWED
    if ($product_owner === 1 ){

        if(isAllowed('products_categories',$profile,$permission,'U') === 1 || isAllowed('products_categories',$profile,$permission,'C') === 1) {
            
            if (isset($post_content['categories']) && is_array($post_content['categories']) && count($post_content['categories']) > 0) {
                    $in  = str_repeat('?,', count($post_content['categories']) - 1) . '?';
                    $stmt = $pdo->prepare('DELETE FROM products_categories WHERE product_id = ? AND category_id NOT IN (' . $in . ')');
                    $stmt->execute(array_merge([$post_content['product_id'] ], $post_content['categories']));
                    
                    foreach ($post_content['categories'] as $cat) {
                        $stmt = $pdo->prepare('INSERT IGNORE INTO products_categories (product_id,category_id) VALUES (?,?)');
                        $stmt->execute([$post_content['product_id'], $cat ]);
                    }
            }
        } else {
            if(isAllowed('products_categories',$profile,$permission,'D') === 1){
                
            $stmt = $pdo->prepare('DELETE FROM products_categories WHERE product_id = ?');
            $stmt->execute([$post_content['product_id']]);

            changelog($dbname,'products_categories',$id,'Delete','Delete',$username);
            }
        }
    }
}