<?php
namespace Lcmigrator\LcMigrator\Migrator\BackupInProgress;

class BackupInProgress {
    private string $backupId;
    private string $transientName;
    private string $optionName;
    private array $metadata = [];

    public function __construct(string $backupId) {
        $this->backupId = $backupId;
        $this->transientName = 'lc_mg_backup_in_progress_' . $backupId;
        $this->optionName = 'lc_mg_backup_status_' . $backupId;

        $this->initializeMetadata();
        $this->refreshMetadata();
    }

    private function initializeMetadata(): void {
        $this->metadata = [
            'stage' => 1,
            'status' => 'running',
            'message' => 'Creating a secure backup of your current website...'
        ];
    }

    public function setMetadata(string $key, $value): void {
        $this->refreshMetadata();
        
        // Store the value directly without wrapping in array
        $this->metadata[$key] = $value;
        
        // Store in both transient and option for reliability
        set_transient($this->transientName, json_encode($this->metadata), 86400);
        update_option($this->optionName, json_encode($this->metadata), false);
    }

    public function getMetadata(string $key) {
        $this->refreshMetadata();
        return $this->metadata[$key] ?? null;
    }

    public function refreshMetadata(): void {
        // Clear caches
        wp_cache_delete($this->transientName, 'transients');
        wp_cache_delete($this->optionName, 'options');
        
        // Try to get from option first (more reliable for immediate updates)
        $optionData = get_option($this->optionName);
        if ($optionData !== false) {
            $this->metadata = json_decode($optionData, true) ?: [];
            return;
        }

        // Fallback to transient
        $transientData = get_transient($this->transientName);
        if ($transientData !== false) {
            $this->metadata = json_decode($transientData, true) ?: [];
        } else {
            $this->metadata = [];
        }
    }

    public function getAllMetadata(): array {
        $this->refreshMetadata();
        return $this->metadata;
    }

    public function getBackupId(): string {
        return $this->backupId;
    }

    public function clearMetadata(): void {
        $this->metadata = [];
        delete_transient($this->transientName);
        delete_option($this->optionName);
    }

    public function isForceClosed(): bool {
        // Direct option check for force_closed status
        $optionData = get_option($this->optionName);
        if ($optionData !== false) {
            $data = json_decode($optionData, true) ?: [];
            return isset($data['force_closed']) && $data['force_closed'] === true;
        }
        return false;
    }
}
