<?php

namespace BWFAN\Exporter;

use BWFAN\Exporter\Base;

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly
}

/***
 * Class Template_Exporter
 *
 * @package Autonami
 */
class Templates extends Base {

	public $export_id = 0;
    /**
     * Class constructor
     */
    public function __construct() {
        $this->type = 'templates';
    }

    /**
     * Handle template export
     *
	 * @param $user_id
	 * @param $export_id
	 *
	 * @return void
	 */
    public function handle_export( $user_id, $export_id = 0 ){
		$this->export_id = 0;
        $status_data = [
            'status' => 3,
            'msg' => [
	            __( 'Unable to create export file.', 'wp-marketing-automations-pro' )
            ]
        ];
        if ( ! class_exists( '\BWFCRM_Templates'  ) ) {
            $status_data = [
                'status' => 3,
                'msg' => [
	                __( 'Unable to get template export file data.', 'wp-marketing-automations-pro' ),
	                __( 'Unable to find BWFCRM_Templates class.', 'wp-marketing-automations-pro' )
                ]
            ];
        } else {
            // get templates json
            $get_export_templates_data = \BWFCRM_Templates::get_json();

            $filename = 'template-export-'.time().'.json';

            if ( ! file_exists( self::$export_folder . '/' ) ) {
                wp_mkdir_p( self::$export_folder );
            }

            $res = file_put_contents( self::$export_folder . '/' . $filename, $get_export_templates_data, 8 );

            if ( $res ) {
                $status_data = [
                    'status' => 2,
                    'url' => self::$export_folder . '/' . $filename,
                    'msg' => [
                        __( 'File created successfully', 'wp-marketing-automations-pro' )
                    ]
                ];
            }
        }
        $user_data = get_user_meta( $user_id, 'bwfan_single_export_status', true );

        $user_data[ $this->type ] = $status_data;

        update_user_meta( $user_id, 'bwfan_single_export_status', $user_data );

        BWFAN_Core()->exporter->unschedule_export_action( [
            'type' => $this->type,
            'user_id' => $user_id,
            'export_id' => $this->export_id
        ] );
    }
}

/**
 * Register exporter
 */
BWFAN_Core()->exporter->register_exporter( 'templates', 'BWFAN\Exporter\Templates' );