<?php
namespace PrimeLink\Modules\Imports\DataSources;

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

final class DesktopUploadSource implements DataSourceInterface {

    public function handle( array $payload ) {
        if ( empty( $_FILES['file'] ) ) {
            return array( 'error' => 'No file uploaded.' );
        }

        $file = $_FILES['file'];

        if ( $file['error'] !== UPLOAD_ERR_OK ) {
            return array( 'error' => 'Upload error.' );
        }

        $upload_dir = wp_upload_dir();
        $dest_dir   = trailingslashit( $upload_dir['basedir'] ) . 'primelink/';
        $dest_url   = trailingslashit( $upload_dir['baseurl'] ) . 'primelink/';

        if ( ! \PrimeLink\Helpers\FilesystemHelper::directory_exists( $dest_dir ) ) {
            \PrimeLink\Helpers\FilesystemHelper::create_directory( $dest_dir );
        }

        $name = sanitize_file_name( $file['name'] );
        $path = $dest_dir . time() . '-' . $name;

        if ( ! move_uploaded_file( $file['tmp_name'], $path ) ) {
            return array( 'error' => 'Could not move uploaded file.' );
        }

        return array(
            'path'          => $path,
            'url'           => $dest_url . basename( $path ),
            'type'          => strtolower( pathinfo( $path, PATHINFO_EXTENSION ) ),
            'original_name' => $name,
        );
    }
}