<?php

use Doctrine\ORM\EntityRepository;

class CertificateTypeRepository extends EntityRepository
{

    public function addType($body)
    {
        $entityManager = $this->getEntityManager();
        $type_name = addslashes(strip_tags(trim($body['type_name'])));
        
        if (sizeof($this->checkAccountsHead($body)) == 0) {
            $access = new CertificateType();
            $access->setTypeName($type_name);
           
            $entityManager->persist($access);
            $entityManager->flush();
            return 'Sucessfully Inserted';
        } else {
            return 'Already Exists';
        }

    }

    public function getCertificateType()
    {
        $dql = "SELECT r.id,r.type_name FROM CertificateType r ORDER BY r.type_name";
        $query = $this->getEntityManager()->createQuery($dql);
        return $query->getResult();
    }
    private function getTypeForEdit($id)
    {
        $dql = "SELECT r FROM CertificateType r WHERE r.id=:id";
        $query = $this->getEntityManager()->createQuery($dql)->setParameter('id', $id);
        return $query->getResult();
    }

    public function getCertificateTypeSingle($id)
    {
        $dql = "SELECT r.id,r.type_name FROM CertificateType r WHERE r.id=:id";
        $query = $this->getEntityManager()->createQuery($dql)->setParameter('id', $id);
        return $query->getResult();
    }

    public function updateCertificateType($id, $body)
    {
        $entityManager = $this->getEntityManager();

        $id = addslashes(strip_tags(trim($body['id'])));
        $type_name = addslashes(strip_tags(trim($body['type_name'])));
        

        $result = $this->getTypeForEdit($id);

        if (sizeof($result) == 1) {
            $result[0]->setTypeName($type_name);
           
            $entityManager->persist($result[0]);
            $entityManager->flush();
            return "Updated Successfully.";
        } else {
            return "Not Found.";
        }

    }

    public function checkAccountsHead($body)
    {
        $type_name = addslashes(strip_tags(trim($body['type_name'])));
       

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

    public function deleteCertificateType($id)
    {
        $dql = 'DELETE FROM CertificateType r WHERE r.id=:id';
        $query = $this->getEntityManager()->createQuery($dql)->setParameter('id', $id);
        $query->getResult();
        return 'Successfully Deleted';
    }
}
