<?php

namespace Repositories;

use Doctrine\ORM\EntityRepository;

/**
 * MessageRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class MessageRepository extends EntityRepository
{
    
    /**
     * Get Message
     * 
     * @param int $id
     * @return array
     */
    public function get($id) {
        $qb = $this->createQueryBuilder('m');
        $qb->select('m, c')
           ->leftJoin('m.contact', 'c')
           ->where('m.id = :id')->setParameter('id', $id);
        $messageTemp = $qb->getQuery()->getArrayResult();
        $this->setAsNotNew($id);
        return $messageTemp[0];
    }
    
    /**
     * Get all message
     * 
     * @return array
     */
    public function getAll() {
        $qb = $this->createQueryBuilder('m');
        $qb->select('m, c')
           ->leftJoin('m.contact', 'c')
           ->orderBy('m.is_new', 'DESC')
           ->addOrderBy('m.sent', 'DESC');
        return $qb->getQuery()->getArrayResult();
    }
    
    /**
     * Add new message
     * 
     * @param array $cnt
     * @param array $msg
     * @return array
     */
    public function setMessage($cnt, $msg) {
       
        $em = $this->getEntityManager();
        $cnx = $em->getConnection();
        $cnx->beginTransaction();
        try {
            if (!$contact = $em->getRepository('Entities\Contact')->findOneBy(['email' => trim($cnt['email']), 'phone' => trim($cnt['phone'])])) {
                $contact = new \Entities\Contact();
                $contact->setName($cnt['name']);
                $contact->setEmail(trim($cnt['email']));
                $contact->setPhone(trim($cnt['phone']));
            }
            $message = new \Entities\Message();
            $message->setSubject(( trim($msg['subject']) != '' ? $msg['subject'] : 'Msg: ' . $cnt['name']));
            $message->setContent($msg['content']);
            $message->setIsNew(1);
            $message->setContact($contact);
            $em->persist($contact);
            $em->persist($message);
            $alert = [
                'type' => 'success',
                'msg' => '<strong><i class="fa fa-check"></i></strong> Nous avons bien reçu votre message, vous receverez une réponse très bientôt.'
               ];
            $em->flush();
            $cnx->commit();
        } catch (Exception $e) {
            $cnx->rollback();
            $alert = [
                'type' => 'danger',
                'msg' => '<strong><i class="fa fa-warning"></i></strong> Une erreur interne est survenus, veuillez recommancer plutard.'
            ];
        }
        return $alert;
    }

    /**
     * Change message status to new
     * 
     * @param int $id
     * @param boolean $is_new
     * @return array
     */
    public function setAsNew($id) {
        $alert = [
            'type' => 'success',
            'msg' => '<strong><i class="fa fa-check"></i></strong> Etat du message modifier.'
        ];
        $em = $this->getEntityManager();
        $cnx = $em->getConnection();
        $cnx->beginTransaction();
        try {
            $entity = $this->find($id);
            $entity->setIsNew(1);
            $em->persist($entity);
            $em->flush();
        } catch (Exception $e) {
            $cnx->rollback();
            $alert = [
                'type' => 'danger',
                'msg' => '<strong><i class="fa fa-warning"></i></strong> Une erreur interne est survenus, veuillez recommancer plutard.'
            ];
        }
        return $alert;
    }
    
    /**
     * Change message status to not new
     * 
     * @param int $id
     * @param boolean $is_new
     * @return array
     */
    public function setAsNotNew($id) {
        $alert = [
            'type' => 'success',
            'msg' => '<strong><i class="fa fa-check"></i></strong> Etat du message modifier.'
        ];
        $em = $this->getEntityManager();
        $cnx = $em->getConnection();
        $cnx->beginTransaction();
        try {
            $entity = $this->find($id);
            $entity->setIsNew(0);
            $em->persist($entity);
            $em->flush();
        } catch (Exception $e) {
            $cnx->rollback();
            $alert = [
                'type' => 'danger',
                'msg' => '<strong><i class="fa fa-warning"></i></strong> Une erreur interne est survenus, veuillez recommencer plus tard.'
            ];
        }
        return $alert;
    }

    /**
     * Delete message by its ID
     * 
     * @param int $id
     * @param string $subject
     * @return array
     */
    public function delete($id, $subject) {
        $alert = [
            'type' => 'success',
            'msg' => '<strong><i class="fa fa-check"></i></strong> Le message ' . $subject . ' 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 recommancer plutard.'
            ];
        }
        return $alert;
    }
}