<?php

namespace Bixo\Niche\Actions;

use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
use Litepie\Actions\Concerns\AsAction;
use Bixo\Niche\Models\Niche;


class NicheAction
{
    use AsAction;

    protected $model;
    protected $namespace = 'bixo.niche.niche';
    protected $eventClass = \Bixo\Niche\Events\NicheAction::class;
    protected $action;
    protected $function;
    protected $request;

    public function handle(string $action, Niche $niche, array $request = [])
    {
        $this->action = $action;
        $this->request = $request;
        $this->model = $niche;
        $this->function = Str::camel($action);
        $this->executeAction();
        return $this->model;

    }


    public function store(Niche $niche, array $request)
    {
        $attributes = $request;
        $attributes['user_id'] = user_id();
        $attributes['user_type'] = user_type();
        $niche = $niche->create($attributes);
        return $niche;
    }

    public function update(Niche $niche, array $request)
    {
        $attributes = $request;
        $niche->update($attributes);
        return $niche;
    }

    public function destroy(Niche $niche, array $request)
    {
        $niche->delete();
        return $niche;
    }

    public function copy(Niche $niche, array $request)
    {
        $count = $request['count'] ?: 1;

        if ($count == 1) {
            $niche = $niche->replicate();
            $niche->created_at = Carbon::now();
            $niche->save();
            return $niche;
        }

        for ($i = 1; $i <= $count; $i++) {
            $new = $niche->replicate();
            $new->created_at = Carbon::now();
            $new->save();
        }

        return $niche;
    }


}