<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;

class SetupStorage extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'storage:setup';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Setup storage directories and symlink for production';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('Setting up storage...');

        // 1. Create storage directories
        $directories = [
            'app/public/wallets/qr-codes',
            'app/public/deposits/vouchers',
            'app/public/support',
            'framework/cache',
            'framework/sessions',
            'framework/views',
            'logs',
        ];

        foreach ($directories as $dir) {
            $path = storage_path($dir);
            if (!File::exists($path)) {
                File::makeDirectory($path, 0755, true);
                $this->line("✅ Created: {$dir}");
            } else {
                $this->line("✓ Exists: {$dir}");
            }
        }

        // 2. Create storage symlink
        $link = public_path('storage');
        $target = storage_path('app/public');

        if (file_exists($link)) {
            if (is_link($link) && readlink($link) === $target) {
                $this->info("✅ Storage symlink already exists and is correct");
            } else {
                if (is_link($link)) {
                    unlink($link);
                } else {
                    File::deleteDirectory($link);
                }
                symlink($target, $link);
                $this->info("✅ Storage symlink recreated");
            }
        } else {
            symlink($target, $link);
            $this->info("✅ Storage symlink created");
        }

        // 3. Set permissions
        $storagePath = storage_path();
        $publicStoragePath = public_path('storage');
        
        $this->line("Setting permissions...");
        
        // Set directory permissions
        $this->setPermissions($storagePath, 0755);
        $this->setPermissions($publicStoragePath, 0755);
        
        $this->info("✅ Storage setup complete!");
        $this->line("");
        $this->line("Storage directories:");
        $this->line("  - QR Codes: storage/app/public/wallets/qr-codes");
        $this->line("  - Vouchers: storage/app/public/deposits/vouchers");
        $this->line("  - Support: storage/app/public/support");
        $this->line("");
        $this->line("Symlink: public/storage -> storage/app/public");

        return 0;
    }

    /**
     * Set permissions recursively
     */
    private function setPermissions($path, $permissions)
    {
        if (file_exists($path)) {
            chmod($path, $permissions);
            if (is_dir($path)) {
                $items = new \RecursiveIteratorIterator(
                    new \RecursiveDirectoryIterator($path, \RecursiveDirectoryIterator::SKIP_DOTS),
                    \RecursiveIteratorIterator::SELF_FIRST
                );
                
                foreach ($items as $item) {
                    chmod($item->getPathname(), $permissions);
                }
            }
        }
    }
}

