<?php
namespace Modules\Appointment\Repositories\Eloquents;

use App\User;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Modules\Appointment\Entities\TimeSlot;
use App\Repositories\Eloquents\BaseRepository;
use Modules\Appointment\Repositories\Interfaces\TimeSlotRepositoryInterface;
use Modules\Appointment\Repositories\Interfaces\InstructorRepositoryInterface;

class TimeSlotRepository extends BaseRepository implements TimeSlotRepositoryInterface
{
    protected $user;
    public function __construct(
        TimeSlot $model,
        User $user,
        InstructorRepositoryInterface $instructorRepository
    ) {
        parent::__construct($model);
        $this->user = $user;
        $this->instructorRepository = $instructorRepository;
    }

    public function create(array $playLoad): ?Model
    {

        return $this->model->create($this->formatParams($playLoad));
    }

    private function formatParams($playLoad, $modelId = null): array
    {

        $end_time =  gv($playLoad, 'end_time')
        ? Carbon::parse(gv($playLoad, 'end_time'))->format('H:i')
        : Carbon::parse(gv($playLoad, 'start_time'))->addHour(1)->format('H:i');
        $formatParams = [
            'start_time' => Carbon::parse(gv($playLoad, 'start_time'))->format('H:i'),
            'end_time' => $end_time,
            'updated_by'=>auth()->user()->id,
            'user_id' => gv($playLoad, 'user') ?? auth()->user()->id,
        ];
        if (!$modelId) {
            $formatParams['created_by'] = auth()->user()->id;
        }
        return $formatParams;
    }

    public function update(int $modelId, array $playLoad): bool
    {
        $model = $this->findById($modelId);
        return $model->update($this->formatParams($playLoad, $modelId));
    }

    public function getEditValue($modelId): array
    {
        $data = $this->index();
        $data['editTimeSlot'] = $this->model->when(auth()->user()->role_id !=1, function ($query) {
            $query->where('created_by', auth()->user()->id);
        })->where('id', $modelId)->first();
        return $data;
    }

    public function index(): array
    {
        $data = $this->instructorRepository->instructors();
        $data['timeSlots'] = $this->model->when(auth()->user(), function ($query) {
            $query->when(auth()->user()->role_id != 1, function ($query) {
                $query->where('user_id', auth()->user()->id);
            });
        })->get();

        return $data;
    }

    private function exitSlot($start_time): bool
    {
        return true;
    }
}
