<?php

namespace Lcmigrator\LcMigrator\ImporterV2;
use ZipArchive;
use Lcmigrator\LcMigrator\Logger\Logger;

class ZipHandler {

    private string $temp_dir;
    private string $upload_dir;

    public static function execute($zip_path, &$sharedParams, Logger $logger = null){

        if(!isset($logger)){
            $logger = Logger::getInstance();
        }

        $unique_id = uniqid('import_');
        $temp_dir = wp_upload_dir()['basedir'] . '/temp_' . $unique_id . '/';
        $upload_dir = $temp_dir . 'backup-imports/';

        $zipHandler = new ZipArchive();
        $logger->info("ZipHandler: Executing zip handler");
        $logger->info("ZipHandler: Zip path: {$zip_path}");

        // Create Temporary Directory
        wp_mkdir_p($temp_dir);
        wp_mkdir_p($upload_dir);

        // Copy Zip to Temporary Directory
        $temp_zip = $temp_dir . basename($zip_path);
        rename($zip_path, $temp_zip);

        // Extract Zip
        $zip = new ZipArchive();
        $zip->open($temp_zip);

        $extract_path = $upload_dir . 'extracted_backup/';
        $logger->info("ZipHandler: Extracting zip to: {$extract_path}");
        $zip->extractTo($extract_path);
        $zip->close();

        $logger->info("ZipHandler: Zip extracted successfully");
        
        // Set Shared Params 
        $sharedParams['temp_dir'] = $temp_dir;
        $sharedParams['upload_dir'] = $upload_dir;
        $sharedParams['extract_path'] = $extract_path;

        $logger->info("ZipHandler: Shared params set successfully");

        return true;
    }

}