<?php

namespace App\Http\Controllers\Settings;

use App\Http\Controllers\Controller;
use App\Models\Setting;
use App\Services\BackupService;
use Illuminate\Http\Request;

class BackupController extends Controller
{
    protected $backupService;

    public function __construct(BackupService $backupService)
    {
        $this->backupService = $backupService;
    }

    public function index()
    {
        $settings = Setting::getGroup('backup');
        return view('settings.backup.index', compact('settings'));
    }

    public function update(Request $request)
    {
        $validated = $request->validate([
            'email_enabled' => 'nullable|in:0,1',
            'email_address' => 'nullable|email',
            'ftp_enabled' => 'nullable|in:0,1',
            'ftp_host' => 'nullable|string',
            'ftp_username' => 'nullable|string',
            'ftp_password' => 'nullable|string',
            'ftp_path' => 'nullable|string',
        ]);

        // Convert checkboxes
        $data = [
            'email_enabled' => $request->has('email_enabled') ? 1 : 0,
            'email_address' => $validated['email_address'],
            'ftp_enabled' => $request->has('ftp_enabled') ? 1 : 0,
            'ftp_host' => $validated['ftp_host'],
            'ftp_username' => $validated['ftp_username'],
            'ftp_password' => $validated['ftp_password'],
            'ftp_path' => $validated['ftp_path'],
        ];

        Setting::setGroup('backup', $data);

        return back()->with('success', 'Backup settings updated successfully.');
    }

    public function download()
    {
        $result = $this->backupService->createBackup('manual');

        if ($result['success']) {
            return response()->download($result['path'], $result['filename']);
        }

        return back()->with('error', 'Backup failed: ' . ($result['message'] ?? 'Unknown error'));
    }
}
