<?php

namespace App\Orchid\Screens\Brand;

use App\Models\Brand;
use Orchid\Screen\Screen;
use Illuminate\Http\Request;
use Orchid\Support\Facades\Alert;
use Orchid\Screen\Actions\Button;
use App\Orchid\Layouts\Brand\BrandEditLayout;

class BrandEditScreen extends Screen {
  public $brand;

  public function query(Brand $brand): iterable {
    return [
      'brand' => $brand,
    ];
  }

  public function name(): ?string {
    return 'Edit brand';
  }

  public function commandBar(): iterable {
    return [
      Button::make('Update')
        ->icon('note')
        ->method('update'),

      Button::make('Remove')
        ->icon('trash')
        ->method('remove')
        ->confirm('Are you sure you want to delete this brand ?'),
    ];
  }

  public function layout(): iterable {
    return [
      BrandEditLayout::class,
    ];
  }

  public function update(Request $request) {

    $request->validate([
      'brand.name' => 'required|unique:brands,name,' . $this->brand->id,
    ]);

    $this->brand->name = ucwords($request->input('brand.name'));

    $this->brand->save();
    Alert::info('You have successfully updated the brand.');
    return redirect()->route('platform.brand.list');
  }

  public function remove() {
    $this->brand->delete();
    Alert::info('You have successfully deleted the brand.');
    return redirect()->route('platform.brand.list');
  }
}
