<?php

namespace App\Orchid\Screens\Product;

use Orchid\Screen\TD;
use App\Models\Product;
use Orchid\Screen\Screen;
use Illuminate\Support\Str;
use Orchid\Screen\Fields\Input;
use Orchid\Screen\Actions\Link;
use Orchid\Support\Facades\Alert;
use Orchid\Screen\Actions\Button;
use Orchid\Support\Facades\Layout;
use Orchid\Screen\Actions\DropDown;
use Illuminate\Support\Facades\File;
use App\Orchid\Layouts\Product\ProductListLayout;

class ProductListScreen extends Screen {
  public $products;

  public function query(): iterable {
    return [
      'products' => Product::filters()->defaultSort('created_at', 'desc')->paginate(10),
    ];
  }

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

  public function commandBar(): iterable {
    return [
      Link::make('Create new')
        ->icon('bs.plus-circle')
        ->route('platform.product.create')
    ];
  }

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

  public function remove(Product $product) {
    // Delete single image
    $image_path = $product->image;
    $image_path = str_replace(asset(''), '', $image_path);
    $images = json_decode($product->images);
    $imagesCount = count($images);
    File::exists($image_path) && File::delete($image_path);

    // Delete multiple images
    if ($imagesCount > 0) {
      foreach ($images as $image) {
        $image_from_array = str_replace(asset(''), '', $image);
        File::delete($image_from_array);
      }
    }

    $product->delete();
    Alert::info('You have successfully deleted the product.');
    return redirect()->route('platform.product.list');
  }
}
