<?php

namespace Repositories;

use Doctrine\ORM\EntityRepository;

/**
 * ContactRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class ContactRepository extends EntityRepository
{
    /**
     * Get Contact
     * 
     * @param int $id
     * @return array
     */
    public function get($id) {
        $qb = $this->createQueryBuilder('c');
        $qb->select('c, m')
           ->leftJoin('c.message', 'm')
           ->where('c.id = :id')
           ->setParameter('id', $id);
        $contactTemp = $qb->getQuery()->getArrayResult();
        return $contactTemp[0];
    }
    
    /**
     * Get all contact
     * 
     * @return array
     */
    public function getAll() {
        $qb = $this->createQueryBuilder('c');
        $qb->select('c,m')
                ->leftJoin('c.message', 'm');
        return $qb->getQuery()
                ->getArrayResult();
    }
    
    /**
     * Delete contact by its ID
     * 
     * @param int $id
     * @param string $name
     * @return array
     */
    public function delete($id, $name) {
        $alert = [
            'type' => 'success',
            'msg' => '<strong><i class="fa fa-check"></i></strong> Le contact ' . $name . ' a été supprimé avec succès.'
        ];
        $em = $this->getEntityManager();
        $cnx = $em->getConnection();
        $cnx->beginTransaction();
        try {
            $em->remove($this->find($id));
            $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 recommencer plutard.'
            ];
        }
        return $alert;
    }
}