<?php

namespace App\Livewire\Admin;

use App\Models\AppVersion;
use Livewire\Component;

class Versions extends Component
{
    public string  $version    = '';
    public string  $name       = '';
    public string  $changelog  = '';
    public string  $status     = 'draft';
    public string  $platform   = 'all';
    public bool    $show_popup = true;
    public ?string $editingId  = null;

    public function getVersionsProperty()
    {
        return AppVersion::latest()->get();
    }

    public function save(): void
    {
        $this->validate([
            'version'  => 'required',
            'name'     => 'required',
            'status'   => 'required|in:draft,beta,live,rollback',
            'platform' => 'required|in:all,web,app',
        ]);

        $data = [
            'version'     => $this->version,
            'name'        => $this->name,
            'changelog'   => $this->changelog,
            'status'      => $this->status,
            'platform'    => $this->platform,
            'show_popup'  => $this->show_popup,
            'released_at' => $this->status === 'live' ? now() : null,
        ];

        if ($this->editingId) {
            AppVersion::find($this->editingId)->update($data);
        } else {
            AppVersion::create($data);
        }

        $this->reset(['version', 'name', 'changelog', 'show_popup', 'editingId']);
        $this->status   = 'draft';
        $this->platform = 'all';
    }

    public function setLive(string $id): void
    {
        AppVersion::find($id)->update([
            'status'      => 'live',
            'released_at' => now(),
        ]);
    }

    public function edit(string $id): void
    {
        $v = AppVersion::find($id);
        $this->editingId  = $id;
        $this->version    = $v->version;
        $this->name       = $v->name;
        $this->changelog  = $v->changelog ?? '';
        $this->status     = $v->status;
        $this->platform   = $v->platform;
        $this->show_popup = $v->show_popup;
    }

    public function delete(string $id): void
    {
        AppVersion::find($id)->delete();
    }

    public function render()
    {
        return view('livewire.admin.versions')
            ->layout('layouts.app');
    }
}
