<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        // return view('home');
       return redirect('/admin');
    }

    public function backupTenant($tenantId=null) {
        // 1. Identificazione del tenant
        if (!isset($tenantId)){
            $tenantId = tenant()->id;
        }
        $tenant = Tenant::find($tenantId);
        if (!$tenant) {
            return 'Tenant non trovato.';
        }

        // 2. Switch al tenant
        tenancy()->initialize($tenant);

        // 3. Generazione del nome del file zip
        $fileName = $tenantId . '_' . date('YmdHms') . '.zip';
        $zipPath = storage_path('app/' . $fileName);

        // 4. Creazione dell'archivio zip
        $zip = new ZipArchive;
        if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
            return 'Impossibile creare l\'archivio zip.';
        }

        // 5. Dump del database
        $databaseName = config('database.connections.tenant.database'); // Assumi 'tenant' come connessione per i tenant
        $dumpFile = storage_path('app/temp_dump.sql');
        $command = "mysqldump -u " . config('database.connections.tenant.username') . " -p" . config('database.connections.tenant.password') . " " . $databaseName . " > " . $dumpFile;
        exec($command);
        $zip->addFile($dumpFile, 'database.sql');

        // 6. Aggiunta della cartella storage
        //$storagePath = storage_path('app/tenant/' .$tenantId); // Assumi una struttura di storage separata per tenant
        $storagePath = storage_path();
        $files = \File::allFiles($storagePath);
        foreach ($files as $file) {
            $relativePath = str_replace($storagePath . '/', '', $file->getPathname());
            $zip->addFile($file->getPathname(), 'storage/' . $relativePath);
        }

        // 7. Chiusura dell'archivio zip
        $zip->close();

        // 8. Download del file
       // dd($zipPath);
        return response()->download($zipPath, $fileName, [
            'Content-Type' => 'application/zip',
            'Content-Disposition' => 'attachment; filename="' . $fileName . '"',
        ])->deleteFileAfterSend(true); // Cancella il file dopo il download
    }
}
