<?php

namespace FileBird\Controller;

defined( 'ABSPATH' ) || exit;

use FileBird\Model\Folder as FolderModel;

class SyncController {
	public function exportCSV( \WP_REST_Request $request ) {
		$id = $request->get_param( 'id' );
		if( !empty( $id ) ) {
			$folders = get_option( 'filebird_backup_' . $id, array() );
		} else {
			$folders = FolderModel::exportAll();
		}
		return new \WP_REST_Response( array( 'folders' => $folders ) );
	}

    public function readCSV( \WP_REST_Request $request ) {
		$params  = $request->get_file_params();
		$handle  = \fopen( $params['file']['tmp_name'], 'r' );
		$data    = array();
		$columns = array();
		if ( false !== $handle ) {
			$count = 1;
			while ( 1 ) {
				$row = fgetcsv( $handle, 0 );
				if ( 1 === $count ) {
					$columns = $row;
					$count++;
					continue;
				}
				if ( false === $row ) {
					break;
				}
				foreach ( $columns as $key => $col ) {
					$tmp[ $col ] = $row[ $key ];
				}
				$data[] = $tmp;
			}
		}
		\fclose( $handle );

		$check = array_diff(
			$columns,
			array(
				'id',
				'name',
				'parent',
				'type',
				'ord',
				'created_by',
				'attachment_ids',
			)
		);

		if ( count( $check ) > 0 ) {
			return new \WP_REST_Response(
				array(
					'success' => false,
					'message' => __( 'The uploaded file was not generated by FileBird. Please check again.', 'filebird' ),
				)
			);
		}

		return $data;
	}

    public function restoreFolderStructure( $folders ) {
		$tree            = $this->buildTree( $folders );
        $folders_created = $this->run_import_folders( $tree );

		$mess = sprintf( __( 'Congratulations! We imported successfully %d folders into <strong>FileBird.</strong>', 'filebird' ), count( $folders_created ) );

		return new \WP_REST_Response( array( 'mess' => $mess ) );
	}

    public function buildTree( array &$data, $parentId = 0 ) {
		$tree = array();
		foreach ( $data as &$node ) {
			if ( $node['parent'] == $parentId ) {
				$children = $this->buildTree( $data, $node['id'] );
				if ( $children ) {
					$node['children'] = $children;
				}
				$tree[] = $node;
				unset( $node );
			}
		}
		return $tree;
	}

	public function run_import_folders( $folders, $parent = 0 ) {
        $folders_created = array();

		usort(
			$folders,
			function( $folder1, $folder2 ) {
				return intval( $folder1['ord'] ) > intval( $folder2['ord'] ) ? 1 : -1;
			}
		);

		foreach ( $folders as $folder ) {
			$new_folder     = FolderModel::newOrGet( $folder['name'], $parent );
			$attachment_ids = ! empty( $folder['attachment_ids'] ) ? explode( '|', $folder['attachment_ids'] ) : false;
            array_push( $folders_created, $folder['id'] );

			if ( $attachment_ids && false !== $new_folder ) {
				FolderModel::setFoldersForPosts( $attachment_ids, $new_folder['id'] );
			}

			if ( isset( $folder['children'] ) && count( $folder['children'] ) > 0 ) {
				$new_child_folders = $this->run_import_folders( $folder['children'], $new_folder['id'] );
				$folders_created   = array_merge( $folders_created, $new_child_folders );
			}
		}

		return $folders_created;
    }

    public function importCSV( \WP_REST_Request $request ) {
		$data      = $this->readCSV( $request );
		$createdBy = intval( $request->get_param( 'userId' ) );

		if ( $createdBy != '-1' ) {
			$data = array_filter(
                $data,
                function( $item ) use ( $createdBy ) {
				return $item['created_by'] == $createdBy;
				}
                );
		}

		$result = $this->restoreFolderStructure( $data );

		return new \WP_REST_Response( array( 'success' => $result ) );
	}

	public function getImportCSVDetail( \WP_REST_Request $request ) {
		$data = $this->readCSV( $request );

		$users = \get_users(
            array(
				'include' => array_unique( array_column( $data, 'created_by' ) ),
			)
            );

		$usersReturn = array();

		foreach ( $users as $user ) {
			$usersReturn[ $user->ID ] = $user->data->display_name . ' ' . __( 'folders', 'filebird' );
		}

		return new \WP_REST_Response( $usersReturn );
	}
}
