<?php
/*
* Plugin-Name: Product Designer App
* Plugin-URI: https://productdesignerapp.com
* Author: productdesignerapp
* Backend API
*/

if (!defined('ABSPATH'))
{
    exit;
}

/*
* get Refresh token
*/
add_action('wp_ajax_pdapp-refresh-token', 'pdapp_refresh_new_token');
if(!function_exists('pdapp_refresh_new_token'))
{
    function pdapp_refresh_new_token()
    {
        $token = pdapp_refresh_token();
        pdapp_response(0, "", ["token"=>$token]);
    }
}

/*
* Setting
*/
add_action('wp_ajax_pdapp-load-setting', 'pdapp_load_setting');
if(!function_exists('pdapp_load_setting'))
{
    function pdapp_load_setting()
    {
        if(!current_user_can(PDAPP_CAP_ACCESS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $systems = [];
        if(pdapp_get('translateTo') != '')
        {
            $systems['admin'] = pdapp_get_lang_by_code(pdapp_get('translateTo'), 'admin');
            $systems['front'] = pdapp_get_lang_by_code(pdapp_get('translateTo'), 'front');
            $systems['system'] = pdapp_get_lang_by_code(pdapp_get('translateTo'), 'system');
            pdapp_response(0, '', $systems);
        }

        if(pdapp_get('langCode') == 1)
        {
            $systems['langCode'] = pdapp_lang_code();
        }

        if(pdapp_get('listLangs') == 1)
        {
            $systems['listLangs'] = pdapp_get_lang_available();
        }

        if(pdapp_get('langs') == 1)
        {
            $systems['langs'] = pdapp_languages('admin');
        }

        if(pdapp_get('printings') == 1)
        {
            $systems['printings'] = pdapp_get_prints();
        }

        if(pdapp_get('artFolder') == 1)
        {
            $systems['folders'] = pdapp_get_art_folders();
        }

        if(pdapp_get('tempFolder') == 1)
        {
            $systems['folders'] = pdapp_get_template_folders();
        }

        if(pdapp_get('fontsize') == 1)
        {
            $systems['fontsize'] = pdapp_get_font_size();
        }

        if(pdapp_get('type') == 'folder')
        {
            pdapp_response(0, '', $systems['folders']);
        }

        if(pdapp_get('menus') == 1)
        {
            $systems['menus'] = pdapp_get_menus();
        }

        if(pdapp_get('listPrints') == 1)
        {
            $systems['listPrints'] = pdapp_print_types();
        }

        if(pdapp_get('newOrders') == 1)
        {
            $systems['newOrders'] = pdapp_new_orders();
        }

        if(pdapp_get('newQuotes') == 1)
        {
            $systems['newQuotes'] = pdapp_new_quotes();
        }
        
        if(pdapp_get('settings') == 1)
        {
            $systems['settings'] = pdapp_get_settings(true, true, false, false, false, false);
        }

        pdapp_response(0, '', $systems);
    }
}

/*
* list Dashboard Info
*/
add_action('wp_ajax_pdapp-dashboards', 'pdapp_dashboards');
if(!function_exists('pdapp_dashboards'))
{
    function pdapp_dashboards()
    {
        if(!current_user_can(PDAPP_CAP_ACCESS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $dashboard = [];
        $dashboard['totals'] = pdapp_get_total_info();
        $dashboard['require'] = pdapp_get_requirements();
        
        pdapp_response(0, '', $dashboard);
    }
}

/*
* list Dashboard Chart
*/
add_action('wp_ajax_pdapp-dashboard-charts', 'pdapp_dashboard_charts');
if(!function_exists('pdapp_dashboard_charts'))
{
    function pdapp_dashboard_charts()
    {
        if(!current_user_can(PDAPP_CAP_ACCESS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }
        $type = pdapp_get('type');
        $type = $type != '' ? $type : 'month';

        $chart = pdapp_get_chart_orders($type);
        
        pdapp_response(0, '', $chart);
    }
}

/*
* update purchased code
*/
add_action('wp_ajax_pdapp-dashboard-purchased', 'pdapp_dashboard_purchased');
if(!function_exists('pdapp_dashboard_purchased'))
{
    function pdapp_dashboard_purchased()
    {
        if (!pdapp_check_token(true))
        {
            pdapp_response(-1, pdapp_lang('token_error', 'system'));
        }
        if(!current_user_can(PDAPP_CAP_ACCESS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $purchased = pdapp_post('purchased', 'key');
        if($purchased)
        {
            $key = pdapp_get_cache('settings', 'key');
            if(!$key)
            {
                global $wpdb;
                $res = $wpdb->get_row($wpdb->prepare("SELECT * FROM %i WHERE `type`='k'", PDAPP_DB_SETTINGS), ARRAY_A);
                if(isset($res['values']))
                {
                    $key = $res['values'];
                    pdapp_set_cache('settings', 'key', $key);
                }
            }
            
            if(pdapp_update_db(PDAPP_DB_SETTINGS, ["values"=>$purchased], ["type"=>"k"], ["%s"], ["%s"]))
            {
                pdapp_set_cache('settings', 'key', $purchased);
            }
            pdapp_response(0, '');
        }

        pdapp_response(1, pdapp_lang('msg.update_error', 'admin'));
    }
}

/*
* list orders
*/
add_action('wp_ajax_pdapp-orders', 'pdapp_orders');
if(!function_exists('pdapp_orders'))
{
    function pdapp_orders()
    {
        if(!current_user_can(PDAPP_CAP_ORDERS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $orders = pdapp_get_cache('orders', 'lists');
        if(!$orders)
        {
            $orders = [];
            global $wpdb;
            $res = $wpdb->get_results($wpdb->prepare("SELECT * FROM %i WHERE `type`='o' ORDER BY `id` DESC", PDAPP_DB_ORDERS), ARRAY_A);
            foreach($res as $val)
            {
                $orders[] = ["id"=>$val['id'], "oid"=>$val['oid'], "status"=>$val['status'], "thumb"=>json_decode($val['thumb'], true), "created"=>$val['created']];
            }
            pdapp_set_cache('orders', 'lists', $orders);
        }
        
        pdapp_response(0, '', $orders);
    }
}

/*
* get order
*/
add_action('wp_ajax_pdapp-order', 'pdapp_order');
if(!function_exists('pdapp_order'))
{
    function pdapp_order()
    {
        if(!current_user_can(PDAPP_CAP_ORDERS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $orderID = (int) pdapp_get('id');
        if($orderID == 0)
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }

        $orders = pdapp_get_cache('orders', 'order-'. $orderID);
        if(!$orders)
        {
            $orders = [];
            global $wpdb;
            $res = $wpdb->get_results($wpdb->prepare("SELECT * FROM %i WHERE `oid`=%d", [PDAPP_DB_ORDER_DETAIL, $orderID]), ARRAY_A);
            foreach($res as $row)
            {
                $orders[] = ["id"=>$row['id'], "oid"=>$row['oid'], "did"=>$row['did'], "product"=>json_decode($row['product'], true), "price"=>$row['price'], "folder"=>$row['folder'], "qty"=>$row['qty'], "print"=>json_decode($row['print'], true), "options"=>json_decode($row['options'], true), "file"=>json_decode($row['file'], true), "team"=>json_decode($row['team'], true), "thumb"=>json_decode($row['thumb'], true), "note"=>$row['note']];
            }

            pdapp_set_cache('orders', 'order-'. $orderID, $orders);
        }
        
        foreach($orders as $key=>$order)
        {
            $designs = [];
            $files = $order['file'];
            foreach($files as $file)
            {
                $designs[] = [
                    "svg"=>'orders/' .$order['folder']. '/print/' .$file. '-' .PDAPP_PREFIX. 'design.pda',
                    "png"=>""
                ];
            }

            $orders[$key]["designs"] = $designs;
            $orders[$key]["uploads"] = pdapp_files_folder(PDAPP_UPLOAD_DIR .'orders/' .$order['folder']. '/upload');
        }

        pdapp_opened_order('order', $orderID);
        
        pdapp_response(0, '', $orders);
    }
}

/*
* remove Order
*/
add_action('wp_ajax_pdapp-remove-order', 'pdapp_remove_order_action');
if(!function_exists('pdapp_remove_order_action'))
{
    function pdapp_remove_order_action()
    {
        if (!pdapp_check_token(true))
        {
            pdapp_response(-1, pdapp_lang('token_error', 'system'));
        }
        if(!current_user_can(PDAPP_CAP_ORDERS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $id = (int) pdapp_post('id', 'key', 0);
        if($id != 0)
        {
            pdapp_remove_order($id);
            pdapp_response(0, pdapp_lang('msg.remove_success', 'admin'));
        }

        pdapp_response(1, pdapp_lang('msg.remove_error', 'admin'));
    }
}

/*
* get download
*/
add_action('wp_ajax_pdapp-file-download', 'pdapp_file_download');
if(!function_exists('pdapp_file_download'))
{
    function pdapp_file_download()
    {
        if (!pdapp_check_token(true))
        {
            pdapp_response(-1, pdapp_lang('token_error', 'system'));
        }
        if(!current_user_can(PDAPP_CAP_ORDERS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }
        
        $file = pdapp_post('file', 'text');
        if(!$file)
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }

        $file = PDAPP_UPLOAD_DIR . $file;
        
        if(file_exists($file))
        {
            $svgData = pdapp_read_file($file);
            if($svgData && $svgData != '')
            {
                if(strpos($svgData, '<svg') !== false)
                {
                    $svgData = 'data:image/svg+xml;base64,' . base64_encode($svgData);
                }
                pdapp_response(0, '', $svgData);
            }
        }
        
        pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
    }
}

/*
* Download 300DPI png
*/
add_action('wp_ajax_pdapp-download-png', 'pdapp_download_png');
if(!function_exists('pdapp_download_png'))
{
    function pdapp_download_png()
    {
        if (!pdapp_check_token(true))
        {
            pdapp_response(-1, pdapp_lang('token_error', 'system'));
        }
        if(!current_user_can(PDAPP_CAP_ORDERS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $imgData = pdapp_post('imgData', 'text');
        if(!$imgData || strpos($imgData, 'base64') === false)
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }
        if(strpos($imgData, 'base64') !== false)
        {
            $imgs = explode(';base64,', $imgData);
            if(isset($imgs[1]))
            {
                $imgData = base64_decode($imgs[1]);
            }
        }

        $convert = round(300/0.0254);
        if (extension_loaded('gd') && function_exists('imagesetresolution'))
        {
            $image = imagecreatefromstring($imgData);
            imagesetresolution($image, $convert, $convert);
            
            ob_start();
            imagepng($image);
            $newImgData = ob_get_contents();
            imagedestroy($image);
            ob_end_clean();
        }else
        {
            $incPos = strpos($imgData, 'IDAT') - 4;
            $chunk = 'pHYs'.pack('NNc', $convert, $convert, 1);
            $incData = pack('N', 9).$chunk.pack('N', crc32($chunk));
            $newImgData = substr_replace($imgData, $incData, $incPos, 0);
        }
        
        pdapp_response(0, "", 'data:image/png;base64,'. base64_encode($newImgData));
    }
}

/*
* list quotes
*/
add_action('wp_ajax_pdapp-quotes', 'pdapp_quotes');
if(!function_exists('pdapp_quotes'))
{
    function pdapp_quotes()
    {
        if(!current_user_can(PDAPP_CAP_QUOTES))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }
        
        pdapp_response(0, '', []);
    }
}

/*
* get quote
*/
add_action('wp_ajax_pdapp-quote', 'pdapp_quote');
if(!function_exists('pdapp_quote'))
{
    function pdapp_quote()
    {
        if(!current_user_can(PDAPP_CAP_QUOTES))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }
        
        pdapp_response(0, '', []);
    }
}

/*
* update quote status
*/
add_action('wp_ajax_pdapp-quote-status', 'pdapp_quote_status');
if(!function_exists('pdapp_quote_status'))
{
    function pdapp_quote_status()
    {
        if(!current_user_can(PDAPP_CAP_QUOTES))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        pdapp_response(1, pdapp_lang('msg.change_status_error', 'admin'));
    }
}

/*
* remove Quote
*/
add_action('wp_ajax_pdapp-remove-quote', 'pdapp_remove_quote');
if(!function_exists('pdapp_remove_quote'))
{
    function pdapp_remove_quote()
    {
        if(!current_user_can(PDAPP_CAP_QUOTES))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        pdapp_response(1, pdapp_lang('msg.remove_error', 'admin'));
    }
}

/*
* list products
*/
add_action('wp_ajax_pdapp-products', 'pdapp_products');
if(!function_exists('pdapp_products'))
{
    function pdapp_products()
    {
        if(!current_user_can(PDAPP_CAP_PRODUCTS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $products = pdapp_get_cache('products', 'lists');
        if(!$products)
        {
            global $wpdb;
            $products = $wpdb->get_results($wpdb->prepare("SELECT * FROM %i", PDAPP_DB_PRODUCTS), ARRAY_A);
            if(!$products || count($products) == 0)
            {
                pdapp_response(0, '', []);
            }
            pdapp_set_cache('products', 'lists', $products);
        }

        pdapp_response(0, '', $products);
    }
}

/*
* get product
*/
add_action('wp_ajax_pdapp-product', 'pdapp_product');
if(!function_exists('pdapp_product'))
{
    function pdapp_product()
    {
        if(!current_user_can(PDAPP_CAP_PRODUCTS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $id = (int) pdapp_get('id');
        if($id == 0)
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }

        $product = pdapp_get_product($id);
        if(!isset($product['id']))
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }
        
        pdapp_response(0, '', $product);
    }
}

/*
* copy product
*/
add_action('wp_ajax_pdapp-copy-product', 'pdapp_copy_product');
if(!function_exists('pdapp_copy_product'))
{
    function pdapp_copy_product()
    {
        if(!current_user_can(PDAPP_CAP_PRODUCTS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
    }
}

/*
* get colors Data
*/
add_action('wp_ajax_pdapp-get-colors', 'pdapp_get_colors');
if(!function_exists('pdapp_get_colors'))
{
    function pdapp_get_colors()
    {
        if (!pdapp_check_token(true))
        {
            pdapp_response(-1, pdapp_lang('token_error', 'system'));
        }
        if(!current_user_can(PDAPP_CAP_PRODUCTS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }
        
        $colors = [];
        $file = PDAPP_PLUGIN_DIR .'datas/colors.json';
        $str = pdapp_read_file($file);
        if($str)
        {
            $colors = json_decode($str, true);
        }
        
        pdapp_response(0, '', $colors);
    }
}

/*
* save Product Data
*/
add_action('wp_ajax_pdapp-save-product', 'pdapp_save_product');
if(!function_exists('pdapp_save_product'))
{
    function pdapp_save_product()
    {
        if (!pdapp_check_token(true))
        {
            pdapp_response(-1, pdapp_lang('token_error', 'system'));
        }
        if(!current_user_can(PDAPP_CAP_PRODUCTS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $err = pdapp_lang('save_error', 'system');
        $post = pdapp_upload_jsons('product', ['id'=>"key", 'vid'=>"key", 'title'=>"text", 'pid'=>"key", 'unit'=>"text", 'colors'=>"text", 'sizes'=>"text", 'views'=>"text", 'attributes'=>"text"], ['extras'=>'text', 'advanced'=>'text', 'thumb'=>'text']);
        if(!$post)
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }
        
        $extras = $post['extras'];
        $advanced = $post['advanced'];
        $pid = ($post['id'] != '' && $post['vid'] != '') ? (int) $post['id'] : pdapp_insert_db(PDAPP_DB_PRODUCTS, ["vid"=>0, "pid"=>0, "title"=>"", "thumb"=>"", "created"=>gmdate('Y-m-d H:i:s')], ["%d", "%d", "%s", "%s", "%s"]);
        if(!$pid)
        {
            pdapp_response(1, $err);
        }

        $post['unit'] = json_decode($post['unit'], true);
        $post['colors'] = json_decode($post['colors'], true);
        $post['sizes'] = json_decode($post['sizes'], true);
        $post['views'] = json_decode($post['views'], true);
        $post['attributes'] = json_decode($post['attributes'], true);
        $extras = $extras != '' ? json_decode($extras, true) : [];
        $advanced = $advanced != '' ? json_decode($advanced, true) : ["customize"=>false];

        $views = pdapp_upload_views($post['views'], $pid);
        $value = ["unit"=>$post['unit'], "colors"=>$post['colors'], "sizes"=>$post['sizes'], "extras"=>$extras, "views"=>$views, "attributes"=>$post['attributes'], "advanced"=>$advanced];
        $thumb = $post['thumb'] != '' ? pdapp_write_image('products/product-'. $pid, $post['thumb']) : '';
        $product = ["pid"=>(int) $post['pid'], "title"=>$post['title'], "thumb"=>$thumb];
        
        if($post['id'] != '' && $post['vid'] != '')
        {
            $vid = (int) $post['vid'];
            $err = pdapp_lang('msg.update_error', 'admin');
            $vcheck = pdapp_update_db(PDAPP_DB_VALUES, ["values"=>pdapp_json_encode($value)], ["id"=>$vid], ["%s"], ["%d"]);
            $pcheck = pdapp_update_db(PDAPP_DB_PRODUCTS, pdapp_verify_field($product, ["pid", "title", "thumb"]), ["id"=>$pid], ["%d", "%s", "%s"], ["%d"]);

            if($vcheck || $pcheck)
            {
                $post['created'] = pdapp_post('created', 'text', gmdate('Y-m-d H:i:s'));
                $res = ["id"=>$pid, "vid"=>$vid, "title"=>$post["title"], "pid"=>(int) $post['pid'], "thumb"=>$thumb, "created"=>$post['created']];
                $value = json_decode(pdapp_json_encode($value), true);
                $product = pdapp_merge_value($res, $value);

                pdapp_delete_cache('products', 'lists');
                pdapp_delete_cache('products', 'product-'. $pid);
                pdapp_response(0, pdapp_lang('msg.update_success', 'admin'), $product);
            }
        }else
        {
            $vid = pdapp_insert_db(PDAPP_DB_VALUES, ["values"=>pdapp_json_encode($value)], ["%s"]);
            if($vid)
            {
                $product['vid'] = $vid;
                if(pdapp_update_db(PDAPP_DB_PRODUCTS, pdapp_verify_field($product, ["pid", "title", "thumb", "vid"]), ["id"=>$pid], ["%d", "%s", "%s", "%d"], ["%d"]))
                {
                    $res = ["id"=>$pid, "vid"=>$vid, "pid"=>$product['pid'], "title"=>$post["title"], "thumb"=>$thumb, "created"=>gmdate('Y-m-d H:i:s')];
                    pdapp_delete_cache('products', 'lists');

                    $value = json_decode(pdapp_json_encode($value), true);
                    $product = pdapp_merge_value($res, $value);
                    pdapp_set_cache('products', 'product-'. $pid, $product);
                    pdapp_response(0, pdapp_lang('msg.add_success', 'admin'), $product);
                }
            }
        }

        pdapp_response(1, $err);
    }
}

/*
* Upload product data
*/
add_action('wp_ajax_pdapp-upload-product', 'pdapp_upload_product');
if(!function_exists('pdapp_upload_product'))
{
    function pdapp_upload_product()
    {
        if (!pdapp_check_token(true))
        {
            pdapp_response(-1, pdapp_lang('token_error', 'system'));
        }
        if(!current_user_can(PDAPP_CAP_PRODUCTS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $post = pdapp_upload_jsons('product', ['title'=>"text", 'pid'=>"key", 'unit'=>"text", 'colors'=>"text", 'sizes'=>"text", 'views'=>"text", 'attributes'=>"text"], ['extras'=>'text', 'advanced'=>'text', 'thumb'=>'text']);
        if(!$post)
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }
        
        $created = gmdate('Y-m-d H:i:s');
        $extras = $post['extras'];
        $advanced = $post['advanced'];
        $pid = pdapp_insert_db(PDAPP_DB_PRODUCTS, ["vid"=>0, "pid"=>0, "title"=>"", "thumb"=>"", "created"=>$created], ["%d", "%d", "%s", "%s", "%s"]);
        if(!$pid)
        {
            pdapp_response(1, pdapp_lang('save_error', 'system'));
        }

        $post['unit'] = json_decode($post['unit'], true);
        $post['colors'] = json_decode($post['colors'], true);
        $post['sizes'] = json_decode($post['sizes'], true);
        $post['views'] = json_decode($post['views'], true);
        $post['attributes'] = json_decode($post['attributes'], true);
        $extras = $extras != '' ? json_decode($extras, true) : [];
        $advanced = $advanced != '' ? json_decode($advanced, true) : ["customize"=>false];

        $views = pdapp_upload_views($post['views'], $pid);
        $value = ["unit"=>$post['unit'], "colors"=>$post['colors'], "sizes"=>$post['sizes'], "extras"=>$extras, "views"=>$views, "attributes"=>$post['attributes'], "advanced"=>$advanced];
        $thumb = pdapp_write_image('products/product-'. $pid, $post['thumb']);
        $product = ["pid"=>(int) $post['pid'], "title"=>$post['title'], "thumb"=>$thumb];
        
        $vid = pdapp_insert_db(PDAPP_DB_VALUES, ["values"=>pdapp_json_encode($value)], ["%s"]);
        if($vid)
        {
            $product['vid'] = $vid;
            if(pdapp_update_db(PDAPP_DB_PRODUCTS, pdapp_verify_field($product, ["pid", "title", "thumb", "vid"]), ["id"=>$pid], ["%d", "%s", "%s", "%d"], ["%d"]))
            {
                $res = ["id"=>$pid, "vid"=>$vid, "pid"=>$product['pid'], "title"=>$post["title"], "thumb"=>$thumb, "created"=>$created];
                pdapp_delete_cache('products', 'lists');

                $value = json_decode(pdapp_json_encode($value), true);
                $product = pdapp_merge_value($res, $value);
                pdapp_set_cache('products', 'product-'. $pid, $product);
                pdapp_response(0, pdapp_lang('msg.add_success', 'admin'), $product);
            }
        }

        pdapp_response(1, pdapp_lang('save_error', 'system'));
    }
}

/*
* remove Product Data
*/
add_action('wp_ajax_pdapp-remove-product', 'pdapp_remove_product');
if(!function_exists('pdapp_remove_product'))
{
    function pdapp_remove_product()
    {
        if (!pdapp_check_token(true))
        {
            pdapp_response(-1, pdapp_lang('token_error', 'system'));
        }
        if(!current_user_can(PDAPP_CAP_PRODUCTS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $posts = pdapp_post_arrs('data', ['pid'=>'key', 'vid'=>'key']);
        if(!isset($posts[0]))
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }
        
        $removed = [];
        foreach($posts as $post)
        {
            $pid = (int) $post['pid'];
            $vid = (int) $post['vid'];
            if(pdapp_delete_db(PDAPP_DB_PRODUCTS, ["id"=>$pid], ["%d"]))
            {
                pdapp_delete_dir(PDAPP_UPLOAD_DIR .'products/product-' .$pid);
                $removed[] = $pid;

                pdapp_delete_cache('products', 'lists');
                if(pdapp_delete_db(PDAPP_DB_VALUES, ["id"=>$vid], ["%d"]))
                {
                    pdapp_delete_cache('products', 'product-'. $pid);
                }
            }
        }

        if(count($removed))
        {
            pdapp_response(0, pdapp_lang('msg.remove_success', 'admin'), $removed);
        }

        pdapp_response(1, pdapp_lang('msg.remove_error', 'admin'));
    }
}

/*
* list prints
*/
add_action('wp_ajax_pdapp-prints', 'pdapp_prints');
if(!function_exists('pdapp_prints'))
{
    function pdapp_prints()
    {
        if(!current_user_can(PDAPP_CAP_PRINTINGS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $prints = pdapp_get_prints();
        
        pdapp_response(0, '', $prints);
    }
}

/*
* get print
*/
add_action('wp_ajax_pdapp-print', 'pdapp_print');
if(!function_exists('pdapp_print'))
{
    function pdapp_print()
    {
        if(!current_user_can(PDAPP_CAP_PRINTINGS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $id = (int) pdapp_get('id');
        if($id == 0)
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }

        $print = pdapp_get_cache('prints', 'print-'. $id);
        if(!$print)
        {
            global $wpdb;
            $res = $wpdb->get_row($wpdb->prepare("SELECT * FROM %i WHERE `id`=%d", [PDAPP_DB_PRINTS, $id]), ARRAY_A);
            if(!isset($res['id']))
            {
                pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
            }
            $print = ["id"=>(int) $res['id'], "pid"=>$res['pid'], "title"=>$res["title"], "thumb"=>$res['thumb'], "created"=>$res['created']];
            
            $value = $wpdb->get_row($wpdb->prepare("SELECT * FROM %i WHERE `id`=%d", [PDAPP_DB_VALUES, $res['pid']]), ARRAY_A);
            if(!isset($value['values']))
            {
                pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
            }

            $value['values'] = json_decode($value['values'], true);
            $print['prints'] = $value['values'];
            pdapp_set_cache('prints', 'print-'. $id, $print);
        }
        
        pdapp_response(0, '', $print);
    }
}

/*
* save Print Data
*/
add_action('wp_ajax_pdapp-save-print', 'pdapp_save_print');
if(!function_exists('pdapp_save_print'))
{
    function pdapp_save_print()
    {
        if (!pdapp_check_token(true))
        {
            pdapp_response(-1, pdapp_lang('token_error', 'system'));
        }
        if(!current_user_can(PDAPP_CAP_PRINTINGS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $err = pdapp_lang('save_error', 'system');
        $post = pdapp_upload_jsons('print', ['title'=>"text", 'prints'=>"text"], ['id'=>'key', 'pid'=>'key', 'thumb'=>'text']);
        if(!$post)
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }
        
        $post['prints'] = json_decode($post['prints'], true);
        $created = pdapp_post('created', 'text', gmdate('Y-m-d H:i:s'));

        $id = ($post['id'] && $post['pid']) ? $post['id'] : pdapp_insert_db(PDAPP_DB_PRINTS, ["pid"=>0, "title"=>"", "thumb"=>"", "created"=>gmdate('Y-m-d H:i:s')], ["%d", "%s", "%s", "%s"]);
        if(!$id)
        {
            pdapp_response(1, $err);
        }
        
        $value = $post['prints'];
        $thumb = pdapp_write_image('prints', $post['thumb'], 'print-'. $id .'.png');

        $thumb = $thumb != '' ? $id .'.png' : '';
        $print = ["title"=>$post['title'], "thumb"=>$thumb];
        if($post['id'] && $post['pid'])
        {
            $pid = $post['pid'];
            $err = pdapp_lang('msg.update_error', 'admin');
            pdapp_update_db(PDAPP_DB_VALUES, ["values"=>pdapp_json_encode($value)], ["id"=>$pid], ["%s"], ["%d"]);

            pdapp_update_db(PDAPP_DB_PRINTS, pdapp_verify_field($print, ["title", "thumb"]), ["id"=>$id], ["%s", "%s"], ["%d"]);
            $res = ["id"=>$id, "pid"=>$pid, "title"=>$post['title'], "thumb"=>$thumb, "created"=>$created];
            pdapp_delete_cache('prints', 'lists');
            
            $value = json_decode(pdapp_json_encode($value), true);
            $res['prints'] = $value;
            pdapp_delete_cache('prints', 'print-'. $id);
            pdapp_response(0, pdapp_lang('msg.update_success', 'admin'), $res);
        }else
        {
            $pid = pdapp_insert_db(PDAPP_DB_VALUES, ["values"=>pdapp_json_encode($value)], ["%s"]);
            if($pid)
            {
                $print['pid'] = $pid;
                if(pdapp_update_db(PDAPP_DB_PRINTS, pdapp_verify_field($print, ["title", "thumb", "pid"]), ["id"=>$id], ["%s", "%s", "%d"], ["%d"]))
                {
                    $res = ["id"=>$id, "pid"=>$pid, "title"=>$post['title'], "thumb"=>$thumb, "created"=>gmdate('Y-m-d H:i:s')];
                    pdapp_delete_cache('prints', 'lists');

                    $value = json_decode(pdapp_json_encode($value), true);
                    $res['prints'] = $value;
                    pdapp_set_cache('prints', 'print-'. $id, $res);
                    pdapp_response(0, pdapp_lang('msg.add_success', 'admin'), $res);
                }
            }
        }

        pdapp_response(1, $err);
    }
}

/*
* remove Print
*/
add_action('wp_ajax_pdapp-remove-print', 'pdapp_remove_print');
if(!function_exists('pdapp_remove_print'))
{
    function pdapp_remove_print()
    {
        if (!pdapp_check_token(true))
        {
            pdapp_response(-1, pdapp_lang('token_error', 'system'));
        }
        if(!current_user_can(PDAPP_CAP_PRINTINGS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $posts = pdapp_post_arrs('data', ['id'=>'key', 'pid'=>'key']);
        if(!isset($posts[0]))
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }
        
        $removed = [];
        foreach($posts as $post)
        {
            $id = (int) $post['id'];
            $pid = (int) $post['pid'];
            if(pdapp_delete_db(PDAPP_DB_PRINTS, ["id"=>$id], ["%d"]))
            {
                pdapp_delete_file(PDAPP_UPLOAD_DIR .'thumbnails/prints/print-' .$id. '.png');
                pdapp_delete_cache('prints', 'lists');
                if(pdapp_delete_db(PDAPP_DB_VALUES, ["id"=>$pid], ["%d"]))
                {
                    pdapp_delete_cache('prints', 'print-'. $id);
                }
                $removed[] = $id;
            }
        }

        if(count($removed))
        {
            pdapp_response(0, pdapp_lang('msg.remove_success', 'admin'), $removed);
        }

        pdapp_response(1, pdapp_lang('msg.remove_error', 'admin'));
    }
}

/*
* Artworks
*
* get Folders
*/
add_action('wp_ajax_pdapp-art-folders', 'pdapp_art_folders');
if(!function_exists('pdapp_art_folders'))
{
    function pdapp_art_folders()
    {
        if(!current_user_can(PDAPP_CAP_ARTS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $folders = pdapp_get_art_folders();
        pdapp_response(0, "", $folders);
    }
}

/*
* list arts
*/
add_action('wp_ajax_pdapp-arts', 'pdapp_arts');
if(!function_exists('pdapp_arts'))
{
    function pdapp_arts()
    {
        if(!current_user_can(PDAPP_CAP_ARTS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }
        $folderID = pdapp_get('folder');
        if(!$folderID)
        {
            $folderID = 0;
        }

        $arts = pdapp_get_cache('arts', 'arts-'. $folderID);
        if(!$arts)
        {
            $arts = [];
            global $wpdb;
            $res = $wpdb->get_results($wpdb->prepare("SELECT * FROM %i WHERE `pid`=%d AND `type`='a'", [PDAPP_DB_ARTWORKS, $folderID]), ARRAY_A);
            
            usort($res, function ($a, $b)
            {
                $arrA = json_decode($a['title'], true);
                $arrB = json_decode($b['title'], true);
                if($arrA == '' || $arrB == '') return strcmp('a', 'b');
                $newA = isset($arrA['en_US']) ? $arrA['en_US'] : current($arrA);
                $newB = isset($arrB['en_US']) ? $arrB['en_US'] :current($arrB);
                return strcmp($newA, $newB);
            });

            $langs = pdapp_get_lang_available();
            foreach($res as $val)
            {
                $titles = json_decode($val["title"], true);
                $title = [];
                foreach($langs as $key=>$lang)
                {
                    $title[$key] = isset($titles[$key]) ? $titles[$key] : "Untitle";
                }
                $arts[] = ["id"=>$val['id'], "pid"=>$val['pid'], "title"=>$title, "price"=>$val['price'], "filetype"=>$val['filetype'], "thumb"=>$val['thumb'], "created"=>$val['created']];
            }
            pdapp_set_cache('arts', 'arts-'. $folderID, $arts);
        }
        
        pdapp_response(0, '', $arts);
    }
}

/*
* get Artwork
*/
add_action('wp_ajax_pdapp-artwork', 'pdapp_artwork');
if(!function_exists('pdapp_artwork'))
{
    function pdapp_artwork()
    {
        if(!current_user_can(PDAPP_CAP_ARTS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $artID = (int) pdapp_get('id', 0);
        if(!$artID)
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }

        $filetype = pdapp_get('type');
        
        $file = PDAPP_UPLOAD_DIR .'arts/art-'. md5(PDAPP_PREFIX . $artID) .'.'. $filetype;
        $art = pdapp_read_file($file);
        if($art)
        {
            $res = '';
            if($filetype == 'svg')
            {
                $res = $art;
            }else
            {
                $res = 'data:image/' . $filetype . ';base64,' . base64_encode($art);
            }

            if($res != '')
            {
                pdapp_response(0, "", $res);
            }
        }
        
        pdapp_response(1, pdapp_lang('file_empty', 'system'));
    }
}

/*
* save Art Data
*/
add_action('wp_ajax_pdapp-save-art', 'pdapp_save_art');
if(!function_exists('pdapp_save_art'))
{
    function pdapp_save_art()
    {
        if (!pdapp_check_token(true))
        {
            pdapp_response(-1, pdapp_lang('token_error', 'system'));
        }
        if(!current_user_can(PDAPP_CAP_ARTS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $err = pdapp_lang('save_error', 'system');
        $post = pdapp_post_fields(['pid'=>"key", 'title'=>"lang", 'filetype'=>"text", 'type'=>"text"]);
        if(!$post)
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }
        
        $id = 0;
        $post['id'] = pdapp_post('id', 'key', 0);
        $post['thumb'] = pdapp_post('thumb', 'text', '');
        $post['created'] = pdapp_post('created', 'text', gmdate('Y-m-d H:i:s'));
        $pid = (int) $post['pid'];
        $type = $post['type'] == 'art' ? 'a' : 'f';
        $filetype = $post['filetype'];
        
        $thumb = '';
        if($type == 'a')
        {
            $filePath = '';
            if(isset($_FILES['upload']) && !empty($_FILES['upload']['name']))
            {
                $name = 'upload-'. uniqid();
                $result = pdapp_upload('upload', PDAPP_UPLOAD_DIR .'arts', ['png', 'jpg', 'jpeg', 'svg'], $name, ['jpg|jpeg|jpe'=>'image/jpeg', 'png'=>'image/png', 'svg'=>'image/svg+xml']);

                if($result['error'] == 0 && isset($result['filename']) && $result['filename'] != '')
                {
                    $filetype = $result['ext'];
                }else
                {
                    pdapp_response(1, $result['message']);
                }

                $filePath = $result['path'];
            }

            $post['price'] = pdapp_post('price', 'text', 0);
            if($post['id'])
            {
                /*Update art*/
                $id = (int) $post['id'];
                if($filePath != '')
                {
                    $filename = 'art-' .md5(PDAPP_PREFIX . $id). '.'.$filetype;
                    global $wp_filesystem;
                    $wp_filesystem->move($filePath, PDAPP_UPLOAD_DIR .'arts/'. $filename);
                }
                
                $thumb = pdapp_write_image('thumbnails/arts', $post['thumb'], 'art-'. $id .'.png');
                $thumb = $thumb != '' ? $id. '.png' : '';
                $err = pdapp_lang('msg.update_error', 'admin');
                pdapp_update_db(PDAPP_DB_ARTWORKS, pdapp_verify_field(["pid"=>$pid, "title"=>$post["title"], "filetype"=>$filetype, "thumb"=>$thumb, "price"=>$post['price']], ["pid", "title", "filetype", "thumb", "price"]), ["id"=>$id], ["%d", "%s", "%s", "%s", "%f"], ["%d"]);
                
                pdapp_delete_cache('arts', 'arts-'. $pid);
                pdapp_response(0, pdapp_lang('msg.update_success', 'admin'), ["id"=>$id, "pid"=>$pid, "title"=>$post["title"], "filetype"=>$filetype, "thumb"=>$thumb, "price"=>$post['price'], "created"=>$post['created']]);
            }else
            {
                /*Add art*/
                $created = gmdate('Y-m-d H:i:s');
                $id = pdapp_insert_db(PDAPP_DB_ARTWORKS, pdapp_verify_field(["pid"=>$pid, "title"=>$post["title"], "type"=>$type, "filetype"=>$filetype, "thumb"=>"", "price"=>$post['price'], "created"=>$created], ["pid", "title", "type", "filetype", "thumb", "price", "created"]), ["%d", "%s", "%s", "%s", "%s", "%f", "%s"]);
                if(!$id)
                {
                    if($filePath != '')
                    {
                        pdapp_delete_file($filePath);
                    }
                    pdapp_response(1, $err);
                }
                if($filePath != '')
                {
                    $filename = 'art-' .md5(PDAPP_PREFIX . $id). '.'.$filetype;
                    global $wp_filesystem;
                    $wp_filesystem->move($filePath, PDAPP_UPLOAD_DIR .'arts/'. $filename);
                }

                $thumb = pdapp_write_image('thumbnails/arts', $post['thumb'], 'art-'. $id .'.png');
                $thumb = $thumb != '' ? $id. '.png' : '';
                pdapp_update_db(PDAPP_DB_ARTWORKS, ["thumb"=>$thumb], ["id"=>$id], ["%s"], ["%d"]);

                pdapp_delete_cache('arts', 'arts-'. $pid);
                pdapp_response(0, pdapp_lang('msg.add_success', 'admin'), ["id"=>$id, "pid"=>$pid, "title"=>$post["title"], "filetype"=>$filetype, "thumb"=>$thumb, "price"=>$post['price'], "created"=>$created]);
            }
        }else
        {
            if($post['id'])
            {
                /*Update folder*/
                $id = (int) $post['id'];
                $thumb = pdapp_write_image('thumbnails/arts', $post['thumb'], 'art-folder-'. $id. '.png');
                $thumb = $thumb != '' ? $id. '.png' : '';
                $err = pdapp_lang('msg.update_error', 'admin');
                pdapp_update_db(PDAPP_DB_ARTWORKS, pdapp_verify_field(["pid"=>$pid, "title"=>$post["title"], "filetype"=>$filetype, "thumb"=>$thumb], ["pid", "title", "filetype", "thumb"]), ["id"=>$id], ["%d", "%s", "%s", "%s"], ["%d"]);

                pdapp_delete_cache('arts', 'folders-'. $pid);
                pdapp_delete_cache('arts', 'folders');
                pdapp_response(0, pdapp_lang('msg.update_success', 'admin'), ["id"=>$id, "pid"=>$pid, "title"=>$post["title"], "filetype"=>$filetype, "thumb"=>$thumb, "created"=>$post['created']]);
            }else
            {
                /*Add folder*/
                $created = gmdate('Y-m-d H:i:s');
                $id = pdapp_insert_db(PDAPP_DB_ARTWORKS, pdapp_verify_field(["pid"=>$pid, "title"=>$post["title"], "type"=>$type, "filetype"=>$filetype, "thumb"=>"", "created"=>$created], ["pid", "title", "type", "filetype", "thumb", "created"]), ["%d", "%s", "%s", "%s", "%s", "%s"]);
                if(!$id)
                {
                    pdapp_response(1, $err);
                }
                $thumb = pdapp_write_image('thumbnails/arts', $post['thumb'], 'art-folder-'. $id. '.png');
                $thumb = $thumb != '' ? $id. '.png' : '';
                pdapp_update_db(PDAPP_DB_ARTWORKS, ["thumb"=>$thumb], ["id"=>$id], ["%s"], ["%d"]);
                
                pdapp_delete_cache('arts', 'folders-'. $pid);
                pdapp_delete_cache('arts', 'folders');
                pdapp_response(0, pdapp_lang('msg.add_success', 'admin'), ["id"=>$id, "pid"=>$pid, "title"=>$post["title"], "filetype"=>$filetype, "thumb"=>$thumb, "created"=>$created]);
            }
        }

        pdapp_response(1, $err);
    }
}

/*
* update Art Data
*/
add_action('wp_ajax_pdapp-update-arts', 'pdapp_update_arts');
if(!function_exists('pdapp_update_arts'))
{
    function pdapp_update_arts()
    {
        if (!pdapp_check_token(true))
        {
            pdapp_response(-1, pdapp_lang('token_error', 'system'));
        }
        if(!current_user_can(PDAPP_CAP_ARTS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $posts = pdapp_post_arrs('data', ['id'=>'key', 'pid'=>'key', 'title'=>'lang', 'price'=>'text']);
        if(!isset($posts[0]))
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }
        
        $updated = [];
        foreach($posts as $post)
        {
            $id = (int) $post['id'];
            $pid = (int) $post['pid'];
            if(pdapp_update_db(PDAPP_DB_ARTWORKS, pdapp_verify_field(["title"=>$post['title'], "price"=>(float) $post['price']], ["title", "price"]), ["id"=>$id], ["%s", "%f"], ["%d"]))
            {
                $updated[] = $id;
                pdapp_delete_cache('arts', 'arts-'. $pid);
            }
        }

        if(count($updated))
        {
            pdapp_response(0, pdapp_lang('msg.update_success', 'admin'), $updated);
        }

        pdapp_response(1, pdapp_lang('msg.update_error', 'admin'));
    }
}

/*
* import Art Data
*/
add_action('wp_ajax_pdapp-upload-art', 'pdapp_upload_art');
if(!function_exists('pdapp_upload_art'))
{
    function pdapp_upload_art()
    {
        if (!pdapp_check_token(true))
        {
            pdapp_response(-1, pdapp_lang('token_error', 'system'));
        }
        if(!current_user_can(PDAPP_CAP_ARTS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $post = pdapp_post_fields(['pid'=>"key", 'title'=>"text", 'data'=>"text", 'thumb'=>"text"]);
        if(!$post)
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }
        
        $name = 'art-' .uniqid(). '.svg';
        $file = pdapp_write_pda('/arts', $post['data'], $name);
        if($file != '')
        {
            $pid = (int) $post['pid'];
            $title = [];
            $langs = pdapp_get_lang_available();
            foreach($langs as $key=>$lang)
            {
                $title[$key] = $post["title"];
            }

            $created = gmdate('Y-m-d H:i:s');
            $id = pdapp_insert_db(PDAPP_DB_ARTWORKS, pdapp_verify_field(["pid"=>$pid, "title"=>$title, "type"=>"a", "filetype"=>"svg", "thumb"=>"", "price"=>0, "created"=>$created], ["pid", "title", "type", "filetype", "thumb", "created"]), ["%d", "%s", "%s", "%s", "%s", "%s"]);
            if(!$id)
            {
                pdapp_delete_file(PDAPP_UPLOAD_DIR .'arts/'. $name);
                pdapp_response(1, pdapp_lang('save_error', 'system'));
            }

            $filename = 'art-' .md5(PDAPP_PREFIX . $id). '.svg';
            global $wp_filesystem;
            $wp_filesystem->move(PDAPP_UPLOAD_DIR .'arts/'. $name, PDAPP_UPLOAD_DIR .'arts/'. $filename);
            
            $thumb = pdapp_write_image('thumbnails/arts', $post['thumb'], 'art-'. $id .'.png');
            $thumb = $thumb != '' ? $id. '.png' : '';
            pdapp_update_db(PDAPP_DB_ARTWORKS, ["thumb"=>$thumb], ["id"=>$id], ["%s"], ["%d"]);

            pdapp_delete_cache('arts', 'arts-'. $pid);
            pdapp_response(0, pdapp_lang('msg.add_success', 'admin'), ["id"=>$id, "pid"=>$pid, "title"=>$title, "filetype"=>"svg", "thumb"=>$thumb, "price"=>0, "created"=>$created]);
        }

        pdapp_response(1, pdapp_lang('save_error', 'system'));
    }
}

/*
* remove Art Data
*/
add_action('wp_ajax_pdapp-remove-art', 'pdapp_remove_art');
if(!function_exists('pdapp_remove_art'))
{
    function pdapp_remove_art()
    {
        if (!pdapp_check_token(true))
        {
            pdapp_response(-1, pdapp_lang('token_error', 'system'));
        }
        if(!current_user_can(PDAPP_CAP_ARTS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $removed = [];
        $type = pdapp_post('type', 'text', 'art');
        $posts = pdapp_post_arrs('data', ['id'=>'key', 'pid'=>'key']);
        if(!isset($posts[0]))
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }

        if($type == 'art')
        {
            foreach($posts as $post)
            {
                $id = (int) $post['id'];
                $pid = (int) $post['pid'];
                if(pdapp_delete_db(PDAPP_DB_ARTWORKS, ["id"=>$id], ["%d"]))
                {
                    if(!pdapp_delete_file(PDAPP_UPLOAD_DIR .'arts/art-'. md5(PDAPP_PREFIX . $id) .'.svg'))
                    {
                        if(!pdapp_delete_file(PDAPP_UPLOAD_DIR .'arts/art-'. md5(PDAPP_PREFIX . $id) .'.png'))
                        {
                            if(!pdapp_delete_file(PDAPP_UPLOAD_DIR .'arts/art-'. md5(PDAPP_PREFIX . $id) .'.jpg'))
                            {
                                pdapp_delete_file(PDAPP_UPLOAD_DIR .'arts/art-'. md5(PDAPP_PREFIX . $id) .'.jpeg');
                            }
                        }
                    }
                    
                    pdapp_delete_file(PDAPP_UPLOAD_DIR .'thumbnails/arts/art-'. $id .'.png');
                    pdapp_delete_cache('arts', 'arts-'. $pid);
                    $removed[] = $id;
                }
            }
        }else
        {
            $post = $posts[0];
            $id = (int) $post['id'];
            $pid = (int) $post['pid'];
            if(pdapp_delete_db(PDAPP_DB_ARTWORKS, ["id"=>$id], ["%d"]))
            {
                pdapp_delete_file(PDAPP_UPLOAD_DIR .'thumbnails/arts/art-folder-'. $id .'.png');
                pdapp_delete_cache('arts', 'folders-'. $pid);
                pdapp_delete_cache('arts', 'arts-'. $pid);
                pdapp_update_root_folders($id, 'arts');
                pdapp_delete_cache('arts', 'folders');
                $removed[] = $id;
            }
        }

        if(count($removed))
        {
            pdapp_response(0, pdapp_lang('msg.remove_success', 'admin'), $removed);
        }

        pdapp_response(1, pdapp_lang('msg.remove_error', 'admin'));
    }
}

/*
* move Art Data
*/
add_action('wp_ajax_pdapp-move-art', 'pdapp_move_art');
if(!function_exists('pdapp_move_art'))
{
    function pdapp_move_art()
    {
        if (!pdapp_check_token(true))
        {
            pdapp_response(-1, pdapp_lang('token_error', 'system'));
        }
        if(!current_user_can(PDAPP_CAP_ARTS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $post = pdapp_post_fields(['id'=>"key", 'pid'=>"key", 'tid'=>"key", 'type'=>"text"]);
        if(!$post)
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }

        $id = (int) $post['id'];
        $pid = (int) $post['pid'];
        $tid = (int) $post['tid'];
        $type = $post['type'] == 'art' ? 'a' : 'f';
        
        if($type == 'a')
        {
            if(pdapp_update_db(PDAPP_DB_ARTWORKS, ["pid"=>$tid], ["id"=>$id, "type"=>$type], ["%d"], ["%d", "%s"]))
            {
                pdapp_delete_cache('arts', 'arts-'. $pid);
                pdapp_delete_cache('arts', 'arts-'. $tid);
                pdapp_response(0, pdapp_lang('msg.move_success', 'admin'));
            }
        }else
        {
            if(pdapp_update_db(PDAPP_DB_ARTWORKS, ["pid"=>$tid], ["id"=>$id, "type"=>$type], ["%d"], ["%d", "%s"]))
            {
                pdapp_delete_cache('arts', 'folders-'. $pid);
                pdapp_delete_cache('arts', 'folders-'. $tid);
                pdapp_delete_cache('arts', 'folders');

                pdapp_response(0, pdapp_lang('msg.move_success', 'admin'));
            }
        }

        pdapp_response(1, pdapp_lang('msg.move_error', 'admin'));
    }
}

/*
* list temps
*/
add_action('wp_ajax_pdapp-temps', 'pdapp_templates');
if(!function_exists('pdapp_templates'))
{
    function pdapp_templates()
    {
        if(!current_user_can(PDAPP_CAP_TEMPLATES))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $folderID = pdapp_get('folder');
        if($folderID == '')
        {
            $folderID = 0;
        }

        $temps = pdapp_get_cache('templates', 'templates-'. $folderID);
        if(!$temps)
        {
            $temps = [];
            global $wpdb;
            $res = $wpdb->get_results($wpdb->prepare("SELECT * FROM %i WHERE `pid`=%d AND `type`='t'", [PDAPP_DB_TEMPLATES, $folderID]), ARRAY_A);

            usort($res, function ($a, $b)
            {
                $arrA = json_decode($a['title'], true);
                $arrB = json_decode($b['title'], true);
                if($arrA == '' || $arrB == '') return strcmp('a', 'b');
                $newA = isset($arrA['en_US']) ? $arrA['en_US'] : current($arrA);
                $newB = isset($arrB['en_US']) ? $arrB['en_US'] :current($arrB);
                return strcmp($newA, $newB);
            });

            $langs = pdapp_get_lang_available();
            foreach($res as $val)
            {
                $titles = json_decode($val["title"], true);
                $title = [];
                foreach($langs as $key=>$lang)
                {
                    $title[$key] = isset($titles[$key]) ? $titles[$key] : "Untitle";
                }
                
                $temps[] = ["id"=>$val['id'], "pid"=>$val['pid'], "title"=>$title, "price"=>$val['price'], "size"=>json_decode($val["size"], true), "thumb"=>$val['thumb'], "created"=>$val['created']];
            }
            pdapp_set_cache('templates', 'templates-'. $folderID, $temps);
        }
        
        pdapp_response(0, '', $temps);
    }
}

/*
* get temp
*/
add_action('wp_ajax_pdapp-temp', 'pdapp_temp');
if(!function_exists('pdapp_temp'))
{
    function pdapp_temp()
    {
        if(!current_user_can(PDAPP_CAP_TEMPLATES))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $id = (int) pdapp_get('id');
        if($id == 0)
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }

        $file = PDAPP_UPLOAD_DIR .'templates/template-'. md5(PDAPP_PREFIX . $id) .'.pda';
        $data = pdapp_read_file($file);
        if($data)
        {
            pdapp_response(0, '', $data);
        }
        
        pdapp_response(1, pdapp_lang('file_empty', 'system'));
    }
}

/*
* save Temp Data
*/
add_action('wp_ajax_pdapp-save-temp', 'pdapp_save_temp');
if(!function_exists('pdapp_save_temp'))
{
    function pdapp_save_temp()
    {
        if (!pdapp_check_token(true))
        {
            pdapp_response(-1, pdapp_lang('token_error', 'system'));
        }
        if(!current_user_can(PDAPP_CAP_TEMPLATES))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $err = pdapp_lang('save_error', 'system');
        $post = pdapp_post_fields(['id'=>"key", 'pid'=>"key", 'title'=>"lang", 'type'=>"text"]);
        if(!$post)
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }
        
        $pid = (int) $post['pid'];
        $post['thumb'] = pdapp_post('thumb', 'text', '');
        $post['created'] = pdapp_post('created', 'text', gmdate('Y-m-d H:i:s'));
        $type = $post['type'] == 'temp' ? 't' : 'f';
        
        $thumb = '';
        if($type == 't')
        {
            $post['price'] = pdapp_post('price', 'text', 0);
            $post['size'] = pdapp_post('size', 'text', '');
            $post['file'] = pdapp_post('file', 'text', '');
            if($post['size'] == '')
            {
                $post['size'] = [];
            }else
            {
                $post['size'] = json_decode($post['size'], true);
            }

            if($post['file'] != '')
            {
                $post['file'] = pdapp_replace_image_svg($post['file']);
            }
            if($post['id'])
            {
                /*Update template*/
                $id = (int) $post['id'];
                $thumb = pdapp_write_image('thumbnails/templates', $post['thumb'], 'template-'. $id .'.png');
                $file = pdapp_write_pda('templates', $post['file'], 'template-'. md5(PDAPP_PREFIX . $id) .'.pda');
                if($file == '')
                {
                    pdapp_response(1, pdapp_lang('msg.update_error', 'admin'));
                }

                $filePath = PDAPP_UPLOAD_DIR .'templates/' .$file;
                if(isset($post['size']) && file_exists($filePath))
                {
                    $post['size']['size'] = number_format(filesize($filePath) / 1048576, 2);
                }
                
                $thumb = $thumb != '' ? $id .'.png' : '';
                if(!pdapp_update_db(PDAPP_DB_TEMPLATES, pdapp_verify_field(["pid"=>$pid, "title"=>$post["title"], "thumb"=>$thumb, "price"=>$post['price'], "size"=>$post['size']], ["pid", "title", "thumb", "price", "size"]), ["id"=>$id], ["%d", "%s", "%s", "%f", "%s"], ["%d"]))
                {
                    $err = pdapp_lang('msg.update_error', 'admin');
                    pdapp_response(1, $err);
                }
                
                pdapp_delete_cache('templates', 'templates-'. $pid);
                pdapp_response(0, pdapp_lang('msg.update_success', 'admin'), ["id"=>$id, "pid"=>$pid, "title"=>$post["title"], "thumb"=>$thumb, "price"=>$post['price'], "size"=>$post['size'], "created"=>$post['created']]);
            }else
            {
                /*Add template*/
                $created = gmdate('Y-m-d H:i:s');
                $id = pdapp_insert_db(PDAPP_DB_TEMPLATES, pdapp_verify_field(["pid"=>$pid, "title"=>$post["title"], "type"=>$type, "price"=>0, "size"=>"{}", "thumb"=>"", "created"=>$created], ["pid", "title", "type", "price", "size", "thumb", "created"]), ["%d", "%s", "%s", "%f", "%s", "%s", "%s"]); 
                if(!$id)
                {
                    pdapp_response(1, $err);
                }

                $thumb = pdapp_write_image('thumbnails/templates', $post['thumb'], 'template-'. $id .'.png');
                $file = pdapp_write_pda('templates', $post['file'], 'template-'. md5(PDAPP_PREFIX . $id) .'.pda');
                if($file == '')
                {
                    pdapp_delete_db(PDAPP_DB_TEMPLATES, ["id"=>$id], ["%d"]);
                    pdapp_response(1, $err);
                }

                $filePath = PDAPP_UPLOAD_DIR .'templates/' .$file;
                if(isset($post['size']) && file_exists($filePath))
                {
                    $post['size']['size'] = number_format(filesize($filePath) / 1048576, 2);
                }
                
                $thumb = $thumb != '' ? $id .'.png' : '';
                pdapp_update_db(PDAPP_DB_TEMPLATES, pdapp_verify_field(["size"=>$post['size'], "thumb"=>$thumb], ["size", "thumb"]), ["id"=>$id], ["%s", "%s"], ["%d"]);
                
                pdapp_delete_cache('templates', 'templates-'. $pid);
                pdapp_response(0, pdapp_lang('msg.add_success', 'admin'), ["id"=>$id, "pid"=>$pid, "title"=>$post["title"], "thumb"=>$thumb, "price"=>$post['price'], "size"=>$post['size'], "created"=>$created]);
            }
        }else
        {
            if($post['id'])
            {
                /*Update folder*/
                $id = (int) $post['id'];
                $thumb = pdapp_write_image('thumbnails/templates', $post['thumb'], 'template-folder-'. $id .'.png');
                $thumb = $thumb != '' ? $id. '.png' : '';
                $err = pdapp_lang('msg.update_error', 'admin');

                if(!pdapp_update_db(PDAPP_DB_TEMPLATES, pdapp_verify_field(["pid"=>$pid, "title"=>$post["title"], "thumb"=>$thumb], ["pid", "title", "thumb"]), ["id"=>$id], ["%d", "%s", "%s"], ["%d"]))
                {
                    $err = pdapp_lang('msg.update_error', 'admin');
                    pdapp_response(1, $err);
                }
                pdapp_delete_cache('templates', 'folders-'. $pid);
                pdapp_delete_cache('templates', 'folders');
                
                pdapp_response(0, pdapp_lang('msg.update_success', 'admin'), ["id"=>$id, "pid"=>$pid, "title"=>$post["title"], "thumb"=>$thumb, "created"=>$post['created']]);
            }else
            {
                /*Add folder*/
                $created = gmdate('Y-m-d H:i:s');
                $id = pdapp_insert_db(PDAPP_DB_TEMPLATES, pdapp_verify_field(["pid"=>$pid, "title"=>$post["title"], "type"=>$type, "price"=>0, "size"=>"{}", "thumb"=>"", "created"=>$created], ["pid", "title", "type", "price", "size", "thumb", "created"]), ["%d", "%s", "%s", "%f", "%s", "%s", "%s"]);
                if(!$id)
                {
                    pdapp_response(1, $err);
                }
                $thumb = pdapp_write_image('thumbnails/templates', $post['thumb'], 'template-folder-'. $id. '.png');
                $thumb = $thumb != '' ? $id. '.png' : '';
                pdapp_update_db(PDAPP_DB_TEMPLATES, ["thumb"=>$thumb], ["id"=>$id], ["%s"], ["%d"]);
                
                pdapp_delete_cache('templates', 'folders-'. $pid);
                pdapp_delete_cache('templates', 'folders');
                pdapp_response(0, pdapp_lang('msg.add_success', 'admin'), ["id"=>$id, "pid"=>$pid, "title"=>$post["title"], "type"=>$type, "thumb"=>$thumb, "created"=>$created]);
            }
        }

        pdapp_response(1, $err);
    }
}

/*
* update Temp Data
*/
add_action('wp_ajax_pdapp-update-temps', 'pdapp_update_temps');
if(!function_exists('pdapp_update_temps'))
{
    function pdapp_update_temps()
    {
        if (!pdapp_check_token(true))
        {
            pdapp_response(-1, pdapp_lang('token_error', 'system'));
        }
        if(!current_user_can(PDAPP_CAP_TEMPLATES))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $posts = pdapp_post_arrs('data', ['id'=>'key', 'pid'=>'key', 'title'=>'lang', 'price'=>'text']);
        if(!isset($posts[0]))
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }

        $updated = [];
        foreach($posts as $post)
        {
            $id = (int) $post['id'];
            $pid = (int) $post['pid'];
            $update = ["title"=>$post['title'], "price"=>(float) $post['price']];
            if(pdapp_update_db(PDAPP_DB_TEMPLATES, pdapp_verify_field($update, ["title", "price"]), ["id"=>$id], ["%s", "%f"], ["%d"]))
            {
                $updated[] = $id;
                pdapp_delete_cache('templates', 'templates-'. $pid);
            }
        }

        if(count($updated))
        {
            pdapp_response(0, pdapp_lang('msg.update_success', 'admin'), $updated);
        }

        pdapp_response(1, pdapp_lang('msg.update_error', 'admin'));
    }
}

/*
* import Temp Data
*/
add_action('wp_ajax_pdapp-upload-temp', 'pdapp_upload_temp');
if(!function_exists('pdapp_upload_temp'))
{
    function pdapp_upload_temp()
    {
        if (!pdapp_check_token(true))
        {
            pdapp_response(-1, pdapp_lang('token_error', 'system'));
        }
        if(!current_user_can(PDAPP_CAP_TEMPLATES))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $post = pdapp_post_fields(['pid'=>"key", 'title'=>"text", 'title'=>"data"]);
        $post['data'] = pdapp_post('data', 'text', '');
        if(!$post || $post['data'] == '')
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }
        
        $pid = (int) $post['pid'];
        $size = pdapp_post('size', 'text', '');
        if($size == '')
        {
            $size = [];
        }else
        {
            $size = json_decode($size, true);
        }
        $post['thumb'] = pdapp_post('thumb', 'text', '');
        $created = gmdate('Y-m-d H:i:s');
        $title = [];
        $langs = pdapp_get_lang_available();
        foreach($langs as $key=>$lang)
        {
            $title[$key] = $post["title"];
        }
        $id = pdapp_insert_db(PDAPP_DB_TEMPLATES, ["pid"=>$pid, "title"=>pdapp_json_encode($title), "type"=>"t", "price"=>0, "size"=>"{}", "thumb"=>"", "created"=>$created], ["%d", "%s", "%s", "%f", "%s", "%s", "%s"]);
        if(!$id)
        {
            pdapp_response(1, pdapp_lang('save_error', 'system'));
        }

        $post["title"] = $title;
        $post['data'] = pdapp_replace_image_svg($post['data']);
        $name = 'template-' .md5(PDAPP_PREFIX . $id). '.pda';
        $file = pdapp_write_pda('/templates', $post['data'], $name);
        if($file == '')
        {
            pdapp_delete_db(PDAPP_DB_TEMPLATES, ["id"=>$id], ["%d"]);
            pdapp_response(1, pdapp_lang('save_error', 'system'));
        }

        pdapp_write_image('thumbnails/templates', $post['thumb'], 'template-'. $id .'.png');
        $thumb = $id .'.png';

        $size["unit"] = "px";
        $size["size"] = number_format(filesize(PDAPP_UPLOAD_DIR .'templates/'. $file) / 1048576, 2);
        
        pdapp_update_db(PDAPP_DB_TEMPLATES, pdapp_verify_field(["thumb"=>$thumb, "size"=>$size], ["thumb", "size"]), ["id"=>$id], ["%s", "%s"], ["%d"]);

        pdapp_delete_cache('templates', 'templates-'. $pid);
        pdapp_response(0, pdapp_lang('msg.add_success', 'admin'), ["id"=>$id, "pid"=>$pid, "title"=>$post["title"], "thumb"=>$thumb, "price"=>0, "size"=>$size, "created"=>$created]);
    }
}

/*
* remove Temp Data
*/
add_action('wp_ajax_pdapp-remove-temp', 'pdapp_remove_temp');
if(!function_exists('pdapp_remove_temp'))
{
    function pdapp_remove_temp()
    {
        if (!pdapp_check_token(true))
        {
            pdapp_response(-1, pdapp_lang('token_error', 'system'));
        }
        if(!current_user_can(PDAPP_CAP_TEMPLATES))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $removed = [];
        $type = pdapp_post('type', 'text', 'temp');
        $posts = pdapp_post_arrs('data', ['id'=>'key', 'pid'=>'key']);
        if(!isset($posts[0]))
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }
        if($type == 'temp')
        {
            foreach($posts as $post)
            {
                $id = (int) $post['id'];
                $pid = (int) $post['pid'];
                if(pdapp_delete_db(PDAPP_DB_TEMPLATES, ["id"=>$id], ["%d"]))
                {
                    pdapp_delete_file(PDAPP_UPLOAD_DIR .'templates/template-'. md5(PDAPP_PREFIX . $id) .'.pda');
                    pdapp_delete_file(PDAPP_UPLOAD_DIR .'thumbnails/templates/template-'. $id .'.png');
                    pdapp_delete_cache('templates', 'templates-'. $pid);
                    $removed[] = $id;
                }
            }
        }else
        {
            $post = $posts[0];
            $id = (int) $post['id'];
            $pid = (int) $post['pid'];
            if(pdapp_delete_db(PDAPP_DB_TEMPLATES, ["id"=>$id], ["%d"]))
            {
                pdapp_delete_file(PDAPP_UPLOAD_DIR .'thumbnails/templatess/template-folder-'. $id .'.png');
                pdapp_delete_cache('templates', 'folders-'. $pid);
                pdapp_delete_cache('templates', 'templates-'. $pid);
                pdapp_update_root_folders($id, 'templates');
                pdapp_delete_cache('templates', 'folders');
                $removed[] = $id;
            }
        }

        if(count($removed))
        {
            pdapp_response(0, pdapp_lang('msg.remove_success', 'admin'), $removed);
        }

        pdapp_response(1, pdapp_lang('msg.remove_error', 'admin'));
    }
}

/*
* move Temp Data
*/
add_action('wp_ajax_pdapp-move-temp', 'pdapp_move_temp');
if(!function_exists('pdapp_move_temp'))
{
    function pdapp_move_temp()
    {
        if (!pdapp_check_token(true))
        {
            pdapp_response(-1, pdapp_lang('token_error', 'system'));
        }
        if(!current_user_can(PDAPP_CAP_TEMPLATES))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $post = pdapp_post_fields(['id'=>"key", 'pid'=>"key", 'tid'=>"key", 'type'=>"text"]);
        if(!$post)
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }

        $id = (int) $post['id'];
        $pid = (int) $post['pid'];
        $tid = (int) $post['tid'];
        $type = $post['type'] == 'temp' ? 't' : 'f';
        
        if($type == 't')
        {
            if(pdapp_update_db(PDAPP_DB_TEMPLATES, ["pid"=>$tid], ["id"=>$id, "type"=>$type], ["%d"], ["%d", "%s"]))
            {
                pdapp_delete_cache('templates', 'templates-'. $pid);
                pdapp_delete_cache('templates', 'templates-'. $tid);
                pdapp_response(0, pdapp_lang('msg.move_success', 'admin'));
            }
        }else
        {
            if(pdapp_update_db(PDAPP_DB_TEMPLATES, ["pid"=>$tid], ["id"=>$id, "type"=>$type], ["%d"], ["%d", "%s"]))
            {
                pdapp_delete_cache('templates', 'folders-'. $pid);
                pdapp_delete_cache('templates', 'folders-'. $tid);
                pdapp_delete_cache('templates', 'folders');

                pdapp_response(0, pdapp_lang('msg.move_success', 'admin'));
            }
        }

        pdapp_response(1, pdapp_lang('msg.move_error', 'admin'));
    }
}

/*
* Templates
*
* get Folder
*/
add_action('wp_ajax_pdapp-temp-folders', 'pdapp_temp_folders');
if(!function_exists('pdapp_temp_folders'))
{
    function pdapp_temp_folders()
    {
        if(!current_user_can(PDAPP_CAP_TEMPLATES))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $folders = pdapp_get_template_folders();
        pdapp_response(0, "", $folders);
    }
}

/*
* Templates
*
* get Templates
*/
add_action('wp_ajax_pdapp-templates', 'pdapp_get_templates');
if(!function_exists('pdapp_get_templates'))
{
    function pdapp_get_templates()
    {
        if(!current_user_can(PDAPP_CAP_TEMPLATES))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $folderID = pdapp_get('folder');
        if($folderID == '')
        {
            $folderID = 0;
        }

        $templates = pdapp_get_cache('templates', 'templates-'. $folderID);
        if(!$templates)
        {
            $templates = [];
            global $wpdb;
            $res = $wpdb->get_results($wpdb->prepare("SELECT * FROM %i WHERE `pid`=%d AND `type`='t'", [PDAPP_DB_TEMPLATES, $folderID]), ARRAY_A);
            foreach($res as $val)
            {
                $templates[] = ["id"=>$val['id'], "pid"=>$val['pid'], "title"=>json_decode($val["title"], true), "price"=>$val['price'], "size"=>json_decode($val["size"], true), "thumb"=>$val['thumb'], "created"=>$val['created']];
            }
            pdapp_set_cache('templates', 'templates-'. $folderID, $templates);
        }

        pdapp_response(0, "", $templates);
    }
}

/*
* FONTS
*
* get Fonts
*/
add_action('wp_ajax_pdapp-fonts', 'pdapp_fonts');
if(!function_exists('pdapp_fonts'))
{
    function pdapp_fonts()
    {
        if(!current_user_can(PDAPP_CAP_ACCESS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }
        
        $setting = pdapp_get_settings(false, false, false, true, false, false);
        $listFonts = $setting['font'];
        $datas = [
            "url"=> PDAPP_GG_FONT,
            "find"=> '',
            "category"=> '',
            "fonts"=> []
        ];
        foreach($listFonts as $font)
        {
            $datas['fonts'][] = [
                "title"=>$font['title'],
                "variants"=>$font['variants'],
                "category"=>$font['category']
            ];
        }

        pdapp_response(0, "", $datas);
    }
}

/*
*
* load Font
*/
add_action('wp_ajax_pdapp-load-font', 'pdapp_load_font');
if(!function_exists('pdapp_load_font'))
{
    function pdapp_load_font()
    {
        if (!pdapp_check_token(true))
        {
            pdapp_response(-1, pdapp_lang('token_error', 'system'));
        }
        if(!current_user_can(PDAPP_CAP_ACCESS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $title = pdapp_post('title', 'text');
        if(!$title)
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }
        
        $key = str_replace(' ', '-', strtolower($title));
        $font = pdapp_get_cache('fonts', $key);

        if(!$font)
        {
            $listFonts = pdapp_get_list_fonts();
            foreach($listFonts as $res)
            {
                if($res['title'] == $title)
                {
                    $font = '';
                    foreach($res['files'] as $type=>$file)
                    {
                        if($res['category'] == 'custom')
                        {
                            $fontData = pdapp_read_file(PDAPP_PLUGIN_DIR .'assets/fonts/'. $file);
                        }else
                        {
                            $fontData = pdapp_open_url($file, 'font/truetype');
                        }
                        $fontData = base64_encode($fontData);

                        $fontWeight = ($type == 'regular') ? 'normal' : '700';
                        $font .= "@font-face{font-family: '$title';src: url(data:font/truetype;charset=utf-8;base64,$fontData) format('truetype');font-weight: $fontWeight;font-style: normal;}";
                    }
                    
                    pdapp_set_cache('fonts', $key, $font);
                }
            }
        }
        
        if($font)
		{
			pdapp_response(0, "", ["fontface"=> $font]);
		}else
		{
			pdapp_response(1, pdapp_lang('cannot_load_font', 'system'));
		}
    }
}

/*
* list addons
*/
add_action('wp_ajax_pdapp-addons', 'pdapp_addons');
if(!function_exists('pdapp_addons'))
{
    function pdapp_addons()
    {
        if(!current_user_can(PDAPP_CAP_ADDONS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }
        
        pdapp_response(0, '', []);
    }
}

/*
* list themes
*/
add_action('wp_ajax_pdapp-themes', 'pdapp_themes');
if(!function_exists('pdapp_themes'))
{
    function pdapp_themes()
    {
        if(!current_user_can(PDAPP_CAP_THEMES))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }
        
        $active = pdapp_get_theme();
        $themes = [];
        $path = PDAPP_PLUGIN_DIR .'templates';
        $folders = pdapp_list_folders($path);
        foreach($folders as $folderPath)
        {
            $file = $folderPath .'/theme.json';
            $json = pdapp_read_file($file);
            if($json)
            {
                $folder = str_replace($path. '/', '', $folderPath);
                $theme = json_decode($json, true);
                $actived = $active == $folder ? 1 : 0;
                $themes[] = ["themeID"=>$theme['themeID'], "name"=>$theme['name'], "description"=>$theme['description'], "version"=>$theme['version'], "folder"=>$folder, "active"=>$actived, "require"=>$theme['require'], "upgrade"=>''];
            }
        }
        
        pdapp_response(0, '', $themes);
    }
}

/*
* install theme
*/
add_action('wp_ajax_pdapp-install-theme', 'pdapp_install_theme');
if(!function_exists('pdapp_install_theme'))
{
    function pdapp_install_theme()
    {
        if (!pdapp_check_token(true))
        {
            pdapp_response(-1, pdapp_lang('token_error', 'system'));
        }
        if(!current_user_can(PDAPP_CAP_THEMES))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $post = pdapp_post_fields(['data'=>"text", 'type'=>"text"]);
        if(!$post)
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }
        
        $name = 'install';
        $msg = pdapp_lang('theme.install_theme_error', 'admin');
        if($post['type'] == 'update')
        {
            $name = 'update';
            $msg = pdapp_lang('theme.update_theme_error', 'admin');
        }

        global $wp_filesystem;
        $path = PDAPP_PLUGIN_DIR .'templates';
        if(!is_dir($path))
        {
            if (!wp_mkdir_p($path))
            {
                return false;
            }
        }
        $file = PDAPP_PLUGIN_DIR .'templates/theme-'. $name .'.zip';

        $zip = base64_decode($post['data']);
        pdapp_write_file($file, $zip);

        if(file_exists($file))
        {
            $check = pdapp_unzip($file, $path);
            if($check)
            {
                $wp_filesystem->delete($file);
                $msg = pdapp_lang('theme.install_theme_success', 'admin');
                if($post['type'] == 'update')
                {
                    $msg = pdapp_lang('theme.update_theme_success', 'admin');
                }
                pdapp_response(0, $msg);
            }
        }

        pdapp_response(1, $msg);
    }
}

/*
* active theme
*/
add_action('wp_ajax_pdapp-active-theme', 'pdapp_active_theme');
if(!function_exists('pdapp_active_theme'))
{
    function pdapp_active_theme()
    {
        if (!pdapp_check_token(true))
        {
            pdapp_response(-1, pdapp_lang('token_error', 'system'));
        }
        if(!current_user_can(PDAPP_CAP_THEMES))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $folder = pdapp_post('folder', 'text');
        if(!$folder)
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }

        $file = PDAPP_PLUGIN_DIR .'templates/'. $folder .'/theme.json';

        if(file_exists($file))
        {
            if(pdapp_update_db(PDAPP_DB_SETTINGS, ["values"=>$folder], ["type"=>"t"], ["%s"], ["%s"]))
            {
                pdapp_set_cache('settings', 'theme', $folder);
                pdapp_response(0, pdapp_lang('msg.actived_theme_success', 'admin'));
            }
        }

        pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
    }
}

/*
* get theme style
*/
add_action('wp_ajax_pdapp-theme-style', 'pdapp_theme_style');
if(!function_exists('pdapp_theme_style'))
{
    function pdapp_theme_style()
    {
        if(!current_user_can(PDAPP_CAP_THEMES))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $folder = pdapp_get('theme');
        if($folder == '')
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }

        $file = PDAPP_PLUGIN_DIR .'templates/'. $folder .'/assets/css/customize.css';

        if(file_exists($file))
        {
            $data = pdapp_read_file($file);
            pdapp_response(0, '', $data);
        }

        pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
    }
}

/*
* update theme style
*/
add_action('wp_ajax_pdapp-update-theme-style', 'pdapp_update_theme_style');
if(!function_exists('pdapp_update_theme_style'))
{
    function pdapp_update_theme_style()
    {
        if (!pdapp_check_token(true))
        {
            pdapp_response(-1, pdapp_lang('token_error', 'system'));
        }
        if(!current_user_can(PDAPP_CAP_THEMES))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $folder = pdapp_post('theme', 'text');
        $css = pdapp_post_textarea('style', 'text', '');
        if(!$folder)
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }

        $file = PDAPP_PLUGIN_DIR .'templates/'. $folder .'/assets/css/customize.css';

        if(file_exists($file))
        {
            pdapp_write_file($file, $css);
            pdapp_response(0, pdapp_lang('msg.update_success', 'admin'));
        }

        pdapp_response(1, pdapp_lang('msg.update_error', 'admin'));
    }
}

/*
* upgrade plugin
*/
add_action('wp_ajax_pdapp-upgrade-plugin', 'pdapp_upgrade_plugin');
if(!function_exists('pdapp_upgrade_plugin'))
{
    function pdapp_upgrade_plugin()
    {
        if (!pdapp_check_token(true))
        {
            pdapp_response(-1, pdapp_lang('token_error', 'system'));
        }
        if(!current_user_can(PDAPP_CAP_UPGRADE))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $post = pdapp_post_fields(['data'=>"text", 'version'=>"text"]);
        if(!$post)
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }

        global $wp_filesystem;
        $path = PDAPP_PLUGIN_DIR .'upgrade';
        if(!is_dir($path))
        {
            if (!wp_mkdir_p($path))
            {
                return false;
            }
        }
        $file = $path. '/update-'. $post['version'] .'.zip';

        $zip = base64_decode($post['data']);
        pdapp_write_file($file, $zip);

        if(file_exists($file))
        {
            $check = pdapp_unzip($file, PDAPP_PLUGIN_DIR);
            if($check)
            {
                $wp_filesystem->delete($file);
                $updateDB = $path. '/update-db.php';
                if(file_exists($updateDB))
                {
                    require_once($updateDB);
                    $wp_filesystem->delete($updateDB);
                }
                
                pdapp_copy_files($path. '/colors.json', PDAPP_PLUGIN_DIR .'datas/colors.json');
                pdapp_response(0, pdapp_lang('upgrade.update_success', 'admin'));
            }
        }

        pdapp_response(1, pdapp_lang('upgrade.update_error', 'admin'));
    }
}

/*
* list settings
*/
add_action('wp_ajax_pdapp-settings', 'pdapp_settings');
if(!function_exists('pdapp_settings'))
{
    function pdapp_settings()
    {
        if(!current_user_can(PDAPP_CAP_SETTINGS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $general = pdapp_get('general');
        $layout = pdapp_get('layout');
        $text = pdapp_get('text');
        $font = pdapp_get('font');
        $shape = pdapp_get('shape');
        $filter = pdapp_get('filter');
        $general = $general == 1 ? true : false;
        $layout = $layout == 1 ? true : false;
        $text = $text == 1 ? true : false;
        $font = $font == 1 ? true : false;
        $shape = $shape == 1 ? true : false;
        $filter = $filter == 1 ? true : false;

        if(!$general && !$layout && !$text && !$font && !$shape && !$filter)
        {
            $settings = pdapp_get_settings(true, true, true, true, true, true);
        }else
        {
            $settings = pdapp_get_settings($general, $layout, $text, $font, $shape, $filter);
        }
        
        pdapp_response(0, '', $settings);
    }
}

/*
* save settings
*/
add_action('wp_ajax_pdapp-save-settings', 'pdapp_save_settings');
if(!function_exists('pdapp_save_settings'))
{
    function pdapp_save_settings()
    {
        if (!pdapp_check_token(true))
        {
            pdapp_response(-1, pdapp_lang('token_error', 'system'));
        }
        if(!current_user_can(PDAPP_CAP_SETTINGS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }
        
        $type = pdapp_get('type');
        $posts = pdapp_upload_jsons('settings', ['data'=>"text"]);
        if(!$posts)
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }
        
        $post = json_decode($posts['data'], true);
        if(!is_array($post))
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }

        $check = false;
        
        if($type == 'general')
        {
            $arrs = ["heading", "body", "arc", "reversearc"];
            foreach($arrs as $arr)
            {
                if(isset($post['text']) && isset($post['text'][$arr]) && isset($post['text'][$arr]['thumb']))
                {
                    $thumb = $post['text'][$arr]['thumb'];
                    if(strpos($thumb, 'base64') !== false)
                    {
                        $imgs = explode('base64,', $thumb);
                        if(isset($imgs[1]))
                        {
                            $thumb = base64_decode($imgs[1]);
                            $name = $arr .'.png';
                            $post['text'][$arr]['thumb'] = $name;
                            pdapp_write_file(PDAPP_PLUGIN_DIR .'assets/images/texts/'. $name , $thumb);
                        }
                    }
                }
            }
            
            if(pdapp_update_db(PDAPP_DB_SETTINGS, ["values"=>pdapp_json_encode($post)], ["type"=>"sg"], ["%s"], ["%s"]))
            {
                $post = json_decode(pdapp_json_encode($post), true);
                pdapp_set_cache('settings', 'setting_general', $post);
                $check = true;
            }
        }

        if($type == 'layout')
        {
            if(pdapp_update_db(PDAPP_DB_SETTINGS, ["values"=>pdapp_json_encode($post)], ["type"=>"sl"], ["%s"], ["%s"]))
            {
                $post = json_decode(pdapp_json_encode($post), true);
                pdapp_set_cache('settings', 'setting_layout', $post);
                $check = true;
            }
        }

        if($type == 'text')
        {
            if(pdapp_update_db(PDAPP_DB_SETTINGS, ["values"=>pdapp_json_encode($post)], ["type"=>"st"], ["%s"], ["%s"]))
            {
                $post = json_decode(pdapp_json_encode($post), true);
                pdapp_set_cache('settings', 'setting_text', $post);
                $check = true;
            }
        }

        if($type == 'font')
        {
            usort($post, function ($a, $b)
            {
                return strcmp($a['title'], $b['title']);
            });

            if(pdapp_update_db(PDAPP_DB_SETTINGS, ["values"=>pdapp_json_encode($post)], ["type"=>"tf"], ["%s"], ["%s"]))
            {
                $post = json_decode(pdapp_json_encode($post), true);
                pdapp_set_cache('settings', 'setting_font', $post);
                $check = true;
            }
        }

        if($type == 'shape')
        {
            if(pdapp_update_db(PDAPP_DB_SETTINGS, ["values"=>pdapp_json_encode($post)], ["type"=>"ss"], ["%s"], ["%s"]))
            {
                $post = json_decode(pdapp_json_encode($post), true);
                pdapp_set_cache('settings', 'setting_shape', $post);
                $check = true;
            }
        }

        if($type == 'filter')
        {
            if(pdapp_update_db(PDAPP_DB_SETTINGS, ["values"=>pdapp_json_encode($post)], ["type"=>"sf"], ["%s"], ["%s"]))
            {
                $post = json_decode(pdapp_json_encode($post), true);
                pdapp_set_cache('settings', 'setting_filter', $post);
                $check = true;
            }
        }
        
        if($check)
        {
            pdapp_response(0, pdapp_lang('save_success', 'system'));
        }
        pdapp_response(1, pdapp_lang('save_error', 'system'));
    }
}

/*
* add new text template
*/
add_action('wp_ajax_pdapp-add-new-text', 'pdapp_add_new_text');
if(!function_exists('pdapp_add_new_text'))
{
    function pdapp_add_new_text()
    {
        if (!pdapp_check_token(true))
        {
            pdapp_response(-1, pdapp_lang('token_error', 'system'));
        }
        if(!current_user_can(PDAPP_CAP_SETTINGS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $post = pdapp_upload_jsons('text', ['text'=>"text", 'thumb'=>"text"]);
        if(!$post)
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }

        $text = json_decode($post['text'], true);
        $imgs = explode('base64,', $post['thumb']);
        if(isset($imgs[1]))
        {
            $thumb = base64_decode($imgs[1]);
            $name = uniqid('text_') .'.png';
            $text['thumb'] = $name;
            pdapp_write_file(PDAPP_PLUGIN_DIR .'assets/images/texts/'. $name , $thumb);
        }

        $texts = pdapp_get_settings(false, false, true, false, false, false);
        $texts['text'][] = $text;
        if(pdapp_update_db(PDAPP_DB_SETTINGS, ["values"=>pdapp_json_encode($texts['text'])], ["type"=>"st"], ["%s"], ["%s"]))
        {
            $texts['text'] = json_decode(pdapp_json_encode($texts['text']), true);
            pdapp_set_cache('settings', 'setting_text', $texts['text']);
            pdapp_response(0, pdapp_lang('save_success', 'system'), $text);
        }

        pdapp_response(1, pdapp_lang('save_error', 'system'));
    }
}

/*
* upload text template
*/
add_action('wp_ajax_pdapp-upload-text', 'pdapp_upload_text');
if(!function_exists('pdapp_upload_text'))
{
    function pdapp_upload_text()
    {
        if (!pdapp_check_token(true))
        {
            pdapp_response(-1, pdapp_lang('token_error', 'system'));
        }
        if(!current_user_can(PDAPP_CAP_SETTINGS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }
        
        $post = pdapp_upload_jsons('text', ['font'=>"text", 'text'=>"text", 'thumb'=>"text"]);
        if(!$post)
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }
        $font = json_decode($post['font'], true);
        $text = json_decode($post['text'], true);

        $imgs = explode('base64,', $post['thumb']);
        if(isset($imgs[1]))
        {
            $thumb = base64_decode($imgs[1]);
            $name = uniqid('text_') .'.png';
            $text['thumb'] = $name;
            pdapp_write_file(PDAPP_PLUGIN_DIR .'assets/images/texts/'. $name , $thumb);
        }

        $texts = pdapp_get_settings(false, false, true, false, false, false);
        $texts['text'][] = $text;
        if(pdapp_update_db(PDAPP_DB_SETTINGS, ["values"=>pdapp_json_encode($texts['text'])], ["type"=>"st"], ["%s"], ["%s"]))
        {
            $path = PDAPP_PLUGIN_DIR .'assets/fonts';
            if(!is_dir($path))
            {
                if (!wp_mkdir_p($path))
                {
                    return false;
                }
            }
            
            $listFonts = pdapp_get_list_fonts();
            $checkAdd = true;
            foreach($listFonts as $k=>$f)
            {
                if($f['title'] == $font['name'])
                {
                    $checkAdd = false;
                    break;
                }
            }

            if($checkAdd)
            {
                $fonts = explode('base64,', $font['data']);
                if(isset($fonts[1]))
                {
                    $fontData = base64_decode($fonts[1]);
                    $name = uniqid() .'.ttf';
                    pdapp_write_file($path .'/'. $name , $fontData);
                    $listFonts[] = [
                        "title"=>$font['name'],
                        "variants"=>["regular"],
                        "files"=>[
                            "regular"=>$name
                        ],
                        "category"=>"custom"
                    ];

                    usort($listFonts, function ($a, $b)
                    {
                        return strcmp($a['title'], $b['title']);
                    });
            
                    pdapp_update_db(PDAPP_DB_SETTINGS, ['values'=>pdapp_json_encode($listFonts)], ["type"=>"lf"], ["%s"], ["%s"]);
                    pdapp_delete_cache('fonts', 'list_fonts');
                }
            }
            
            $texts['text'] = json_decode(pdapp_json_encode($texts['text']), true);
            pdapp_set_cache('settings', 'setting_text', $texts['text']);
            pdapp_response(0, pdapp_lang('save_success', 'system'), $text);
        }

        pdapp_response(1, pdapp_lang('save_error', 'system'));
    }
}

/*
* upload font
*/
add_action('wp_ajax_pdapp-upload-font-file', 'pdapp_upload_font_file');
if(!function_exists('pdapp_upload_font_file'))
{
    function pdapp_upload_font_file()
    {
        if (!pdapp_check_token(true))
        {
            pdapp_response(-1, pdapp_lang('token_error', 'system'));
        }
        if(!current_user_can(PDAPP_CAP_SETTINGS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        if(!isset($_FILES['file']) || empty($_FILES['file']["name"]))
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }

        $path = PDAPP_UPLOAD_DIR .'uploads/fonts';
        $listFiles = pdapp_files_folder($path);
        foreach($listFiles as $f)
        {
            pdapp_delete_file($path .'/'. $f);
        }

        $error = pdapp_lang('upload_type_error', 'admin');
        $result = [];
        $fontface = "";
        
        $res = pdapp_upload('file', $path, ["ttf"], '', ['ttf'=>'application/x-font-ttf']);
        if($res['error'] == 0 && isset($res['filename']) && $res['filename'] != '')
        {
            $filePath = $path. '/' .$res['filename'];
            $font = pdapp_read_font_name($filePath);
            if(isset($font["title"]) && isset($font["variant"]) && $font["title"] != "" && $font["variant"] != "")
            {
                $title = $font["title"];
                $variant = strtolower($font["variant"]);

                $result = [
                    "title"=>$title,
                    "variants"=>[$variant],
                    "files"=>[
                        $variant=>$res['filename']
                    ],
                    "category"=>"custom"
                ];
                
                $fontData = pdapp_read_file($filePath);
                $fontData = base64_encode($fontData);
                $fontWeight = ($variant == 'regular' || $variant == 'italic') ? 'normal' : '700';
                $fontface = "@font-face{font-family: '$title';src: url(data:font/truetype;charset=utf-8;base64,$fontData) format('truetype');font-weight: $fontWeight;font-style: normal;}";
            }else
            {
                pdapp_delete_file($filePath);
            }
        }else
        {
            $error = $res['message'];
        }

        if(count($result))
        {
            pdapp_response(0, '', ["font"=>$result, "fontface"=>$fontface]);
        }else
        {
            pdapp_response(1, $error);
        }
    }
}

/*
* update font
*/
add_action('wp_ajax_pdapp-update-font', 'pdapp_update_font');
if(!function_exists('pdapp_update_font'))
{
    function pdapp_update_font()
    {
        if (!pdapp_check_token(true))
        {
            pdapp_response(-1, pdapp_lang('token_error', 'system'));
        }
        if(!current_user_can(PDAPP_CAP_SETTINGS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $post = pdapp_upload_jsons('font', ['font'=>"text", 'thumb'=>"text"]);
        if(!$post)
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }
        $font = json_decode($post['font'], true);
        if(!isset($font['files']))
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }

        $imgs = explode('base64,', $post['thumb']);
        if(isset($imgs[1]))
        {
            $thumb = base64_decode($imgs[1]);
            pdapp_write_file(PDAPP_PLUGIN_DIR .'assets/images/fonts/'. str_replace(' ', '', $font['title']) .'.png', $thumb);
        }
        
        global $wp_filesystem;
        $path = PDAPP_PLUGIN_DIR .'assets/fonts';
        if(!is_dir($path))
        {
            if (!wp_mkdir_p($path))
            {
                return false;
            }
        }
        
        foreach($font['files'] as $file)
        {
            $oldPath = PDAPP_UPLOAD_DIR .'uploads/fonts/'. $file;
            $pathFile = $path. '/'. $file;
            $wp_filesystem->move($oldPath, $pathFile);
        }

        $listFonts = pdapp_get_list_fonts();
        $listFonts[] = $font;

        usort($listFonts, function ($a, $b)
        {
            return strcmp($a['title'], $b['title']);
        });

        pdapp_update_db(PDAPP_DB_SETTINGS, ['values'=>pdapp_json_encode($listFonts)], ["type"=>"lf"], ["%s"], ["%s"]);
        pdapp_delete_cache('fonts', 'list_fonts');

        pdapp_response(0, '');
    }
}

/*
* upload font lib
*/
add_action('wp_ajax_pdapp-upload-font', 'pdapp_upload_font');
if(!function_exists('pdapp_upload_font'))
{
    function pdapp_upload_font()
    {
        if (!pdapp_check_token(true))
        {
            pdapp_response(-1, pdapp_lang('token_error', 'system'));
        }
        if(!current_user_can(PDAPP_CAP_SETTINGS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }
        
        $post = pdapp_upload_jsons('font', ['font'=>"text", 'thumb'=>"text"]);
        if(!$post)
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }
        
        $post['font'] = json_decode($post['font'], true);
        if(empty($post['font']['name']) || empty($post['font']['type']) || empty($post['font']['data']))
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }
        $font = $post['font'];

        $listFonts = pdapp_get_list_fonts();
        $checkAdd = true;
        foreach($listFonts as $k=>$f)
        {
            if($f['title'] == $font['name'])
            {
                $checkAdd = false;
                break;
            }
        }

        $path = PDAPP_PLUGIN_DIR .'assets/fonts';
        if(!is_dir($path))
        {
            if (!wp_mkdir_p($path))
            {
                return false;
            }
        }

        if($checkAdd)
        {
            $check = false;
            $insert = [];
            if($font['type'] == 'file')
            {
                $fonts = explode('base64,', $font['data']);
                if(isset($fonts[1]))
                {
                    $imgs = explode('base64,', $post['thumb']);
                    if(isset($imgs[1]))
                    {
                        $thumb = base64_decode($imgs[1]);
                        pdapp_write_file(PDAPP_PLUGIN_DIR .'assets/images/fonts/'. str_replace(' ', '', $font['name']) .'.png', $thumb);
                    }
                    
                    $fontData = base64_decode($fonts[1]);
                    $name = uniqid() .'.ttf';
                    pdapp_write_file($path .'/'. $name , $fontData);

                    $insert = [
                        "title"=>$font['name'],
                        "variants"=>["regular"],
                        "files"=>[
                            "regular"=>$name
                        ],
                        "category"=>"custom"
                    ];
                    $check = true;
                }
            }else if(isset($font['data']['title']) && isset($font['data']['files']))
            {
                $imgs = explode('base64,', $post['thumb']);
                if(isset($imgs[1]))
                {
                    $thumb = base64_decode($imgs[1]);
                    pdapp_write_file(PDAPP_PLUGIN_DIR .'assets/images/fonts/'. str_replace(' ', '', $font['name']) .'.png', $thumb);
                }

                $insert = $font['data'];
                $check = true;
            }

            if($check)
            {
                $listFonts[] = $insert;
                usort($listFonts, function ($a, $b)
                {
                    return strcmp($a['title'], $b['title']);
                });
        
                pdapp_update_db(PDAPP_DB_SETTINGS, ['values'=>pdapp_json_encode($listFonts)], ["type"=>"lf"], ["%s"], ["%s"]);
                pdapp_delete_cache('fonts', 'list_fonts');
                pdapp_response(0, '', $insert);
            }
        }else
        {
            pdapp_response(0, '');
        }

        pdapp_response(1, pdapp_lang('save_error', 'system'));
    }
}

/*
* get fonts
*/
add_action('wp_ajax_pdapp-list-fonts', 'pdapp_list_fonts');
if(!function_exists('pdapp_list_fonts'))
{
    function pdapp_list_fonts()
    {
        if(!current_user_can(PDAPP_CAP_SETTINGS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }
        
        $listFonts = pdapp_get_list_fonts();
        pdapp_response(0, '', $listFonts);
    }
}

/*
* upload shape
*/
add_action('wp_ajax_pdapp-upload-shape', 'pdapp_upload_shape');
if(!function_exists('pdapp_upload_shape'))
{
    function pdapp_upload_shape()
    {
        if (!pdapp_check_token(true))
        {
            pdapp_response(-1, pdapp_lang('token_error', 'system'));
        }
        if(!current_user_can(PDAPP_CAP_SETTINGS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }
        
        $post = pdapp_upload_jsons('shape', ['title'=>"text", 'value'=>"text", 'thumb'=>"text"]);
        if(!$post)
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }

        $post['value'] = json_decode($post['value'], true);
        if(empty($post['value']['size']) || empty($post['value']['paths']))
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }
        
        $slug = uniqid('shape_');
        $shape = ["title"=>$post['title'], "slug"=>$slug, "thumb"=>"", "type"=>"path", "value"=>$post['value']];
        $imgs = explode('base64,', $post['thumb']);
        if(isset($imgs[1]))
        {
            $thumb = base64_decode($imgs[1]);
            $name = $slug .'.png';
            $shape['thumb'] = $name;
            pdapp_write_file(PDAPP_PLUGIN_DIR .'assets/images/shapes/'. $name , $thumb);
        }

        $shapes = pdapp_get_settings(false, false, false, false, true, false);
        $shapes['shape'][] = $shape;
        if(pdapp_update_db(PDAPP_DB_SETTINGS, ["values"=>pdapp_json_encode($shapes['shape'])], ["type"=>"ss"], ["%s"], ["%s"]))
        {
            $shapes['shape'] = json_decode(pdapp_json_encode($shapes['shape']), true);
            pdapp_set_cache('settings', 'setting_shape', $shapes['shape']);
            pdapp_response(0, pdapp_lang('save_success', 'system'), $shape);
        }

        pdapp_response(1, pdapp_lang('save_error', 'system'));
    }
}

/*
* upload filter
*/
add_action('wp_ajax_pdapp-upload-filter', 'pdapp_upload_filter');
if(!function_exists('pdapp_upload_filter'))
{
    function pdapp_upload_filter()
    {
        if (!pdapp_check_token(true))
        {
            pdapp_response(-1, pdapp_lang('token_error', 'system'));
        }
        if(!current_user_can(PDAPP_CAP_SETTINGS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $post = pdapp_upload_jsons('filter', ['title'=>"text", 'value'=>"text"]);
        if(!$post)
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }

        $slug = uniqid('filter_');
        $filter = ["title"=>$post['title'], "slug"=>$slug, "value"=>$post['value']];

        $filters = pdapp_get_settings(false, false, false, false, false, true);
        $filters['filter'][] = $filter;
        if(pdapp_update_db(PDAPP_DB_SETTINGS, ["values"=>pdapp_json_encode($filters['filter'])], ["type"=>"sf"], ["%s"], ["%s"]))
        {
            $filters['filter'] = json_decode(pdapp_json_encode($filters['filter']), true);
            pdapp_set_cache('settings', 'setting_filter', $filters['filter']);
            pdapp_response(0, pdapp_lang('save_success', 'system'), $filter);
        }

        pdapp_response(1, pdapp_lang('save_error', 'system'));
    }
}

/*
* save translate
*/
add_action('wp_ajax_pdapp-save-translate', 'pdapp_save_translate');
if(!function_exists('pdapp_save_translate'))
{
    function pdapp_save_translate()
    {
        if (!pdapp_check_token(true))
        {
            pdapp_response(-1, pdapp_lang('token_error', 'system'));
        }
        if(!current_user_can(PDAPP_CAP_SETTINGS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }

        $post = pdapp_upload_jsons('translate', ['file'=>"text", 'code'=>"text", 'data'=>"text"]);
        if(!$post)
        {
            pdapp_response(1, pdapp_lang('forbidden_error', 'system'));
        }
        $post['data'] = pdapp_json_encode(json_decode($post['data'], true));
        
        $pathLang = PDAPP_PLUGIN_DIR .'languages/'. $post['code'].'/'.$post['file'].'.json';
        $save = pdapp_write_file($pathLang, $post['data']);
        if($save)
        {
            pdapp_response(0, pdapp_lang('save_success', 'system'));
        }
        
        pdapp_response(1, pdapp_lang('save_error', 'system'));
    }
}

/*
* remove caches
*/
add_action('wp_ajax_pdapp-remove-cache', 'pdapp_remove_cache');
if(!function_exists('pdapp_remove_cache'))
{
    function pdapp_remove_cache()
    {
        if (!pdapp_check_token(true))
        {
            pdapp_response(-1, pdapp_lang('token_error', 'system'));
        }
        if(!current_user_can(PDAPP_CAP_SETTINGS))
        {
            pdapp_response(1, pdapp_lang('msg.capability_error', 'admin'));
        }
        
        $type = pdapp_post('type', 'text', '');
        $check = false;

        if($type == 'dashboard' || $type == 'all')
        {
            $path = PDAPP_PLUGIN_DIR .'cache/dashboards';
            $files = pdapp_files_folder($path);
            foreach($files as $file)
            {
                pdapp_delete_file($path.'/'.$file);
            }
            $check = true;
        }

        if($type == 'order' || $type == 'all')
        {
            $path = PDAPP_PLUGIN_DIR .'cache/orders';
            $files = pdapp_files_folder($path);
            foreach($files as $file)
            {
                pdapp_delete_file($path.'/'.$file);
            }
            $check = true;
        }

        if($type == 'quote' || $type == 'all')
        {
            $path = PDAPP_PLUGIN_DIR .'cache/quotes';
            $files = pdapp_files_folder($path);
            foreach($files as $file)
            {
                pdapp_delete_file($path.'/'.$file);
            }
            $check = true;
        }

        if($type == 'product' || $type == 'all')
        {
            $path = PDAPP_PLUGIN_DIR .'cache/products';
            $files = pdapp_files_folder($path);
            foreach($files as $file)
            {
                pdapp_delete_file($path.'/'.$file);
            }

            $path = PDAPP_PLUGIN_DIR .'cache/designs';
            $files = pdapp_files_folder($path);
            foreach($files as $file)
            {
                pdapp_delete_file($path.'/'.$file);
            }

            $path = PDAPP_PLUGIN_DIR .'cache/woos';
            $files = pdapp_files_folder($path);
            foreach($files as $file)
            {
                pdapp_delete_file($path.'/'.$file);
            }
            $check = true;
        }

        if($type == 'art' || $type == 'all')
        {
            $path = PDAPP_PLUGIN_DIR .'cache/arts';
            $files = pdapp_files_folder($path);
            foreach($files as $file)
            {
                pdapp_delete_file($path.'/'.$file);
            }
            $check = true;
        }

        if($type == 'template' || $type == 'all')
        {
            $path = PDAPP_PLUGIN_DIR .'cache/templates';
            $files = pdapp_files_folder($path);
            foreach($files as $file)
            {
                pdapp_delete_file($path.'/'.$file);
            }
            $check = true;
        }

        if($type == 'print' || $type == 'all')
        {
            $path = PDAPP_PLUGIN_DIR .'cache/prints';
            $files = pdapp_files_folder($path);
            foreach($files as $file)
            {
                pdapp_delete_file($path.'/'.$file);
            }
            $check = true;
        }

        if($type == 'font' || $type == 'all')
        {
            $path = PDAPP_PLUGIN_DIR .'cache/fonts';
            $files = pdapp_files_folder($path);
            foreach($files as $file)
            {
                pdapp_delete_file($path.'/'.$file);
            }
            $check = true;
        }
        
        if($type == 'setting' || $type == 'all')
        {
            $path = PDAPP_PLUGIN_DIR .'cache/settings';
            $files = pdapp_files_folder($path);
            foreach($files as $file)
            {
                pdapp_delete_file($path.'/'.$file);
            }
            $check = true;
        }
        
        if($type == 'woo' || $type == 'all')
        {
            $path = PDAPP_PLUGIN_DIR .'cache/woos';
            $files = pdapp_files_folder($path);
            foreach($files as $file)
            {
                pdapp_delete_file($path.'/'.$file);
            }
            $check = true;
        }
        
        if($check)
        {
            pdapp_response(0, pdapp_lang('msg.removed_cache', 'admin'));
        }
        pdapp_response(1, pdapp_lang('msg.remove_cache_error', 'admin'));
    }
}
?>