<?php

use Doctrine\ORM\EntityRepository;

class AssignmentSubmissionRepository extends EntityRepository
{

    public function submitAssignment($student_id, $body)
    {
        $em = $this->getEntityManager();

        $assignment_id_id = addslashes(strip_tags(trim($body['assignment_id'])));
        $assignment = $em->find('Assignment', $assignment_id_id);
        $assignment_text = addslashes(strip_tags(trim($body['assignment_text'])));
        $upload_info = $body['upload_info'];
        $submission_date = date('d-m-Y');
        $time_stamp = date('d-m-Y H:i:s');
        $checked = 0;

        if ($this->checkAssignment($student_id, $assignment_id_id)) {
            $obj = new AssignmentSubmission();

            $obj->setAssignment($assignment);
            $obj->setStudentId($student_id);
            $obj->setSubmissionDate($submission_date);
            $obj->setAssignmentText($assignment_text);
            $obj->setUploadInfo($upload_info);
            $obj->setTimeStamp($time_stamp);
            $obj->setChecked($checked);

            $em->persist($obj);
            $em->flush();

            $b = [];
            $b['status'] = true;
            $b['status_text'] = 'Successfully Submitted';
        } else {
            $b = [];
            $b['status'] = false;
            $b['status_text'] = 'You have already submitted your assignment';
        }
        return $b;
    }

    public function checkAssignment($student_id, $assignment_id)
    {
        $dql = "SELECT count(r.id) as c FROM AssignmentSubmission r WHERE r.assignment_id=:assignment_id AND r.student_id=:student_id";
        $query = $this->getEntityManager()->createQuery($dql)
            ->setParameter('assignment_id', $assignment_id)->setParameter('student_id', $student_id);
        $r = $query->getResult();
        if ($r[0]['c'] > 0) {
            return false;
        } else {
            return true;
        }
    }

    public function getCheckedValue($student_id, $assignment_id)
    {
        $dql = "SELECT r.checked FROM AssignmentSubmission r WHERE r.assignment_id=:assignment_id AND r.student_id=:student_id";
        $query = $this->getEntityManager()->createQuery($dql)
            ->setParameter('assignment_id', $assignment_id)->setParameter('student_id', $student_id);
        $r = $query->getResult();
        if (sizeof($r) > 0) {
            $c = $r[0]['checked'];
            if($c == NULL){
                return 0;
            }else{
                return 1;
            }
        }else{
            return 0;
        }
    }
}
