<?php

namespace EasyContentManager\Ajax;

use EasyContentManager\Classes\AbstractAjaxHandler;
use EasyContentManager\Utils\ImportExportHelper;

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

class Tools extends AbstractAjaxHandler {

	public function __construct() {
		$this->actions = [
			'export_data' => [
				'callback'   => [ $this, 'export_data' ],
				'capability' => 'manage_options',
				'fields'     => [ 'export_type' => 'string' ],
			],
			'import_data' => [
				'callback'   => [ $this, 'import_data' ],
				'capability' => 'manage_options',
				'fields'     => [
					'import_type' => 'string',
					'file'        => 'file|optional',
					'file_path'   => 'string|optional',
				],
			],
		];
	}

	public function export_data( $payload ) {
		$helper = new ImportExportHelper();
		
		$result = $helper->export( [
			'export_type' => $payload['export_type'] ?? 'all',
		] );

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( [ 'message' => $result->get_error_message() ] );
		}

		wp_send_json_success( [
			'zip_url'  => $result['file_url'] ?? '',
			'filename' => $result['filename'],
			'stats'    => $result['stats'],
		] );
	}

	public function import_data( $payload ) {
		$helper = new ImportExportHelper();
		
		$file_path = null;
		$delete_file = false;

		if ( ! empty( $payload['file_path'] ) ) {
			$file_path = $payload['file_path'];
			
		} else {
			$file = $this->handle_file_upload();
			
			if ( is_wp_error( $file ) ) {
				wp_send_json_error( [ 'message' => $file->get_error_message() ] );
			}
			
			$file_path = $file['path'];
			$delete_file = true;
		}

		$result = $helper->import( [
			'file_path'   => $file_path,
			'import_type' => $payload['import_type'] ?? 'all',
			'delete_file' => $delete_file,
		] );

		if ( is_wp_error( $result ) ) {
			wp_send_json_error( [ 'message' => $result->get_error_message() ] );
		}

		wp_send_json_success( [
			'stats'   => $result['stats'],
			'message' => $result['message'],
		] );
	}

	private function handle_file_upload() {
		if ( ! isset( $_FILES['file'] ) || empty( $_FILES['file']['tmp_name'] ) ) {
			return new \WP_Error( 'no_file', __( 'No file uploaded.', 'easy-content-manager' ) );
		}

		$file = $_FILES['file'];

		if ( $file['error'] !== UPLOAD_ERR_OK ) {
			return new \WP_Error( 'upload_error', __( 'File upload failed.', 'easy-content-manager' ) );
		}

		if ( wp_check_filetype( $file['name'] )['ext'] !== 'zip' ) {
			return new \WP_Error( 'invalid_type', __( 'Only ZIP files are allowed.', 'easy-content-manager' ) );
		}

		$upload_dir = wp_upload_dir();
		$temp_file = $upload_dir['basedir'] . '/ecm_import_' . time() . '.zip';

		if ( ! move_uploaded_file( $file['tmp_name'], $temp_file ) ) {
			return new \WP_Error( 'move_failed', __( 'Failed to process file.', 'easy-content-manager' ) );
		}

		return [ 'path' => $temp_file ];
	}
}