<?php

namespace App\Repositories;

use App\CalendarTemplate;
use App\CalendarTemplateExclusion;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class CalendarTemplateRepository implements RepositoryInterface{
    public static function all() {
        return CalendarTemplate::all();
    }

    public static function create(array $data){

        $exclusions = [];
        if(isset($data["calendar_template_exclusions"])) {
            $exclusions = $data["calendar_template_exclusions"];
            unset($data["calendar_template_exclusions"]);
        }

        DB::beginTransaction();
        try {
            $template = CalendarTemplate::create($data);

            foreach($exclusions as $excl) {
                $excl["calendar_template_id"] = $template->id;
                CalendarTemplateExclusion::create($excl);
            }
        }
        catch(\Exception $e) {
            DB::rollBack();
            throw $e;
        }
        DB::commit();

        return CalendarTemplate::find($template->id);
    }

    public static function update(array $data, $id){
        $template = CalendarTemplate::findOrFail($id);
        $exclusions = [];
        if(isset($data["calendar_template_exclusions"])) {
            $exclusions = $data["calendar_template_exclusions"];
            unset($data["calendar_template_exclusions"]);
        }

        DB::beginTransaction();
        try {
            $template->update($data);
            $template->calendarTemplateExclusions()->delete();

            foreach($exclusions as $excl) {
                $excl["calendar_template_id"] = $template->id;
                CalendarTemplateExclusion::create($excl);
            }
        }
        catch(\Exception $e) {
            DB::rollBack();
            throw $e;
        }
        DB::commit();

        return CalendarTemplate::find($template->id);
    }

    public static function delete($id){
        return CalendarTemplate::destroy($id);
    }

    public static function find($id){
        return CalendarTemplate::findOrFail($id);
    }

    public static function box($id) {
        return CalendarTemplate::findOrFail($id)->box;
    }

    public static function isExcluded(CalendarTemplate $ct, Carbon $datetime) {
        foreach($ct->calendarTemplateExclusions as $cte) {
            $start_time = $datetime->copy()->setTimeFromTimeString($cte->start_time_exclusion);
            $end_time = $datetime->copy()->setTimeFromTimeString($cte->end_time_exclusion);
            if($start_time <= $datetime && $end_time > $datetime) {
                return true;
            }
        }
        return false;
    }

}
