<?php

namespace App\Http\Controllers;

use App\Models\CentralTenant;
use Illuminate\Http\Request;
use App\Models\Tenant;
use Illuminate\Support\Facades\Artisan; // Include the Artisan facade

class CentralTenantController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        // Ritorna la lista dei tenants attivi
        return view('centraltenant.index', ['tenants' => CentralTenant::listTenants()]);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //Ritorna la view del form per la creazione di un nuovo tenant
        return view('centraltenant.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        //
        $validated = $request->validate([
            'tenant_name' => 'required | unique:tenants,id',
            'fqdn_domain' => 'required | unique:domains,domain'
        ]);

        $tenant1 = Tenant::create(['id' => $request->tenant_name]);
        $tenant1->domains()->create(['domain' => $request->fqdn_domain]);
        Artisan::call('tenants:migrate', ['--tenants' => $request->tenant_name]);
        Artisan::call('tenants:seed', ['--tenants' => $request->tenant_name]);
        /*Artisan::call('tenants:run storage:link', ['--tenants' => $request->tenant_name]);*/

        return redirect()->route('home.index');
    }

    /**
     * Display the specified resource.
     */
    public function show(CentralTenant $centralTenant)
    {
        //
        return view('centraltenant.show', ['tenant' => $centralTenant]);
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit($home)
    {
        //
        return view('centraltenant.edit', ['tenant' => \App\Models\CentralTenant::getTenant($home)]);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, CentralTenant $centralTenant)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($home)
    {
        // dd($home);
        //$tenant1 = Tenant::create(['id' => $request->tenant_name]);
        $tenant1 = Tenant::destroy(['id' => $home]);
        return redirect()->route('home.index');
    }

    public function backupTenant($home)
    {

        $tenant = CentralTenant::backupTenant($home);
        /*$tenant->backup();
        return redirect()->route('home.index');
        */
    }
}
