<?php

namespace Repositories;

use Doctrine\ORM\EntityRepository;

/**
 * CvpdfRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class CvpdfRepository extends EntityRepository
{
    public function get() {
        $qb = $this->createQueryBuilder('c')
                ->select('c, r')
                ->leftJoin('c.resource', 'r');
        $picture = $qb->getQuery()->getArrayResult();
        return $picture[0];
    }
    
    public function update($thumb_id) {
        $alert = [
            'type' => 'success',
            'msg' => '<strong><i class="fa fa-check"></i></strong> Le CV a été modifié avec succès.'
        ];
        $em = $this->getEntityManager();
        $cnx = $em->getConnection();
        $cnx->beginTransaction();
        try {
            $EntityTmp = $em->getRepository('Entities\Cvpdf')->findAll();
            $entity = $EntityTmp[0];
            
            if ($thumb_id != null) {
                $thumb = $em->getRepository('Entities\Resource')->findOneBy(['id' => $thumb_id]);
                $entity->setResource($thumb);
            }
            $em->persist($entity);
            $em->flush();
            $cnx->commit();
        } catch (Exception $ex) {
            $cnx->rollback();
            $alert = [
                'type' => 'danger',
                'msg' => '<strong><i class="fa fa-warning"></i></strong> Une erreur interne est survenus, veuillez recommancer plutard.'
            ];
        }
        return $alert;
    }

    public function dumpCvPdf() {
        $em = $this->getEntityManager();
        $cv = [
            [
                'resource' => [
                    [
                        'name' => 'CV+photo.pdf'
                    ]
                ]
            ]
        ];
        foreach ($cv as $c) {
            $entity = new \Entities\Cvpdf();

            foreach ($c['resource'] as $thumb) {
                $thumbnail = new \Entities\Resource();
                $thumbnail->setName($thumb['name']);
                $em->persist($thumbnail);
                $entity->setResource($thumbnail);
            }

            $em->persist($entity);
            $em->flush();
        }
    }
}