<?php
namespace Lcmigrator\LcMigrator\Importer\Cli;

use Lcmigrator\LcMigrator\ImporterV2\CleanComplete;
use Lcmigrator\LcMigrator\ImporterV2\DatabaseImporter;
use Lcmigrator\LcMigrator\ImporterV2\ImportDone;
use Lcmigrator\LcMigrator\ImporterV2\Permalink;
use Lcmigrator\LcMigrator\ImporterV2\RestoreFiles;
use Lcmigrator\LcMigrator\ImporterV2\ZipHandler;
use WP_CLI;
use WP_CLI_Command;
use Exception;
use Lcmigrator\LcMigrator\Importer\Manager\Manager;
use Lcmigrator\LcMigrator\Logger\Logger;

if (!defined('WP_CLI') || !WP_CLI) return;
// Use Composer Autoloader

WP_CLI::log('ImportManager class: ' . Manager::class);

class ImporterCli extends WP_CLI_Command
{
    private $importer;
    private $logger; 

    public function __construct()
    {
        $this->logger = Logger::getInstance();
        $this->logger->info("Importer CLI Initialized");
    }

    /**
     * Imports a WordPress backup from a URL
     * 
     * ## OPTIONS
     * 
     * <url>
     * : The URL of the backup zip file
     * 
     * ## EXAMPLES
     *
     * wp backup-import url https://example.com/backup.zip
     */
    public function url($args, $assoc_args)
    {
        list($url) = $args; // Get they URL argument

        WP_CLI::log("Starting backup import from URL: $url");
        $time_start = microtime(true);


        try {
            $this->logger->info("Downloading Backup file from URL: $url");
            // Download with progress bar
            $temp_file = $this->download_with_progress($url);
            
            if (is_wp_error($temp_file)) {
                $this->logger->error("Failed To Download File: {$url}");
                throw new Exception("Failed to download file: {$url}");
            }

            $this->logger->info("File Download Success : $temp_file");
            WP_CLI::log("Downloaded file to: $temp_file");
            
            
            WP_CLI::log("Processing Backup File...");
            $this->logger->info("Starting Backup : Import Process");
            try{
                // Shared Params To Share Across Functions
                $sharedParams = [];
                // Execute Zip Handler
                ZipHandler::execute($temp_file, $sharedParams, $this->logger);
                // Print Shared Params
                WP_CLI::log("Shared Params: " . json_encode($sharedParams));

                // Execute Permalink
                Permalink::execute($sharedParams);
                WP_CLI::log("Permalink Exported");

                // Execute Restore Files
                RestoreFiles::execute($sharedParams);
                WP_CLI::log("Files Restored");

                // Execute Database Import
                DatabaseImporter::execute($sharedParams, $this->logger);
                WP_CLI::log("Database Import Completed");

                // Execute Import Done
                ImportDone::execute($sharedParams);
                WP_CLI::log("Import Done");

                // Execute Clean Complete
                CleanComplete::execute($sharedParams);
                WP_CLI::log("Clean Complete");

            }
            catch(Exception $e){
                $this->logger->error("Failed To Import Backup File: {$temp_file}");
                WP_CLI::error("Failed to import backup file: {$temp_file}");
                WP_CLI::error($e->getMessage());
                throw new Exception("Failed to import backup file: {$temp_file}");
            }
            $this->logger->info("Backup import completed successfully!");
            WP_CLI::log("Backup import completed successfully!");
            
        } catch (Exception $e) {
            WP_CLI::error($e->getMessage());
        }

        $end_time = microtime(true);
        $execution_time = ($end_time - $time_start);
        WP_CLI::success("Backup import completed in $execution_time seconds");
    }
    private function download_with_progress($url)
    {
        WP_CLI::log("Starting file download...");

        // Get file size
        $headers = get_headers($url, 1);
        $filesize = isset($headers['Content-Length']) ? (int)$headers['Content-Length'] : 0;

        // Create progress bar
        $progress = \WP_CLI\Utils\make_progress_bar('Downloading', $filesize);

        $temp_file = wp_upload_dir()['basedir'] . '/backup.zip';
        $fp = fopen($temp_file, 'w+');

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_FILE, $fp);
        curl_setopt($ch, CURLOPT_BUFFERSIZE, 128);
        curl_setopt($ch, CURLOPT_NOPROGRESS, false);
        curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, function ($resource, $download_size, $downloaded) use ($progress) {
            if ($download_size > 0) {
                $progress->tick($downloaded);
            }
        });

        curl_exec($ch);
        curl_close($ch);
        fclose($fp);

        $progress->finish();
        WP_CLI::log("\nDownload complete!");
        return $temp_file;
    }
}

WP_CLI::add_command('backup-import', 'Lcmigrator\LcMigrator\Importer\Cli\ImporterCli');
