<?php

namespace App\Orchid\Screens\Promocode;

use Orchid\Screen\Screen;
use App\Orchid\Layouts\Promocode\PromocodeCreateLayout;

use App\Models\Promocode;
use Illuminate\Http\Request;
use Orchid\Screen\Actions\Button;
use Orchid\Support\Facades\Alert;

class PromocodeCreateScreen extends Screen {
  public $promocode;

  public function query(Promocode $promocode): iterable {
    return [
      'promocode' => $promocode
    ];
  }

  public function name(): ?string {
    return 'Creating a new promocode';
  }

  public function commandBar(): iterable {
    return [
      Button::make('Create promocode')
        ->icon('pencil')
        ->method('create')
    ];
  }

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

  public function create(Request $request) {

    $request->validate([
      'promocode.code' => 'required|unique:promocodes,code,' . $this->promocode->id,
      'promocode.discount' => 'required|numeric|min:1|max:100',
    ]);


    $this->promocode->code = $request->input('promocode.code');
    $this->promocode->discount = $request->input('promocode.discount');
    $this->promocode->expires_at = $request->input('promocode.expires_at');

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