<?php
/**
 * Created by PhpStorm.
 * User: Olyanren
 * Date: 22.10.2016
 * Time: 12:36
 */

namespace AppBundle\Controller;


use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\NoResultException;
use JMS\Serializer\SerializerBuilder;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * HomeController controller.
 *
 * @Route("/7073a00e724bbda643cb7e2a85110640/home")
 */
class HomeController extends Controller
{
    /**
     * @Route("/")
     */
    public function index()
    {
        return $this->redirect('/7073a00e724bbda643cb7e2a85110640/home/product');
    }

    /**
     * Finds and displays a Product entity.
     *
     * @Route("/product/search", name="product_search")
     * @Method("GET")
     * @return Response
     */
    public function searchByName(Request $request)
    {
        $name = $request->query->get('name');
        if(empty($name)){
            $this->addFlash("error","Ad kısmı boş olamaz");
            return new Response(json_encode(array_values("Ad kısmı boş olamaz")));

        }
        $em = $this->getDoctrine()->getManager();
        $query = $em->createQuery('SELECT p FROM AppBundle:Product p WHERE p.name LIKE :name ORDER BY p.id ASC')
            ->setParameter('name', '%' . $name . '%');
        try {
            $products = $query->getResult();
            $resultList = array();
            foreach ($products as $product) {
                $result["id"] = $product->getId();
                $result["name"] = $product->getName();
                $result["lastPrice"] =  $this->get("app.doctrineutil")->getLastPrice($product->getId());
                $resultList[] = $result;
            }
            $response = new Response(json_encode(array_values($resultList)));
            $response->headers->set('Content-Type', 'application/json');
            return $response;
        } catch (NoResultException $e) {
            return json_encode(false);
        }
    }


    /**
     * Load ProductHistories.
     *
     * @Route("/producthistory/all", name="product_histories")
     * @Method("GET")
     * @return Response
     */
    public function allProductHistories(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $invoiceNo = $request->query->get('invoiceNo');
        if ($invoiceNo != null) {
            $query = $em->createQuery("SELECT ph.amount,ph.remainingAmount,ph.price,prod.id,prod.name
            FROM AppBundle:ProductHistory ph INNER JOIN ph.product prod 
            INNER JOIN ph.invoice i WHERE i.no = :invoiceNo ORDER BY ph.id DESC")
                ->setParameter('invoiceNo', $invoiceNo);
        } else {
            $productId = $request->query->get('productId');
            $query = $em->createQuery("SELECT ph.amount,ph.price,ph.creationDate,prod.id,prod.name
            FROM AppBundle:ProductHistory ph INNER JOIN ph.product prod WHERE prod.id = :productId ORDER BY ph.id DESC")
                ->setParameter('productId', $productId);
        }

        try {
            $result = $query->getResult();
            $response = new Response(json_encode($result));
            $response->headers->set('Content-Type', 'application/json');
            return $response;
        } catch (NoResultException $e) {
            return json_encode(false);
        }
    }

    /**
     * Load DeliveryHistories.
     *
     * @Route("/delivery_history/all", name="delivery_histories")
     * @Method("GET")
     * @return Response
     */
    public function allDeliveryHistories(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $deliveryId = $request->query->get('deliveryId');
        if ($deliveryId != null) {
            $query = $em->createQuery("SELECT dh.amount,prod.id,prod.name
            FROM AppBundle:DeliveryHistory dh INNER JOIN dh.product prod 
            INNER JOIN dh.delivery d WHERE d.id = :deliveryId ORDER BY dh.id DESC")
                ->setParameter('deliveryId', $deliveryId);
        } else {
            $productId = $request->query->get('productId');
            $query = $em->createQuery("SELECT dh.amount,dh.creationDate,prod.id,prod.name
            FROM AppBundle:DeliveryHistory dh INNER JOIN dh.product prod WHERE prod.id = :productId ORDER BY dh.id DESC")
                ->setParameter('productId', $productId);
        }
        try {
            $result = $query->getResult();
            $tempResult = array();
            foreach ($result as $item) {
                if(!isset($productId)){
                    $productId=$item["id"];
                }
                $item["price"] =  $this->get("app.doctrineutil")->getLastPrice($productId);
                $tempResult[]=$item;
            }
            $response = new Response(json_encode($tempResult));
            $response->headers->set('Content-Type', 'application/json');
            return $response;
        } catch (NoResultException $e) {
            return json_encode(false);
        }
    }
}