<?php

namespace App\Http\Controllers;

use App\Enums\StatusEnum;
use App\Http\Services\SettingService;
use App\Models\AiSetting;
use App\Models\Core\Language;
use App\Models\Core\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Inertia\Inertia;
use App\Http\Controllers\CronController;

class SettingController extends Controller
{

    protected $settingService;

    public function __construct(SettingService $settingService)
    {
        $this->settingService = new SettingService();
    }

    public function index()
    {
        // Get cron job status safely
        $cronJobs = [];
        $systemStatus = [];
        
        try {
            $cronController = new CronController();
            $cronResponse = $cronController->status();
            $cronData = $cronResponse->getData(true); // Get as array
            
            $cronJobs = $cronData['cronJobs'] ?? [];
            $systemStatus = $cronData['systemStatus'] ?? [];
        } catch (\Exception $e) {
            // Log the error but don't break the page
            Log::error('Failed to get cron job status: ' . $e->getMessage());
        }
        
        return Inertia::render('PremiumSettings', [
            'time_zone' => config('settings.time_zone'),
            'date_format' => config('settings.date_format'),
            'settings' => Setting::all()->pluck('value', 'key'),
            'settingConfig' => config('settings'),
            'aiSettings' => AiSetting::all(),
            'languages' => Language::search(['name' , 'code'])
            ->filter(['status'])
            ->orderByRaw("is_default = ? DESC", [StatusEnum::true->status()])
            ->paginate(paginateNumber()),
            'backups' => $this->settingService->getBackupList(),
            'backupPath' => storage_path('app/backups'),
            'cronJobs' => $cronJobs,
            'systemStatus' => $systemStatus,
        ]);

    }

    public function store(Request $request)
    {
        $this->settingService->updateSettings($request->except('_token'));

        return redirect()->back()->with('success', 'Settings saved');
    }

    public function logoSetting(Request $request): string
    {

        $this->settingService->logoSettings($request->except('_token'));

        return redirect()->back()->with('success','Logo Saved');


    }

    public function testEmail(Request $request)
    {
        try {
            // Validate email settings
            $validated = $request->validate([
                'smtp_host' => 'required|string',
                'smtp_port' => 'required|numeric|min:1|max:65535',
                'smtp_username' => 'required|email',
                'smtp_password' => 'required|string',
                'smtp_encryption' => 'nullable|in:tls,ssl,none',
                'mail_from_address' => 'required|email',
                'mail_from_name' => 'nullable|string',
                'test_email' => 'required|email',
            ]);

            // Set default encryption if not provided
            if (!isset($validated['smtp_encryption']) || empty($validated['smtp_encryption'])) {
                $validated['smtp_encryption'] = 'tls';
            }

            // Log the attempt for debugging
            \Log::info('Testing email configuration', [
                'host' => $validated['smtp_host'],
                'port' => $validated['smtp_port'],
                'username' => $validated['smtp_username'],
                'encryption' => $validated['smtp_encryption'],
                'test_email' => $validated['test_email']
            ]);

            // Test email configuration
            $this->settingService->testEmailConfiguration($validated);

            return redirect()->back()->with('success', 'Test email sent successfully to ' . $validated['test_email']);

        } catch (\Illuminate\Validation\ValidationException $e) {
            return redirect()->back()->withErrors($e->errors())->withInput();
        } catch (\Exception $e) {
            \Log::error('Email test failed', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            return redirect()->back()->with('error', 'Email test failed: ' . $e->getMessage())->withInput();
        }
    }

    public function dataExport()
    {
        try {
            $exportPath = $this->settingService->exportUserData();
            return response()->download($exportPath)->deleteFileAfterSend();

        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Data export failed: ' . $e->getMessage());
        }
    }

    public function createBackup(Request $request)
    {
        try {
            $request->validate([
                'type' => 'required|in:full,database,files,settings'
            ]);

            $backupPath = $this->settingService->createBackup($request->input('type'));

            return redirect()->back()->with('success', 'Backup created successfully');

        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Backup creation failed: ' . $e->getMessage());
        }
    }

    public function restoreBackup(Request $request)
    {
        try {
            $request->validate([
                'backup_path' => 'required|string'
            ]);

            $this->settingService->restoreBackup($request->input('backup_path'));

            return redirect()->back()->with('success', 'Backup restored successfully');

        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Backup restore failed: ' . $e->getMessage());
        }
    }

    public function deleteBackup(Request $request)
    {
        try {
            $request->validate([
                'backup_path' => 'required|string'
            ]);

            $this->settingService->deleteBackup($request->input('backup_path'));

            return redirect()->back()->with('success', 'Backup deleted successfully');

        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Backup deletion failed: ' . $e->getMessage());
        }
    }

    public function runMaintenance()
    {
        try {
            $this->settingService->runMaintenanceTasks();

            return redirect()->back()->with('success', 'Maintenance tasks completed successfully');

        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Maintenance tasks failed: ' . $e->getMessage());
        }
    }
}
