<?php

use Doctrine\ORM\EntityRepository;

class StudentSubjectsRepository extends EntityRepository
{

    public function addStudentSubject($student_id, $semester, $subjects)
    {
        $entityManager = $this->getEntityManager();

        $r = $this->checkIfAlreadyExists($student_id, $semester);
        if (sizeof($r) > 0) {
            $ot = $r[0];
            $ot->setStudentId($student_id);
            $ot->setSemester($semester);
            $ot->setSubjects($subjects);
            $entityManager->persist($ot);
            $entityManager->flush();
            return true;
        } else {
            // new 

            $ot = new StudentSubjects();
            $ot->setStudentId($student_id);
            $ot->setSemester($semester);
            $ot->setSubjects($subjects);
            $entityManager->persist($ot);
            $entityManager->flush();
            return true;
        }
    }

    private function checkIfAlreadyExists($student_id, $semester)
    {
        $dql = 'SELECT r From StudentSubjects r where r.student_id=:student_id AND r.semester=:semester';
        $query = $this->getEntityManager()->createQuery($dql)
            ->setParameter('semester', $semester)
            ->setParameter('student_id', $student_id);
        return $query->getResult();
    }

    public function getStudentSubject($student_id, $semester)
    {
        $dql = 'SELECT r.subjects From StudentSubjects r where r.student_id=:student_id AND r.semester=:semester';
        $query = $this->getEntityManager()->createQuery($dql)
            ->setParameter('semester', $semester)
            ->setParameter('student_id', $student_id);
        $result = $query->getResult();
        if(sizeof($result) > 0){
            return $result[0]['subjects'];
        }else{
            return [];
        }
    }
}
