/**
 * Delete product or all products
 * 
 * @param int $product_id
 * @param bool $update_categories - flag to update categories statistic
 * @param bool $delete_all - flag to delete all products, $product_id ignored
 * 
 * @return bool
 */
function cw_delete_product($product_id = 0, $update_categories = true, $delete_all = false)
{
    global $tables, $addons;
    cw_load('category', 'image', 'sections', 'attributes', 'tags');
    if ($delete_all === true) {
        $tables_to_clear = array('products', 'products_stats', 'products_prices', 'products_warehouses_amount', 'featured_products', 'products', 'attributes_values', 'products_categories', 'products_votes', 'products_reviews', 'products_lng', 'download_keys', 'discount_coupons', 'products_bookmarks', 'products_memberships');
        foreach ($tables_to_clear as $table) {
            db_query("delete from " . $tables[$table]);
        }
        cw_delete_sections($product_id);
        cw_image_delete('products_images_thumb');
        cw_image_delete('products_images_det');
        cw_image_delete('products_detailed_images');
        /*
        # kornev, TOFIX
        * TODO: move to addon hook
                # magnifier addon
                if (cw_query_first_cell("SELECT addon_name FROM $tables[addons] WHERE addon_name='magnifier'")) {
                    if (!isset($tables['magnifier_images']))
                        include_once $app_main_dir.'/addons/magnifier/config.php';
        
                    db_query("DELETE FROM $tables[magnifier_images]");
                    $dir_z = cw_image_dir("Z");
                    if (is_dir($dir_z) && file_exists($dir_z))
                        cw_rm_dir($dir_z);
                }
        */
        if ($update_categories) {
            $res = db_query("SELECT category_id FROM {$tables['categories']}");
            cw_recalc_subcat_count($res);
        }
        db_query("DELETE FROM {$tables['products_flat']}");
        // TODO: move to addon
        if ($addons['faq']) {
            cw_load('faq');
            cw_faq_delete_products();
        }
        return true;
    }
    $product_categories = cw_query_column("select {$tables['categories_parents']}.parent_id from {$tables['categories_parents']}, {$tables['products_categories']} where {$tables['categories_parents']}.category_id = {$tables['products_categories']}.category_id and {$tables['products_categories']}.product_id='{$product_id}' group by {$tables['categories_parents']}.parent_id");
    // TODO: move to addon
    if ($addons['faq']) {
        cw_load('faq');
        cw_faq_delete_product($product_id);
    }
    cw_delete_section_product($product_id);
    db_query("DELETE FROM {$tables['products_stats']} WHERE product_id='{$product_id}'");
    db_query("DELETE FROM {$tables['products_prices']} WHERE product_id='{$product_id}'");
    db_query("DELETE FROM {$tables['products_warehouses_amount']} WHERE product_id='{$product_id}'");
    db_query("DELETE FROM {$tables['featured_products']} WHERE product_id='{$product_id}'");
    db_query("DELETE FROM {$tables['products_shipping']} WHERE product_id='{$product_id}'");
    cw_call('cw_attributes_cleanup', array($product_id, 'P'));
    db_query("DELETE FROM {$tables['products_memberships']} WHERE product_id='{$product_id}'");
    cw_image_delete($product_id, 'products_images_thumb');
    cw_image_delete($product_id, 'products_images_det');
    Product\delete($product_id);
    // associate your event handlers with on_product_delete event triggered in this method
    # Product options addon
    /*
    # kornev, TOFIX
    * TODO: move to addon hook
        # magnifier addon
        if (cw_query_first_cell("SELECT addon_name FROM $tables[addons] WHERE addon_name='magnifier'")) {
            if (!isset($tables['magnifier_images'])) {
                include_once $app_main_dir."/addons/magnifier/config.php";
            }
    
            db_query("DELETE FROM $tables[magnifier_images] WHERE id = '$product_id'");
            $dir_z = cw_image_dir("Z").DIRECTORY_SEPARATOR.$product_id;
            if (is_dir($dir_z) && file_exists($dir_z))
                cw_rm_dir($dir_z);
        }
    */
    db_query("DELETE FROM {$tables['products_votes']} WHERE product_id='{$product_id}'");
    db_query("DELETE FROM {$tables['products_reviews']} WHERE product_id='{$product_id}'");
    db_query("DELETE FROM {$tables['products_lng']} WHERE product_id='{$product_id}'");
    db_query("DELETE FROM {$tables['download_keys']} WHERE product_id='{$product_id}'");
    db_query("DELETE FROM {$tables['discount_coupons']} WHERE product_id='{$product_id}'");
    db_query("DELETE FROM {$tables['products_bookmarks']} WHERE product_id='{$product_id}'");
    db_query("DELETE FROM {$tables['products_system_info']} WHERE product_id='{$product_id}'");
    #
    # Update product count for categories
    #
    if ($update_categories && !empty($product_categories)) {
        cw_recalc_subcat_count($product_categories);
    }
    db_query("DELETE FROM {$tables['products_flat']} WHERE product_id = '{$product_id}'");
    cw_tags_clear_product_tags($product_id);
    return true;
}
     cw_func_call('cw_items_attribute_classes_save', array('item_id' => $product_id, 'attribute_class_ids' => $product_data['attribute_class_ids'], 'item_type' => 'P'));
     # kornev, it have to be product_data here - because we change the attributes in the error_check function
     cw_call('cw_attributes_save', array('item_id' => $product_id, 'item_type' => 'P', 'attributes' => $product_data['attributes'], 'language' => $edited_language, array('update_posted_only' => true, 'is_default' => false)));
     cw_attributes_group_update($ge_id, $product_id, 'P', $fields);
     cw_func_call('cw_product_build_flat', array('product_id' => $product_id));
     cw_group_edit_end($product_id);
     cw_product_update_system_info($product_id, array('supplier_customer_id' => $product_data['supplier']));
     cw_group_edit_copy_system_info($product_id, array('supplier_customer_id' => $product_data['supplier']));
     cw_warehouse_recalculate($product_id);
     cw_product_filter_recalculate_price_ranges();
     // tags
     if (!empty($product_data['tags'])) {
         $tags = explode(',', $product_data['tags']);
         cw_tags_set_product_tags($tags, $product_id);
     } else {
         cw_tags_clear_product_tags($product_id);
     }
 } else {
     cw_add_top_message($fillerror, 'E');
     $product_modified_data = $product_data;
     $product_modified_data['product_id'] = $product_id;
     cw_core_process_date_fields($product_modified_data, null, array('' => array('membership_ids', 'status')));
     if ($file_upload_data['products_images_thumb']) {
         $file_upload_data['products_images_thumb']['is_redirect'] = false;
         $product_modified_data['image_thumb'] = $file_upload_data['products_images_thumb'];
     }
     if ($file_upload_data['products_images_det']) {
         $file_upload_data['products_images_det']['is_redirect'] = false;
         $product_modified_data['image_det'] = $file_upload_data['products_images_det'];
     }
 }