<?php

use Doctrine\ORM\EntityRepository;

class HolidayRepository extends EntityRepository
{

    public function addHoliday($body)
    {
        $entityManager = $this->getEntityManager();
        $date = addslashes(strip_tags(trim($body['date'])));
        $holiday = addslashes(strip_tags(trim($body['holiday'])));
       

        if (sizeof($this->checkHolidayForEntry($body)) == 0) {
            $leave = new Holiday();
            $leave->setDate($date);
            $leave->setHoliday($holiday);
            $entityManager->persist($leave);
            $entityManager->flush();
            return "Registered Successfully.";
        }

    }

    public function getHolidays()
    {
        $dql = "SELECT r.id,r.date,r.holiday From Holiday r";
        $query = $this->getEntityManager()->createQuery($dql);
        return $query->getResult();
    }

    public function getHolidayForEdit($id)
    {
        $dql = "SELECT r from Holiday r where r.id=:id";
        $query = $this->getEntityManager()->createQuery($dql)->setParameter('id', $id);
        return $query->getResult();
    }

    public function checkHoliday($date)
    {
        $dql = "SELECT r.id,r.date,r.holiday From Holiday r WHERE r.date=:date";
        $query = $this->getEntityManager()->createQuery($dql)
            ->setParameter('date', $date);
        $r = $query->getResult();
        if(sizeof($r) > 0){
            return $r[0]['holiday'];
        }else{
            return null;
        }
    }

    

    public function updateHoliday($id, $body)
    {
        $entityManager = $this->getEntityManager();
        $date = addslashes(strip_tags(trim($body['date'])));
        $holiday = addslashes(strip_tags(trim($body['holiday'])));
        

        $result = $this->getHolidayForEdit($id);
        if (sizeof($result) == 1) {

            $result[0]->setDate($date);
            $result[0]->setHoliday($holiday);
           
            $entityManager->persist($result[0]);
            $entityManager->flush();
            return "Updated Successfully.";
        }

    }

    public function deleteHoliday($id)
    {
        $dql = "DELETE FROM Holiday r WHERE r.id=:id";
        $query = $this->getEntityManager()->createQuery($dql)->setParameter('id', $id);
        $query->getResult();
        return "Succesfully deleted";
    }

    public function checkHolidayForEntry($body)
    {
        $date = addslashes(strip_tags(trim($body['date'])));
        

        $dql = 'SELECT r FROM Holiday r WHERE r.date=:date';
        $query = $this->getEntityManager()->createQuery($dql)
            ->setParameter('date', $date);
        return $query->getResult();
    }

}
