<?php

use Doctrine\ORM\EntityRepository;

class DepartmentRepository extends EntityRepository
{

    public function addDept($body){
        $entityManager = $this->getEntityManager(); 
        $dept_code = addslashes(strip_tags(trim($body['dept_code'])));
        $is_teaching = addslashes(strip_tags(trim($body['is_teaching'])));
        $dept_name = addslashes(strip_tags(trim($body['dept_name'])));
        
        if(sizeof($this->checkDept($dept_code))==0){
        $dept = new Department();
        $dept->setDeptCode($dept_code);  
        $dept->setDeptName($dept_name);
        $dept->setIsTeaching($is_teaching);    
        $entityManager->persist($dept);
        $entityManager->flush();
        return "Department Registered Successfully.";
        }
        else 
        return "Department already registered.";
    }

    public function getDept()
    {
        $dql = "SELECT r.id,r.dept_code,r.dept_name,r.is_teaching From Department r ORDER BY r.dept_name ASC";
        $query =  $this->getEntityManager()->createQuery($dql);
        return $query->getResult();
    }
    private function getDeptForEdit($dept_code)
    {
        $dql = "SELECT r From Department r where r.dept_code=:dept_code";
        $query =  $this->getEntityManager()->createQuery($dql)->setParameter('dept_code',$dept_code);
        return $query->getResult();
    }

    public function getDeptSingle($dept_code)
    {
        $dql = "SELECT r.id,r.dept_code,r.dept_name,r.is_teaching From Department r where r.dept_code=:dept_code";
        $query = $this->getEntityManager()->createQuery($dql)->setParameter('dept_code', $dept_code);
        return $query->getResult();
    }

    public function updateDept($dept_code,$body)
    {   $entityManager = $this->getEntityManager(); 
       
        $dept_name = addslashes(strip_tags(trim($body['dept_name'])));
        $is_teaching = addslashes(strip_tags(trim($body['is_teaching'])));
        $result = $this->getDeptForEdit($dept_code);
        
        if(sizeof($result)==1){
            
            $result[0]->setDeptName($dept_name);
            $result[0]->setIsTeaching($is_teaching);
            $entityManager->persist($result[0]);
            $entityManager->flush();
            return "Department Updated Successfully.";
            }
            else 
            return "Not found";
    }

    public function checkDept($dept_code){
        $dql = 'SELECT r FROM Department r WHERE r.dept_code=:dept_code';
        $query = $this->getEntityManager()->createQuery($dql)->setParameter('dept_code', $dept_code);
        return $query->getResult();
    }

    public function deleteDept($dept_code){
        $dql = 'DELETE FROM Department r WHERE r.dept_code=:dept_code';
        $query = $this->getEntityManager()->createQuery($dql)->setParameter('dept_code', $dept_code);
        $query->getResult();
        return true;
    }
}