<?php

namespace App\Livewire;

use App\Models\Application;
use Flux\Flux;
use Illuminate\Database\Eloquent\Collection;
use Livewire\Attributes\On;
use Livewire\Component;

class AppContainer extends Component
{
    public Collection $apps;
    public ?Application $confirmDeleteApp;

    public function mount()
    {
        // Only load data if user is authorized to view it
        if (auth()->user()->can('viewAny', Application::class)) {
            $this->loadApps();
        }
    }

    public function loadApps()
    {
        $this->apps = Application::orderBy('id')->get();
    }

    #[On('app-updated')]
    public function handleAppUpdated($id)
    {
        $new = Application::find($id);
        $this->apps = $this->apps->map(fn($app) => $app->id == $id ? $new : $app);
    }

    public function confirmDelete($id)
    {
        $this->confirmDeleteApp = $this->apps->where('id', $id)->first();
        Flux::modal('delete-app-confirm')->show();
    }

    public function deleteApp()
    {
        $this->authorize('delete', $this->confirmDeleteApp);

        $this->confirmDeleteApp->delete();
        $deletedId = $this->confirmDeleteApp->id;
        $this->confirmDeleteApp = null;
        $this->apps = $this->apps->filter(fn($app) => $app->id != $deletedId);
        Flux::modal('delete-app-confirm')->close();
    }

    public function cancelDelete()
    {
        $this->confirmDeleteApp = null;
        Flux::modal('delete-app-confirm')->close();
    }

    public function render()
    {
        return view('livewire.app-container');
    }
}
