<?php

namespace App\Orchid\Layouts\Product;

use Orchid\Screen\Layouts\Table;
use Orchid\Screen\TD;

use App\Models\Product;
use Illuminate\Support\Str;
use Orchid\Screen\Fields\Input;
use Orchid\Screen\Actions\Link;
use Orchid\Screen\Actions\Button;
use Orchid\Screen\Actions\DropDown;

class ProductListLayout extends Table {

  protected $target = 'products';

  protected function columns(): iterable {
    return [
      TD::make('image', 'Image')
        ->cantHide()
        ->render(function (Product $product) {
          return '<img src="' . $product->image . '" width="50" height="50" style="object-fit: cover; object-position: center;">';
        }),

      TD::make('name', 'Name')
        ->sort()
        ->cantHide()
        ->filter(Input::make())
        ->render(function (Product $product) {
          return Link::make(Str::limit(Str::ucfirst($product->name), 25))->route('platform.product.edit', $product->id);
        }),

      TD::make('price', 'Price')
        ->sort()
        ->cantHide()
        ->filter(Input::make())
        ->render(function (Product $product) {
          return Link::make('$' . " " . $product->price)->route('platform.product.edit', $product->id);
        }),

      TD::make('old_price', 'Old price')
        ->cantHide()
        ->sort()
        ->filter(Input::make())
        ->render(function (Product $product) {
          return $product->old_price ? '$' . " " . "<strike>$product->old_price</strike>"  : '-';
        }),

      TD::make('updated_at', __('Last edit'))
        ->cantHide()
        ->sort()
        ->filter(Input::make())
        ->render(function (Product $product) {
          return $product->updated_at->format('M j, Y');
        }),

      TD::make('id', 'ID')
        ->cantHide()
        ->sort()
        ->align(TD::ALIGN_CENTER)
        ->filter(Input::make())
        ->render(function (Product $product) {
          return '#' . $product->id;
        }),

      TD::make(__('Actions'))
        ->cantHide()
        ->align(TD::ALIGN_CENTER)
        ->width('100px')
        ->render(fn (Product $product) => DropDown::make()
          ->icon('bs.three-dots-vertical')
          ->list([
            Link::make(__('Edit'))
              ->route('platform.product.edit', $product->id)
              ->icon('bs.pencil'),
            Button::make('Delete')
              ->icon('bs.trash3')
              ->confirm('Are you sure you want to delete this product ?')
              ->method('remove')
              ->parameters([
                'product' => $product->id,
              ]),
          ])),
    ];
  }
}
