<?php

/**
 * @package safi
 */
namespace WPJoli\SAFI\Controllers;

use WPJoli\SAFI\Application;
class TemplatesControllerV2 {
    private $tpl_opt;

    //Wordpress setting name containing our templates in JSON
    private $screenshot_tpl_opt;

    //Wordpress setting name containing our templates in JSON
    protected $templates;

    protected $screenshots;

    public function __construct() {
        // $this->tpl_opt = Application::TEMPLATES_OPT;
        // $this->screenshot_tpl_opt = Application::SCREENSHOT_TEMPLATES_OPT;
        // $this->templates = $this->pullTemplates();
        // $this->screenshots = $this->pullTemplatesScreenshots();
    }

    public function init() {
        // $this->tpl_opt = Application::TEMPLATES_OPT;
        // $this->screenshot_tpl_opt = Application::SCREENSHOT_TEMPLATES_OPT;
        // $this->templates = $this->pullTemplates();
        // $this->screenshots = $this->pullTemplatesScreenshots();
    }

    public function ajaxTemplatesRouteAction() {
        // SAFI()->log('ajaxTemplatesRouteAction--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------');
        check_ajax_referer( 'SAFITemplateEditor', 'nonce' );
        $command = safi_sanitize_command( sanitize_key( safi_sanitize_var( $_POST['command'] ) ) );
        if ( !$command ) {
            die;
        }
        $tplid = safi_sanitize_template_id( sanitize_key( safi_sanitize_var( $_POST['tplid'] ) ) );
        if ( $command === 'duplicate' || $command === 'import' ) {
            //do nothing but skip the next elseif check
        } else {
            if ( $command !== 'reorder' && $tplid === false ) {
                //tplid not passed for command 'reorder'
                die;
            }
        }
        $data = ( isset( $_POST['data'] ) ? json_decode( stripslashes( $_POST['data'] ), true ) : null );
        if ( $command === 'save' || $command === 'update' || $command === 'import' ) {
            if ( !$data ) {
                die;
            }
        }
        // SAFI()->log($data);
        //Sanitizes canvas data
        if ( isset( $data['canvas'] ) ) {
            array_walk_recursive( $data['canvas'], function ( &$value, $key ) {
                switch ( $key ) {
                    case 'googleFonts':
                        $value = filter_var( $value, FILTER_DEFAULT );
                        break;
                    case 'templateName':
                        $value = sanitize_text_field( $value );
                        break;
                    case 'width':
                    case 'height':
                        $value = filter_var( (int) $value, FILTER_DEFAULT, array(
                            'filter'  => FILTER_VALIDATE_INT,
                            'options' => array(
                                'min_range' => 1,
                                'max_range' => 5000,
                            ),
                        ) );
                        break;
                    case 'backgroundColor':
                        $value = sanitize_text_field( $value );
                        break;
                    case 'zoom':
                        $value = filter_var( (float) $value, FILTER_DEFAULT, array(
                            'filter'  => FILTER_VALIDATE_FLOAT,
                            'options' => array(
                                'min_range' => 0.1,
                                'max_range' => 10,
                            ),
                        ) );
                        break;
                    case 'gridSize':
                        $value = filter_var( (int) $value, FILTER_DEFAULT, array(
                            'filter'  => FILTER_VALIDATE_INT,
                            'options' => array(
                                'min_range' => 0,
                                'max_range' => 5000,
                            ),
                        ) );
                        break;
                    case 'globalCss':
                        // $value = filter_var($value, FILTER_CALLBACK, array('options' => 'sanitize_textarea_field'));
                        $value = ( $value === null ? null : sanitize_textarea_field( $value ) );
                }
            } );
        }
        //Sanitizes tree data
        if ( isset( $data['tree'] ) ) {
            // $data['tree'] = filter_var($data['tree'], FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
            $data['tree'] = ( is_array( $data['tree'] ) ? $data['tree'] : null );
        }
        //Sanitizes canvas data
        if ( isset( $data['elements'] ) ) {
            foreach ( $data['elements'] as &$element ) {
                // Filter base props
                if ( isset( $element['type'] ) ) {
                    $element['type'] = sanitize_key( $element['type'] );
                }
                if ( isset( $element['id'] ) ) {
                    $element['id'] = sanitize_key( $element['id'] );
                }
                if ( isset( $element['label'] ) ) {
                    $element['label'] = sanitize_text_field( $element['label'] );
                }
                if ( isset( $element['width'] ) ) {
                    $element['width'] = filter_var( (float) $element['width'], FILTER_DEFAULT, array(
                        'filter' => FILTER_VALIDATE_FLOAT,
                    ) );
                }
                if ( isset( $element['height'] ) ) {
                    $element['height'] = filter_var( (float) $element['height'], FILTER_DEFAULT, array(
                        'filter' => FILTER_VALIDATE_FLOAT,
                    ) );
                }
                if ( isset( $element['x'] ) ) {
                    $element['x'] = filter_var( (float) $element['x'], FILTER_DEFAULT, array(
                        'filter' => FILTER_VALIDATE_FLOAT,
                    ) );
                }
                if ( isset( $element['y'] ) ) {
                    $element['y'] = filter_var( (float) $element['y'], FILTER_DEFAULT, array(
                        'filter' => FILTER_VALIDATE_FLOAT,
                    ) );
                }
                if ( isset( $element['angle'] ) ) {
                    $element['angle'] = filter_var( (float) $element['angle'], FILTER_DEFAULT, array(
                        'filter'  => FILTER_VALIDATE_FLOAT,
                        'options' => array(
                            'min_range' => -360,
                            'max_range' => 360,
                        ),
                    ) );
                }
                if ( isset( $element['opacity'] ) ) {
                    $element['opacity'] = filter_var( (float) $element['opacity'], FILTER_DEFAULT, array(
                        'filter'  => FILTER_VALIDATE_FLOAT,
                        'options' => array(
                            'min_range' => 0,
                            'max_range' => 1,
                        ),
                    ) );
                }
                if ( isset( $element['classes'] ) ) {
                    $element['classes'] = sanitize_text_field( $element['classes'] );
                }
                if ( isset( $element['customCss'] ) ) {
                    $element['customCss'] = ( $element['customCss'] === null ? null : sanitize_textarea_field( $element['customCss'] ) );
                }
                //     };
                // SAFI()->log($element['type']);
                //filter type specific props
                if ( $element['type'] === 'image' ) {
                    if ( isset( $element['sourceType'] ) ) {
                        $element['sourceType'] = ( $element['sourceType'] === null ? null : sanitize_key( $element['sourceType'] ) );
                    }
                    if ( isset( $element['srcUrl'] ) ) {
                        $element['srcUrl'] = ( $element['srcUrl'] === null ? null : sanitize_url( $element['srcUrl'] ) );
                    }
                    if ( isset( $element['srcMedia'] ) ) {
                        $element['srcMedia'] = ( $element['srcMedia'] === null ? null : sanitize_url( $element['srcMedia'] ) );
                    }
                    if ( isset( $element['fit'] ) ) {
                        $element['fit'] = ( $element['fit'] === null ? null : sanitize_text_field( $element['fit'] ) );
                    }
                } else {
                    if ( $element['type'] === 'condition' ) {
                        if ( isset( $element['compareWith'] ) ) {
                            $element['compareWith'] = ( $element['compareWith'] === null ? null : sanitize_text_field( $element['compareWith'] ) );
                        }
                        if ( isset( $element['compareOperator'] ) ) {
                            $element['compareOperator'] = sanitize_text_field( $element['compareOperator'] );
                        }
                        if ( isset( $element['compareValue'] ) ) {
                            $element['compareValue'] = sanitize_text_field( $element['compareValue'] );
                        }
                    } else {
                        if ( $element['type'] === 'text' ) {
                            if ( isset( $element['text'] ) ) {
                                $allowed_html = array(
                                    'br'     => array(),
                                    'em'     => array(),
                                    'strong' => array(),
                                    'style'  => array(),
                                );
                                // SAFI()->log($element['text']);
                                // Kill evil script
                                $element['text'] = wp_kses( $element['text'], $allowed_html );
                                // But still decode the HTML entities because wp_kses is turning them into &amp;
                                // It is safe to do so because wp_kses will be re applied upon building the HTML template
                                // Otherwise, when editing an exisiting template, it is likely to show up as &amp;
                                $element['text'] = html_entity_decode( $element['text'] );
                                // SAFI()->log($element['text']);
                            }
                        }
                    }
                }
            }
        }
        // array_walk_recursive($data['elements'], function (&$value, $key) {
        //     // SAFI()->log($key);
        //     // SAFI()->log($value);
        //     switch ($key) {
        //         // case 'width':
        //         // case 'height':
        //         //     $value = filter_var((float) $value, FILTER_DEFAULT, array(
        //         //         'filter'    => FILTER_VALIDATE_FLOAT,
        //         //         'options'   => array('min_range' => 1, 'max_range' => 5000)
        //         //     ));
        //         //     break;
        //         case 'x':
        //         case 'y':
        //             $value = filter_var((float) $value, FILTER_DEFAULT, array(
        //                 'filter'    => FILTER_VALIDATE_FLOAT,
        //                 'options'   => array('min_range' => 0, 'max_range' => 5000)
        //             ));
        //             break;
        //         case 'color':
        //         case 'backgroundColor':
        //             $value = sanitize_text_field($value);
        //             break;
        //         case 'customCss':
        //             // $value = filter_var($value, FILTER_CALLBACK, array('options' => 'sanitize_textarea_field'));
        //             $value = $value === null ? null : sanitize_textarea_field($value);
        //     }
        // });
        //Sanatizes theroot  template data
        // array_walk($data, function (&$value, $key) {
        //     // SAFI()->log($key);
        //     // SAFI()->log($value);
        //     switch ($key) {
        //             // case 'elements':
        //             //     $value = filter_var($value, FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
        //             //     break;
        //         case 'tree':
        //             $value = filter_var($value, FILTER_CALLBACK, array(
        //                 'options' => 'sanitize_key',
        //                 'flags' => FILTER_REQUIRE_ARRAY,
        //             ));
        //             break;
        //     }
        // });
        // array_walk_recursive($data, function (&$value, $key) {
        //     // SAFI()->log($key);
        //     // SAFI()->log($value);
        //     switch ($key) {
        //         case 'googleFonts':
        //             $value = filter_var($value, FILTER_DEFAULT);
        //             break;
        //         case 'templateName':
        //             $value = sanitize_text_field($value);
        //             break;
        //         case 'width':
        //         case 'height':
        //             $value = filter_var((int) $value, FILTER_DEFAULT, array(
        //                 'filter'    => FILTER_VALIDATE_INT,
        //                 'options'   => array('min_range' => 1, 'max_range' => 5000)
        //             ));
        //             break;
        //         case 'x':
        //         case 'y':
        //             $value = filter_var((float) $value, FILTER_DEFAULT, array(
        //                 'filter'    => FILTER_VALIDATE_FLOAT,
        //                 'options'   => array('min_range' => 0, 'max_range' => 5000)
        //             ));
        //             break;
        //         case 'backgroundColor':
        //             $value = sanitize_text_field($value);
        //             break;
        //         case 'zoom':
        //             $value = filter_var((float) $value, FILTER_DEFAULT, array(
        //                 'filter'    => FILTER_VALIDATE_FLOAT,
        //                 'options'   => array('min_range' => 0.1, 'max_range' => 10) // zoom between 10 & 1000%
        //             ));
        //             break;
        //         case 'gridSize':
        //             $value = filter_var((int) $value, FILTER_DEFAULT, array(
        //                 'filter'    => FILTER_VALIDATE_INT,
        //                 'options'   => array('min_range' => 0, 'max_range' => 5000)
        //             ));
        //             break;
        //         case 'globalCss':
        //             // $value = filter_var($value, FILTER_CALLBACK, array('options' => 'sanitize_textarea_field'));
        //             $value = $value === null ? null : sanitize_textarea_field($value);
        //     }
        // });
        // SAFI()->log('-------------------------------------------');
        // SAFI()->log($data);
        // SAFI()->log('--------------------END-----------------------');
        // wp_send_json_success();
        // die;
        $screenshot = ( safi_is_screenshot_data_valid( safi_sanitize_var( $_POST['screenshot'] ) ) ? stripslashes( $_POST['screenshot'] ) : false );
        if ( $command === 'save' || $command === 'update' ) {
            if ( $screenshot === false ) {
                die;
            }
        }
        //SAVE
        if ( $command == 'save' ) {
            //id == 0 ? then it's a new template
            if ( $tplid == 0 ) {
                //Adds the new template to the collection
                $new_id = $this->addTemplate( $data, $screenshot );
                if ( $new_id !== false ) {
                    wp_send_json_success( [
                        'id' => $new_id,
                    ] );
                }
            }
        } else {
            if ( $command == 'duplicate' ) {
                //id == 0 ? then it's a new template
                //Adds the new template to the collection
                $new_id = $this->duplicateTemplate( $data, $tplid );
                if ( $new_id !== false ) {
                    wp_send_json_success( [
                        'id' => $new_id,
                    ] );
                }
            } else {
                if ( $command == 'reorder' ) {
                    //id == 0 ? then it's a new template
                    //Adds the new template to the collection
                    $response = $this->reorderTemplates( $data, $tplid );
                    wp_send_json_success( [
                        'reordered' => $response,
                    ] );
                } else {
                    if ( $command == 'import' ) {
                        //Adds the new template to the collection
                        $new_id = $this->importTemplate( $data );
                        if ( $new_id !== false ) {
                            wp_send_json_success( [
                                'id' => $new_id,
                            ] );
                        } else {
                            wp_send_json_error( [
                                'message' => 'Error while importing, make sure the template does not already exist',
                            ] );
                        }
                    } else {
                        if ( $command == 'update' ) {
                            //A normal template
                            if ( $tplid != -1 ) {
                                //Updates the current template
                                $added = $this->updateTemplate( $tplid, $data, $screenshot );
                                //true or false
                                wp_send_json_success( [
                                    'updated' => $added,
                                ] );
                            }
                        } else {
                            if ( $command == 'delete' ) {
                                //A normal template
                                if ( $tplid != -1 ) {
                                    $deleted = $this->deleteTemplate( $tplid );
                                    wp_send_json_success( [
                                        'deleted' => true,
                                    ] );
                                    //Updates the current template
                                    //true or false
                                    wp_send_json_success( [
                                        'deleted' => $deleted,
                                    ] );
                                }
                            }
                        }
                    }
                }
            }
        }
        // sleep(2);
        wp_send_json_success( $data );
        die;
    }

    /**
     * Creates a thumbnail png image of the full template image text data and writes it to the WP_UPLOAD_DIR/safi-thumbnails/
     *
     * @param [type] $tplid template ID used for the filename
     * @param [string] $screenshot base64 image data
     * @return mixed filename on success, false on failure
     */
    private function createTemplateThumbnail( $tplid, $screenshot ) {
        $data = base64_decode( substr( $screenshot, strlen( "data:image/png;base64," ) ) );
        $src = imagecreatefromstring( $data );
        if ( !$src ) {
            return false;
        }
        $size = 500;
        $width = imagesx( $src );
        $height = imagesy( $src );
        $aspect_ratio = $height / $width;
        if ( $width <= $size ) {
            $new_w = $width;
            $new_h = $height;
        } else {
            $new_w = $size;
            $new_h = abs( $new_w * $aspect_ratio );
        }
        // Create new image
        $img = imagecreatetruecolor( $new_w, $new_h );
        imagesetinterpolation( $img );
        // For PNG with transparency, fill background white before resampling
        $white = imagecolorallocate(
            $img,
            255,
            255,
            255
        );
        imagefill(
            $img,
            0,
            0,
            $white
        );
        // Resize
        imagecopyresampled(
            $img,
            $src,
            0,
            0,
            0,
            0,
            $new_w,
            $new_h,
            $width,
            $height
        );
        $dir = SAFI_TEMPLATE_THUMB_DIR;
        if ( !is_dir( $dir ) ) {
            wp_mkdir_p( $dir );
        }
        // --- Save PNG ---
        $png_filename = "template-{$tplid}.png";
        $png_path = $dir . $png_filename;
        ob_start();
        imagepng( $img );
        $png_data = ob_get_clean();
        file_put_contents( $png_path, $png_data );
        // --- Save JPG ---
        if ( apply_filters( 'safi_templates_save_jpg', false ) ) {
            $jpg_filename = "template-{$tplid}.jpg";
            $jpg_path = $dir . $jpg_filename;
            imagejpeg( $img, $jpg_path, apply_filters( 'safi_templates_save_jpg_quality', 70 ) );
            // quality = 70
        }
        // --- Save WebP ---
        if ( function_exists( 'imagewebp' ) && apply_filters( 'safi_templates_save_webp', false ) ) {
            $webp_filename = "template-{$tplid}.webp";
            $webp_path = $dir . $webp_filename;
            imagewebp( $img, $webp_path, apply_filters( 'safi_templates_save_webp_quality', 70 ) );
            // quality = 80
        }
        imagedestroy( $img );
        imagedestroy( $src );
        // Return PNG filename (main format)
        return $png_filename;
    }

    private function copyTemplateThumbnail( $tplid, $template_src_id ) {
        if ( !$template_src_id ) {
            return false;
        }
        $dir = SAFI_TEMPLATE_THUMB_DIR;
        if ( !is_dir( $dir ) ) {
            // dir doesn't exist, make it
            wp_mkdir_p( $dir );
        }
        $image_filename_src = "template-{$template_src_id}.png";
        $image_filename = "template-{$tplid}.png";
        if ( false !== copy( $dir . $image_filename_src, $dir . $image_filename ) ) {
            return $image_filename;
        }
        return false;
    }

    private function deleteTemplateThumbnail( $tplid ) {
        if ( !$tplid ) {
            return false;
        }
        $dir = SAFI_TEMPLATE_THUMB_DIR;
        $image_filename = "template-{$tplid}.png";
        return unlink( $dir . $image_filename );
    }

    public function pullTemplatesV1() {
        $templates = get_option( Application::TEMPLATES_OPT );
        if ( !$templates ) {
            return [];
        }
        //returns templates as an array
        $templates = json_decode( $templates, true );
        return $templates;
    }

    public function pullTemplatesScreenshotsV1() {
        $templates = get_option( Application::SCREENSHOT_TEMPLATES_OPT );
        if ( !$templates ) {
            return [];
        }
        //returns templates as an array
        $templates = json_decode( $templates, true );
        return $templates;
    }

    /**
     * Turn the templates database options into single individuals template cutom post types
     *
     * @return void
     */
    public function migrateTemplates() {
        $templates = $this->pullTemplatesV1();
        // $screenshots = $this->pullTemplatesScreenshotsV1();
        if ( !$templates ) {
            return;
        }
        $migrated = [];
        $errors = [];
        foreach ( $templates as $template ) {
            $uid = $template['id'];
            $result = $this->insertTemplate( $template );
            if ( $result ) {
                $migrated[$uid] = $template['name'];
            } else {
                $errors[$uid] = $template['name'];
            }
        }
        return [
            'migrated' => $migrated,
            'errors'   => $errors,
        ];
    }

    //fetches templates from the database
    public function pullTemplates( &$screenshots_out = null ) {
        // WP Query on our custom post type
        // Order by meta field "safi_index"
        $template_posts = get_posts( [
            'post_type'              => Application::POST_TYPE_TEMPLATE,
            'post_status'            => 'any',
            'numberposts'            => -1,
            'orderby'                => 'meta_value_num',
            'order'                  => 'ASC',
            'meta_key'               => 'safi_index',
            'update_post_meta_cache' => true,
        ] );
        // Filter out posts whose post_name is safi_post_name('00000000')
        $template_posts = array_filter( $template_posts, function ( $post ) {
            return $post->post_name !== safi_post_name( '00000000' );
        } );
        // Delete all posts from $template_posts with wp_delete_post
        // foreach ($template_posts as $post) {
        //     wp_delete_post($post->ID, true);
        // }
        // SAFI()->log(print_r($template_posts, true));
        // $templates = array_map(function ($post) {
        //     return json_decode($post->post_content, true);
        // }, $template_posts);
        $templates = [];
        $templates_screenshots = [];
        foreach ( $template_posts as $post ) {
            // $template = json_decode($post->post_content, true);
            $template = json_decode( base64_decode( $post->post_content ), true );
            // $template = json_decode(stripslashes($post->post_content), true);
            if ( !$template ) {
                continue;
            }
            // SAFI()->log(($template));
            $templates[] = $template;
            $screenshot = get_post_meta( $post->ID, 'safi_screenshot', true );
            $templates_screenshots[safi_post_name( $post->post_name )] = $screenshot;
        }
        $screenshots_out = $templates_screenshots;
        return $templates;
    }

    //fetches templates thumbsfrom the database
    public function pullTemplatesScreenshots() {
        $templates = get_option( $this->screenshot_tpl_opt );
        if ( !$templates ) {
            return [];
        }
        //returns templates as an array
        $templates = json_decode( $templates, true );
        return $templates;
    }

    //updates templates to the database
    public function pushTemplates() {
        $dbpush = update_option( $this->tpl_opt, json_encode( $this->templates ), false );
        return $dbpush;
    }

    //updates templates to the database
    public function pushTemplatesScreenshots() {
        return update_option( $this->screenshot_tpl_opt, json_encode( $this->screenshots ), false );
    }

    /**
     * Get templates from the database
     *
     * @param boolean $simple_listing returns only the list of templates nameID => name without the actual templates
     * @return void
     */
    public function getTemplates( $simple_listing = false ) {
        $templates = $this->pullTemplates();
        if ( $simple_listing ) {
            $template_list = [];
            //Populates the template array with id => name
            foreach ( $templates as $item ) {
                $template_list[$item['id']] = $item['name'];
            }
            return $template_list;
        }
        return $templates;
    }

    public function getTemplateById( $id ) {
        return safi_array_find( $id, 'id', $this->templates );
    }

    /**
     * Inserts a template in the template array and updates the database
     *
     * @param [type] $template JSON template
     * @return void
     */
    public function addTemplate( $template, $screenshot ) {
        if ( !$template ) {
            return;
        }
        //Creates a unique key
        $uid = safi_generate_uid();
        //prepares the data
        $data = [
            'id'      => $uid,
            'name'    => $template['canvas']['templateName'],
            'content' => $template,
        ];
        // $this->templates[] = $data;
        /**
         * Meta fields for this post type:
         * - safi_id
         * - safi_index: 
         * - safi_screenshot
         */
        // Let's create the screenshot
        $screenshot_filename = $this->createTemplateThumbnail( $uid, $screenshot );
        //returns the new id on success
        return $this->insertTemplate( $data, $screenshot_filename );
    }

    /**
     * Inserts a template in the template array and updates the database
     *
     * @param [type] $template JSON template
     * @return void
     */
    public function duplicateTemplate( $template, $template_src_id ) {
        if ( !$template ) {
            return;
        }
        //Creates a unique key
        $uid = safi_generate_uid();
        //prepares the data
        $data = [
            'id'      => $uid,
            'name'    => $template['canvas']['templateName'],
            'content' => $template,
        ];
        $screenshot_filename = $this->copyTemplateThumbnail( $uid, $template_src_id );
        return $this->insertTemplate( $data, $screenshot_filename );
    }

    public function insertTemplate( $data, $screenshot_filename = null ) {
        // safi_index will be used to order the templates. It will be set to the last index + 1 (we need to count the existing templates with a wp query)
        // $query = new \WP_Query([
        //     'post_type' => Application::POST_TYPE_TEMPLATE,
        //     'posts_per_page' => -1,
        //     'fields' => 'ids'
        // ]);
        // $safi_index = count($query->posts) + 1;
        // find the max value from "safi_index" meta field in the postmeta table
        global $wpdb;
        if ( empty( $data['id'] ) ) {
            return;
        }
        $uid = $data['id'];
        $max_index = $wpdb->get_var( "\r\n            SELECT MAX(CAST(meta_value AS UNSIGNED))\r\n            FROM {$wpdb->postmeta}\r\n            WHERE meta_key = 'safi_index'\r\n        " );
        $metas = [
            'safi_index' => $max_index + 1,
            'safi_size'  => [
                'width'  => $data['content']['canvas']['width'],
                'height' => $data['content']['canvas']['height'],
            ],
        ];
        if ( $screenshot_filename ) {
            $metas['safi_screenshot'] = $screenshot_filename;
        }
        // Add a new post of type Application::instance()::POST_TYPE_TEMPLATE
        $post_id = wp_insert_post( [
            'post_title'   => $data['name'],
            'post_name'    => safi_post_name( $uid ),
            'post_type'    => Application::POST_TYPE_TEMPLATE,
            'post_status'  => apply_filters( 'safi_default_post_status', 'publish' ),
            'post_content' => base64_encode( wp_json_encode( $data ) ),
            'meta_input'   => $metas,
        ] );
        if ( !$post_id ) {
            return;
        }
        //returns the new id on success
        return $uid;
    }

    /**
     * Inserts a template in the template array and updates the database
     *
     * @param [type] $template JSON template
     * @return void
     */
    public function importTemplate( $template ) {
        if ( !$template ) {
            return;
        }
        //Creates a unique key
        $uid = $template['id'];
        //checks if there is already a template with the provided ID
        $post = $this->getTemplatePostBySlug( safi_post_name( $uid ) );
        if ( $post ) {
            return false;
        }
        return $this->insertTemplate( $template );
    }

    /**
     * Undocumented function
     *
     * @param Array $order collection of ids in the specified order
     * @return void
     */
    public function reorderTemplates( $order ) {
        if ( !$order ) {
            return false;
        }
        $total = count( $order );
        // SAFI()->log($order);
        // save the start time
        // $start_time = microtime(true);
        for ($i = 1; $i < $total + 1; $i++) {
            // Find the post
            $post = $this->getTemplatePostBySlug( safi_post_name( $order[$i - 1] ) );
            // SAFI()->log($order[$i - 1]);
            // SAFI()->log($post->post_title);
            // SAFI()->log($post->ID);
            // SAFI()->log($i);
            // // Update the post meta
            // SAFI()->log(get_post_meta($post->ID, 'safi_index', true));
            update_post_meta( $post->ID, 'safi_index', $i );
            // SAFI()->log(update_post_meta($post->ID, 'safi_index', $i));
        }
        // $end_time = microtime(true);
        // $execution_time = $end_time - $start_time;
        // error_log($execution_time);
        return true;
    }

    /**
     * Updates an existing template
     *
     * @param [type] $tplid template id
     * @param [type] $content
     * @param [type] $screenshot base64 image data for the template thumbnail
     * @return void
     */
    public function updateTemplate( $uid, $content, $screenshot ) {
        $post = $this->getPostFromTemplateId( $uid );
        if ( !$post ) {
            return false;
        }
        $post_id = $post->ID;
        $data = [
            'id'            => $uid,
            'name'          => $content['canvas']['templateName'],
            'content'       => $content,
            'last_modified' => time(),
        ];
        // SAFI()->log(print_r($data, true));
        $screenshot_filename = $this->createTemplateThumbnail( $uid, $screenshot );
        // Add a new post of type Application::instance()::POST_TYPE_TEMPLATE
        $post_id = wp_update_post( [
            'ID'           => $post_id,
            'post_title'   => $content['canvas']['templateName'],
            'post_type'    => Application::POST_TYPE_TEMPLATE,
            'post_content' => base64_encode( wp_json_encode( $data ) ),
            'meta_input'   => [
                'safi_screenshot' => $screenshot_filename,
                'safi_size'       => [
                    'width'  => $content['canvas']['width'],
                    'height' => $content['canvas']['height'],
                ],
            ],
        ], true );
        if ( is_wp_error( $post_id ) ) {
            SAFI()->log( $post_id->get_error_message() );
        }
        SAFI()->log( $post_id );
        if ( !$post_id ) {
            return false;
        }
        //returns the new id on success
        return true;
    }

    public function getJsonTemplate( $uid ) {
        $post = $this->getPostFromTemplateId( $uid );
        if ( !$post ) {
            return false;
        }
        return json_decode( base64_decode( $post->post_content ), true );
    }

    public function getPostFromTemplateId( $uid ) {
        $post_name = safi_post_name( $uid );
        return $this->getTemplatePostBySlug( $post_name );
    }

    public function getTemplatePostBySlug( $slug ) {
        $post = get_page_by_path( $slug, OBJECT, Application::POST_TYPE_TEMPLATE );
        return $post;
    }

    public function deleteTemplate( $tplid ) {
        if ( !$tplid ) {
            return false;
        }
        $post = $this->getPostFromTemplateId( $tplid );
        if ( !$post ) {
            return false;
        }
        $deleted = wp_delete_post( $post->ID, true );
        if ( !$deleted ) {
            return false;
        }
        $thumbnail_deleted = $this->deleteTemplateThumbnail( $tplid );
        return true;
    }

    /**
     * Fetches the starter templates that are present in the templates/ folder
     *
     * @return array
     */
    public function getStarterTemplates() {
        $demo_templates_path = SAFI()->path( 'templates' );
        $demo_templates_url = SAFI()->url( 'templates' );
        if ( !is_dir( $demo_templates_path ) ) {
            return false;
        }
        $files = scandir( $demo_templates_path );
        if ( !count( $files ) > 0 ) {
            return false;
        }
        $templates = [];
        foreach ( $files as $file ) {
            if ( safi_str_ends_with( $file, '.safi.json' ) !== true ) {
                continue;
            }
            if ( $file == '.' || $file == '..' || $file == 'pro' ) {
                continue;
            }
            // $file = 'template-88c6f003-library.safi.json'
            $regex = preg_match( '/template-([0-9a-f]+)/', $file, $matches );
            if ( $regex === false || sizeof( $matches ) !== 2 ) {
                continue;
            }
            //$matches = ["template-88c6f003","88c6f003"]
            $template_id = $matches[1];
            // $theme_json_path = $demo_templates_path . '/' . $file . '/' . $file . '.safi.json';
            // $theme_thumb_path = $demo_templates_path . '/' . $file . '/' . 'thumbnail.jpg';
            // $theme_thumb_url = $demo_templates_url . '/' . $file . '/' . 'thumbnail.jpg';
            $theme_json_path = $demo_templates_path . '/' . $file;
            $theme_thumb_path = $demo_templates_path . '/' . 'template-' . $template_id . '.jpg';
            $theme_thumb_url = $demo_templates_url . '/' . 'template-' . $template_id . '.jpg';
            //make sure the file exists
            if ( !is_file( $theme_json_path ) ) {
                continue;
            }
            $template = json_decode( file_get_contents( $theme_json_path ), true );
            //on parsing failure, skip this tmeplate
            if ( !$template ) {
                continue;
            }
            $template = [
                'id'        => $template_id,
                'template'  => $template,
                'thumbnail' => ( is_file( $theme_thumb_path ) ? $theme_thumb_url : null ),
                'order'     => ( safi_sanitize_var( $template['order'] ) ? $template['order'] : 100000 ),
            ];
            // SAFI()->log($template);
            // exit;
            // $template =
            //     'id' => $file,
            //     'template' => $template,
            //     'thumbnail' => is_file($theme_thumb_path) ? $theme_thumb_url : null,
            // ];
            //Adds the current theme to the csutom themes array
            $templates[] = $template;
        }
        // if (safi_xy()->can_use_premium_code__premium_only()) {
        //     $tpl_pro = $this->getStarterTemplatesPro__premium_only();
        //     if (is_array($tpl_pro)) {
        //         $templates =  array_merge($templates, $tpl_pro);
        //     }
        // }
        return $templates;
    }

}
