<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Log;
use App\Services\MediaService;

class StorageController extends Controller
{
    protected $mediaService;

    public function __construct(MediaService $mediaService)
    {
        $this->mediaService = $mediaService;
    }

    /**
     * Show storage configuration page
     */
    public function index()
    {
        return view('admin.pages.settings.storage_config');
    }

    /**
     * Update storage settings
     */
    public function update(Request $request)
    {
        try {
            $storageType = $request->input('storage_type');
            
            if ($storageType === 'active_storage') {
                return $this->updateActiveStorage($request);
            }

            switch ($storageType) {
                case 'aws':
                    return $this->updateAwsSettings($request);
                case 'wasabi':
                    return $this->updateWasabiSettings($request);
                case 'digitalocean':
                    return $this->updateDigitalOceanSettings($request);
                case 'google':
                    return $this->updateGoogleSettings($request);
                case 'azure':
                    return $this->updateAzureSettings($request);
                case 'ftp':
                    return $this->updateFtpSettings($request);
                default:
                    return response()->json(['success' => false, 'message' => 'Invalid storage type']);
            }
        } catch (\Exception $e) {
            Log::error('Storage configuration update failed', [
                'error' => $e->getMessage(),
                'storage_type' => $request->input('storage_type')
            ]);
            
            return response()->json(['success' => false, 'message' => 'Failed to update storage settings']);
        }
    }

    /**
     * Update active storage setting
     */
    private function updateActiveStorage(Request $request)
    {
        $activeStorage = $request->input('active_storage', 'local');
        
        // Update the active storage setting
        setting(['active_storage' => $activeStorage]);
        
        return response()->json(['success' => true, 'message' => 'Active storage updated successfully']);
    }

    /**
     * Update AWS S3 settings
     */
    private function updateAwsSettings(Request $request)
    {
        $settings = [
            'aws_bucket_name' => $request->input('aws_bucket_name'),
            'aws_access_key' => $request->input('aws_access_key'),
            'aws_secret_key' => $request->input('aws_secret_key'),
            'aws_region' => $request->input('aws_region'),
            'aws_endpoint' => $request->input('aws_endpoint'),
            'aws_cloudfront_domain' => $request->input('aws_cloudfront_domain'),
        ];

        // Validate required fields
        if (empty($settings['aws_bucket_name']) || empty($settings['aws_access_key']) || empty($settings['aws_secret_key'])) {
            return response()->json(['success' => false, 'message' => 'Please fill in all required AWS fields']);
        }

        // Save settings
        foreach ($settings as $key => $value) {
            if ($value !== null) {
                setting([$key => $value]);
            }
        }

        return response()->json(['success' => true, 'message' => 'AWS settings updated successfully']);
    }

    /**
     * Update Wasabi settings
     */
    private function updateWasabiSettings(Request $request)
    {
        $settings = [
            'wasabi_bucket_name' => $request->input('wasabi_bucket_name'),
            'wasabi_access_key' => $request->input('wasabi_access_key'),
            'wasabi_secret_key' => $request->input('wasabi_secret_key'),
            'wasabi_region' => $request->input('wasabi_region'),
        ];

        // Validate required fields
        if (empty($settings['wasabi_bucket_name']) || empty($settings['wasabi_access_key']) || empty($settings['wasabi_secret_key'])) {
            return response()->json(['success' => false, 'message' => 'Please fill in all required Wasabi fields']);
        }

        // Save settings
        foreach ($settings as $key => $value) {
            if ($value !== null) {
                setting([$key => $value]);
            }
        }

        return response()->json(['success' => true, 'message' => 'Wasabi settings updated successfully']);
    }

    /**
     * Update DigitalOcean Spaces settings
     */
    private function updateDigitalOceanSettings(Request $request)
    {
        $settings = [
            'do_spaces_key' => $request->input('do_spaces_key'),
            'do_spaces_secret' => $request->input('do_spaces_secret'),
            'do_spaces_name' => $request->input('do_spaces_name'),
            'do_spaces_region' => $request->input('do_spaces_region'),
        ];

        // Validate required fields
        if (empty($settings['do_spaces_key']) || empty($settings['do_spaces_secret']) || empty($settings['do_spaces_name'])) {
            return response()->json(['success' => false, 'message' => 'Please fill in all required DigitalOcean fields']);
        }

        // Save settings
        foreach ($settings as $key => $value) {
            if ($value !== null) {
                setting([$key => $value]);
            }
        }

        return response()->json(['success' => true, 'message' => 'DigitalOcean settings updated successfully']);
    }

    /**
     * Update Google Cloud Storage settings
     */
    private function updateGoogleSettings(Request $request)
    {
        $settings = [
            'google_project_id' => $request->input('google_project_id'),
            'google_bucket_name' => $request->input('google_bucket_name'),
            'google_credentials' => $request->input('google_credentials'),
        ];

        // Validate required fields
        if (empty($settings['google_project_id']) || empty($settings['google_bucket_name']) || empty($settings['google_credentials'])) {
            return response()->json(['success' => false, 'message' => 'Please fill in all required Google Cloud fields']);
        }

        // Validate JSON credentials
        if (!json_decode($settings['google_credentials'])) {
            return response()->json(['success' => false, 'message' => 'Invalid JSON format for service account credentials']);
        }

        // Save settings
        foreach ($settings as $key => $value) {
            if ($value !== null) {
                setting([$key => $value]);
            }
        }

        return response()->json(['success' => true, 'message' => 'Google Cloud settings updated successfully']);
    }

    /**
     * Update Azure Blob Storage settings
     */
    private function updateAzureSettings(Request $request)
    {
        $settings = [
            'azure_account_name' => $request->input('azure_account_name'),
            'azure_account_key' => $request->input('azure_account_key'),
            'azure_container' => $request->input('azure_container'),
            'azure_endpoint' => $request->input('azure_endpoint'),
        ];

        // Validate required fields
        if (empty($settings['azure_account_name']) || empty($settings['azure_account_key']) || empty($settings['azure_container'])) {
            return response()->json(['success' => false, 'message' => 'Please fill in all required Azure fields']);
        }

        // Save settings
        foreach ($settings as $key => $value) {
            if ($value !== null) {
                setting([$key => $value]);
            }
        }

        return response()->json(['success' => true, 'message' => 'Azure settings updated successfully']);
    }

    /**
     * Update FTP settings
     */
    private function updateFtpSettings(Request $request)
    {
        $settings = [
            'ftp_host' => $request->input('ftp_host'),
            'ftp_username' => $request->input('ftp_username'),
            'ftp_password' => $request->input('ftp_password'),
            'ftp_port' => $request->input('ftp_port', 21),
            'ftp_root' => $request->input('ftp_root', '/'),
            'ftp_ssl' => $request->has('ftp_ssl'),
        ];

        // Validate required fields
        if (empty($settings['ftp_host']) || empty($settings['ftp_username']) || empty($settings['ftp_password'])) {
            return response()->json(['success' => false, 'message' => 'Please fill in all required FTP fields']);
        }

        // Save settings
        foreach ($settings as $key => $value) {
            if ($value !== null) {
                setting([$key => $value]);
            }
        }

        return response()->json(['success' => true, 'message' => 'FTP settings updated successfully']);
    }

    /**
     * Test storage connection
     */
    public function test(Request $request)
    {
        try {
            if (!$request->hasFile('test_file')) {
                return response()->json(['success' => false, 'message' => 'No test file provided']);
            }

            $file = $request->file('test_file');
            $activeStorage = setting('active_storage', 'local');

            // Test file upload using the media service
            $result = $this->mediaService->store($file, 'image', $activeStorage, [
                'test_mode' => true
            ]);

            if ($result['success']) {
                // Clean up test file
                $this->mediaService->delete($result['path'], $activeStorage);
                
                return response()->json([
                    'success' => true, 
                    'message' => "Storage connection test successful! File uploaded and deleted successfully using {$activeStorage} storage."
                ]);
            } else {
                return response()->json(['success' => false, 'message' => $result['error']]);
            }

        } catch (\Exception $e) {
            Log::error('Storage test failed', [
                'error' => $e->getMessage(),
                'storage' => setting('active_storage', 'local')
            ]);
            
            return response()->json(['success' => false, 'message' => 'Storage test failed: ' . $e->getMessage()]);
        }
    }

    /**
     * Reset storage settings to default
     */
    public function reset()
    {
        try {
            // Reset to local storage
            setting(['active_storage' => 'local']);
            
            // Clear all storage-specific settings
            $storageSettings = [
                'aws_bucket_name', 'aws_access_key', 'aws_secret_key', 'aws_region', 'aws_endpoint', 'aws_cloudfront_domain',
                'wasabi_bucket_name', 'wasabi_access_key', 'wasabi_secret_key', 'wasabi_region',
                'do_spaces_key', 'do_spaces_secret', 'do_spaces_name', 'do_spaces_region',
                'google_project_id', 'google_bucket_name', 'google_credentials',
                'azure_account_name', 'azure_account_key', 'azure_container', 'azure_endpoint',
                'ftp_host', 'ftp_username', 'ftp_password', 'ftp_port', 'ftp_root', 'ftp_ssl'
            ];

            foreach ($storageSettings as $setting) {
                setting()->forget($setting);
            }

            return response()->json(['success' => true, 'message' => 'Storage settings reset to default successfully']);
        } catch (\Exception $e) {
            Log::error('Storage reset failed', ['error' => $e->getMessage()]);
            return response()->json(['success' => false, 'message' => 'Failed to reset storage settings']);
        }
    }
} 