<?php

namespace VGM\WOBundle\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use VGM\WOBundle\Entity\Stock;
use VGM\WOBundle\Form\StockType;

/**
 * Stock controller.
 *
 */
class StockController extends Controller
{

    /**
     * Lists all Stock entities.
     *
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('VGMWOBundle:Stock')->findAll();

        return $this->render('VGMWOBundle:Stock:index.html.twig', array(
            'entities' => $entities,
        ));
    }
    /**
     * Creates a new Stock entity.
     *
     */
    public function createAction(Request $request)
    {
        $entity = new Stock();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('stocks_show', array('id' => $entity->getId())));
        }

        return $this->render('VGMWOBundle:Stock:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Creates a form to create a Stock entity.
     *
     * @param Stock $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCreateForm(Stock $entity)
    {
        $form = $this->createForm(new StockType(), $entity, array(
            'action' => $this->generateUrl('stocks_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Create'));

        return $form;
    }

    /**
     * Displays a form to create a new Stock entity.
     *
     */
    public function newAction()
    {
        $entity = new Stock();
        $form   = $this->createCreateForm($entity);

        return $this->render('VGMWOBundle:Stock:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Finds and displays a Stock entity.
     *
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('VGMWOBundle:Stock')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Stock entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return $this->render('VGMWOBundle:Stock:show.html.twig', array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing Stock entity.
     *
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('VGMWOBundle:Stock')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Stock entity.');
        }

        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);

        return $this->render('VGMWOBundle:Stock:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
    * Creates a form to edit a Stock entity.
    *
    * @param Stock $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(Stock $entity)
    {
        $form = $this->createForm(new StockType(), $entity, array(
            'action' => $this->generateUrl('stocks_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form->add('submit', 'submit', array('label' => 'Update'));

        return $form;
    }
    /**
     * Edits an existing Stock entity.
     *
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('VGMWOBundle:Stock')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Stock entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            return $this->redirect($this->generateUrl('stocks_edit', array('id' => $id)));
        }

        return $this->render('VGMWOBundle:Stock:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }
    /**
     * Deletes a Stock entity.
     *
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('VGMWOBundle:Stock')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Stock entity.');
            }

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

        return $this->redirect($this->generateUrl('stocks'));
    }

    /**
     * Creates a form to delete a Stock entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('stocks_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Delete'))
            ->getForm()
        ;
    }


    /**
     * @param Request $request
     * @return Response
     */
    public function saveStockAjaxAction(Request $request){
        $em = $this->getDoctrine()->getManager();

        /**
         * Getting data request
         * initializing others vars
         */
        $own_id = $request->get('own_id');
        $stock = $request->get('stock');
        $serial = $request->get('serial');
        $hours_miles = $request->get('hours_miles');
        $model = $request->get('model');
        $cap = $request->get('cap');
        $year = $request->get('year');
        $cond = $request->get('cond');
        $brand = $request->get('brand');
        $tgc = $request->get('tgc');
        $engine = $request->get('engine');
        $loc = $request->get('loc');
        $acond = $request->get('acond');
        $actual_workorder = $request->get('actual_workorder');
        $equipment_id = $request->get('equipment_id');

        $new_stock = $em->getRepository('VGMWOBundle:Stock')->find($own_id);

        $new_stock->setCode($stock);
        $new_stock->setSerial($serial);
        $new_stock->setHoursMiles($hours_miles);
        $new_stock->setModel($model);
        $new_stock->setCapacity($cap);
        $new_stock->setYear($year);
        $new_stock->setDescription($cond);
        $new_stock->setBrand($brand);
        $new_stock->setTransGenCom($tgc);
        $new_stock->setEngine($engine);
        $new_stock->setLocalization($loc);
        $new_stock->setActualCondition($acond);
        $new_stock->setWo($actual_workorder);
        $new_stock->setEquipment($em->getRepository('VGMWOBundle:Equipment')->find($equipment_id));

        $em->flush();

        $response = array("code" => 100, "success" => true, 'message' => "Ok");

        return new Response(json_encode($response));
    }
    /**
     * @param Request $request
     * @return Response
     */
    public function updateUploadedStocksAjaxAction(Request $request){
        $em = $this->getDoctrine()->getManager();

        $cstocks = $em->getRepository('VGMWOBundle:Stock')->findAll4Update();

        /**
         * Aeroservices DB
         */
        $ext_em = $this->getDoctrine()->getManager('aeroservicios');
        $conn = $ext_em->getConnection();

        foreach($cstocks as $cstock){
            /**
             * Stock Query
             * Getting stocks item own data
             */
            $stock_query = "SELECT Items.Id as asdb_id,Items.StockNo as stock,Items.SerialNo as serial,Items.Status as Status,";
            $stock_query = $stock_query."Items.UseVar as hours_miles,Items.Model as model,Items.Cap as cap,";
            $stock_query = $stock_query."Items.Year as year,Items.ItemCondition as cond,";

            /**
             * Stock Query Relationships
             * Getting stocks item relationships
             */
            $stock_query = $stock_query."Items.Brand as brand,Items.TranGenCom as tgc,Items.Engine as engine,";
            $stock_query = $stock_query."Items.Localization as loc,Items.ActualCond as acond ";
            $stock_query = $stock_query."FROM Items ";

            $stock_query = $stock_query."WHERE Items.StockNo =:stock";

            $query = $conn->prepare($stock_query);

            $query->bindValue('stock', $cstock->getCode());

            $query->execute();
            $ustocks = $query->fetchAll();

            if($ustocks != null){
                $ustocks_cant = $query->rowCount();
                if($ustocks_cant == 1){
                    $ustock = $ustocks[0];

                    /**
                     * Brand
                     */
                    if($ustock['brand'] != null){
                        if($ustock['brand'] != ""){
                            $brand_query = "SELECT Items_Brands.ResourceName as brand FROM Items_Brands WHERE Items_Brands.Id =:brand";
                            $query = $conn->prepare($brand_query);

                            $query->bindValue('brand', $ustock['brand']);
                            $query->execute();
                            $brand_result = $query->fetchAll();

                            if($query->rowCount() > 0)
                                $ustock['brand'] = $brand_result[0]['brand'];
                            else
                                $ustock['brand'] = "---";
                        }
                    }
                    else
                        $ustock['brand'] = "---";
                    /**
                     * TGC
                     */
                    if($ustock['tgc'] != null){
                        if($ustock['tgc'] != ""){
                            $tgc_query = "SELECT TranGenCom.ResourceName as tgc FROM TranGenCom WHERE TranGenCom.Id =:tgc";
                            $query = $conn->prepare($tgc_query);

                            $query->bindValue('tgc', $ustock['tgc']);
                            $query->execute();
                            $tgc_result = $query->fetchAll();

                            if($query->rowCount() > 0)
                                $ustock['tgc'] = $tgc_result[0]['tgc'];
                            else
                                $ustock['tgc'] = "---";
                        }
                    }
                    else
                        $ustock['tgc'] = "---";
                    /**
                     * Engine
                     */
                    if($ustock['engine'] != null){
                        if($ustock['engine'] != "" ){
                            $engine_query = "SELECT Items_Engines.ResourceName as engine FROM Items_Engines WHERE Items_Engines.Id =:engine";
                            $query = $conn->prepare($engine_query);

                            $query->bindValue('engine', $ustock['engine']);
                            $query->execute();
                            $engine_result = $query->fetchAll();

                            if($query->rowCount() > 0)
                                $ustock['engine'] = $engine_result[0]['engine'];
                            else
                                $ustock['engine'] = "---";
                        }
                    }
                    else
                        $ustock['engine'] = "---";

                    /**
                     * Localization
                     */
                    if($ustock['loc'] != null){
                        if($ustock['loc'] != ""){
                            $loc_query = "SELECT Items_Localization.ResourceName as loc FROM Items_Localization ";
                            $loc_query = $loc_query."WHERE Items_Localization.Id =:loc";
                            $query = $conn->prepare($loc_query);

                            $query->bindValue('loc', $ustock['loc']);
                            $query->execute();
                            $loc_result = $query->fetchAll();

                            if($query->rowCount() > 0)
                                $ustock['loc'] = $loc_result[0]['loc'];
                            else
                                $ustock['loc'] = "---";
                        }
                    }
                    else
                        $ustock['loc'] = "---";
                    /**
                     * ActualCond
                     */
                    if($ustock['acond'] != null){
                        if($ustock['acond'] != ""){
                            $acond_query = "SELECT Items_ActualCond.ResourceName as acond FROM Items_ActualCond ";
                            $acond_query = $acond_query."WHERE Items_ActualCond.Id =:acond";
                            $query = $conn->prepare($acond_query);

                            $query->bindValue('acond', $ustock['acond']);
                            $query->execute();
                            $acond_result = $query->fetchAll();

                            if($query->rowCount() > 0)
                                $ustock['acond'] = $acond_result[0]['acond'];
                            else
                                $ustock['acond'] = "---";
                        }
                    }
                    else
                        $ustock['acond'] = "---";

                    $cstock->setAsdbId($ustock['asdb_id']);
                    $cstock->setCode($ustock['stock']);
                    $cstock->setSerial($ustock['serial']);
                    $cstock->setBrand($ustock['brand']);
                    $cstock->setModel($ustock['model']);
                    $cstock->setYear($ustock['year']);
                    $cstock->setCapacity($ustock['cap']);
                    $cstock->setEngine($ustock['engine']);
                    $cstock->setTransGenCom($ustock['tgc']);
                    $cstock->setHoursMiles($ustock['hours_miles']);
                    $cstock->setLocalization($ustock['loc']);
                    $cstock->setDescription($ustock['cond']);
                    $cstock->setActualCondition($ustock['acond']);

                    $em->flush();
                }
            }
        }

        $response = array("code" => 100, "success" => true, 'message' => "Ok");

        return new Response(json_encode($response));
    }
}
