<?php

namespace App\Livewire\Admin;

use Livewire\Component;
use Livewire\WithPagination;
use App\Models\Promotion;

class Promotions extends Component
{
    use WithPagination;

    protected $paginationTheme = 'tailwind';

    public $showModal = false;
    public $editMode = false;

    public $promotionId;
    public $name;
    public $discount_percent;
    public $valid_from;
    public $valid_to;
    public $active = true;

    protected function rules()
    {
        return [
            'name' => 'required|string|min:3',
            'discount_percent' => 'required|numeric|min:1|max:100',
            'valid_from' => 'nullable|date',
            'valid_to' => 'nullable|date|after_or_equal:valid_from',
            'active' => 'boolean',
        ];
    }

    public function render()
    {
        return view('livewire.admin.promotions', [
            'promotions' => Promotion::orderBy('created_at', 'desc')->paginate(10),
        ]);
    }

    public function create()
    {
        $this->resetFields();
        $this->editMode = false;
        $this->showModal = true;
    }

    public function edit(Promotion $promotion)
    {
        $this->promotionId = $promotion->id;
        $this->name = $promotion->name;
        $this->discount_percent = $promotion->discount_percent;
        $this->valid_from = optional($promotion->valid_from)->format('Y-m-d');
        $this->valid_to = optional($promotion->valid_to)->format('Y-m-d');
        $this->active = $promotion->active;

        $this->editMode = true;
        $this->showModal = true;
    }

    public function save()
    {
        $this->validate();

        Promotion::updateOrCreate(
            ['id' => $this->promotionId],
            [
                'name' => $this->name,
                'discount_percent' => $this->discount_percent,
                'valid_from' => $this->valid_from,
                'valid_to' => $this->valid_to,
                'active' => $this->active,
            ]
        );

        $this->showModal = false;
        $this->resetFields();
    }

    public function toggle(Promotion $promotion)
    {
        $promotion->update([
            'active' => ! $promotion->active
        ]);
    }

    private function resetFields()
    {
        $this->reset([
            'promotionId',
            'name',
            'discount_percent',
            'valid_from',
            'valid_to',
            'active',
        ]);
    }
}
