<?php

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

if(!class_exists('acfe_script_import_posts')):

class acfe_script_import_posts extends acfe_script{
    
    /*
     * Init
     */
    function initialize(){
        
        $this->name         = 'import_posts';
        $this->title        = 'Example: Import Posts';
        $this->description  = 'Import posts from a json file generated by the ACF Extended Export script';
        $this->recursive    = true;
        $this->category     = 'Data';
        $this->author       = 'ACF Extended';
        $this->link         = 'https://www.acf-extended.com';
        $this->version      = '1.0';
        
        $this->field_groups = array(
    
            array(
                'title'             => 'Settings',
                'key'               => 'group_acfe_import_posts',
                'position'          => 'side',
                'label_placement'   => 'top',
                'fields'            => array(
            
                    array(
                        'label'             => 'File',
                        'name'              => 'file',
                        'type'              => 'file',
                        'instructions'      => '',
                        'required'          => true,
                        'uploader'          => 'wp',
                        'mime_types'        => '.json',
                        'preview_style'     => 'inline',
                    ),
            
                    array(
                        'label'             => 'Update',
                        'name'              => 'update',
                        'type'              => 'true_false',
                        'instructions'      => '',
                        'message'           => 'Update existing posts',
                    ),
            
                    array(
                        'label'         => 'Posts Per Request',
                        'name'          => 'posts_per_request',
                        'type'          => 'number',
                        'instructions'  => '',
                        'required'      => true,
                        'min'           => 1,
                        'default_value' => 5,
                    ),
        
                ),
    
            ),

        );
        
        $this->data = array(
            'offset' => 0,
        );
        
    }
    
    /*
     * Validate
     */
    function validate(){
    
        // File
        $file = get_field('file');
    
        // Validate file
        if($file){
        
            $file_path = get_attached_file($file['ID']);
            $file_content = file_get_contents($file_path);
        
            // Json decode + error
            $json = json_decode($file_content, true);
        
            if(json_last_error() !== JSON_ERROR_NONE){
            
                acfe_add_validation_error('file', 'Json file is invalid');
            
            }
        
        }
        
    }
    
    /*
     * Start
     */
    function start(){
    
        // File
        $file = get_field('file');
        $file_path = get_attached_file($file['ID']);
        $file_content = file_get_contents($file_path);
        
        // Json decode
        $posts = json_decode($file_content, true);
    
        // Validate posts
        foreach(array_keys($posts) as $k){
        
            // Validate post
            $posts[$k] = wp_parse_args($posts[$k], array(
                'post_id'           => 0,
                'post_title'        => '',
                'post_permalink'    => '',
                'post_content'      => '',
                'post_status'       => 'publish',
                'post_meta'         => array(),
            ));
        
        }
    
        // Save transient
        set_transient('acfe_import_posts', $posts, 43200); // 12 hours cache
    
        // Set stats
        $total = count($posts);
    
        $this->stats['total'] = $total;
        $this->stats['left'] = $total;
    
        // Send Response
        $this->send_response(array(
            'message' => "Reading json file: <strong>{$total}</strong> posts found. Transient saved"
        ));
        
    }
    
    /*
     *
     */
    function stop(){
    
        // Delete transient
        delete_transient('acfe_import_posts');
        
        // Send response
        $this->send_response(array(
            'message'   => "Import finished. {$this->data['offset']} post" . ($this->data['offset'] > 1 ? 's' : '') ." imported",
            'event'     => 'success'
        ));
        
    }
    
    /*
     * Request
     */
    function request(){
    
        // Get Transient
        $posts = acf_get_array(get_transient('acfe_import_posts'));
    
        // Get Fields
        $update = get_field('update');
        $posts_per_request = get_field('posts_per_request');
    
        // Vars
        $message = array();
        $debug = array();
    
        // Loop posts
        for($i = 0; $i < $posts_per_request; $i++){
        
            // Get post
            $post = acf_maybe_get($posts, $this->data['offset']);
        
            // Task done
            if(!$post){
    
                $this->send_response(array(
                    'event' => 'stop'
                ));
            
            }
        
            // Update data
            $this->data['offset']++;
            
            // Update stats
            $this->stats['left'] = absint($this->stats['total'] - $this->data['offset']);
        
            // Post data
            $_post_id = $post['post_id'];
            $post_id = $_post_id;
        
            $post_title = $post['post_title'];
            $post_permalink = $post['post_permalink'];
            $post_content = $post['post_content'];
            $post_status = $post['post_status'];
            $post_meta = $post['post_meta'];
            $updated = false;
        
            // Update existing post
            if($update && $post_id && get_post($post_id)){
            
                $updated = true;
            
                $post_id = wp_update_post(array(
                    'ID'            => $post_id,
                    'post_title'    => $post_title,
                    'post_content'  => $post_content,
                    'post_status'   => $post_status,
                ));
            
            // Insert post
            }else{
            
                $post_id = wp_insert_post(array(
                    'post_title'    => $post_title,
                    'post_content'  => $post_content,
                    'post_status'   => $post_status,
                ));
            
            }
        
            // Error during insert/update
            if(!$post_id || is_wp_error($post_id)){
                continue;
            }
        
            // Update Meta
            foreach($post_meta as $meta_key => $meta_value){
            
                update_post_meta($post_id, $meta_key, $meta_value);
            
            }
        
            // Message & debug
            $message[] = "<a href='" . admin_url('post.php?post=' . $post_id . '&action=edit') . "'>{$post_title}</a>" . ($updated ? ' <span style="color:#888;">Updated</span>' : '');
            $debug[] = $post;
        
        }
    
        // Send Response
        $this->send_response(array(
            'message'   => $message,
            'debug'     => $debug,
        ));
    
    }
    
}

acfe_register_script('acfe_script_import_posts');

endif;