<?php

namespace VGM\WOBundle\Controller;

use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use Symfony\Component\Validator\Constraints\DateTime;
use VGM\WOBundle\Entity\Image;
use VGM\WOBundle\Entity\Worker;
use VGM\WOBundle\Repository\WorkerRepository;
use VGM\WOBundle\Form\WorkerType;
use Symfony\Component\HttpFoundation\File\UploadedFile;

/**
 * Worker controller.
 *
 */
class WorkerController extends Controller
{

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

        $cant_workers = $em->getRepository('VGMWOBundle:Worker')->countWorkers();
        $workers_per_page = $this->container->getParameter('workers_per_page');
        $last_page = ceil($cant_workers / $workers_per_page);
        $previous_page = $page > 1 ? $page - 1 : 1;
        $next_page = $page < $last_page ? $page + 1 : $last_page;

        $offset = ($page - 1) > -1? ($page - 1) * $workers_per_page: null;
        $entities = $em->getRepository('VGMWOBundle:Worker')
            ->getWorkers($workers_per_page, $offset);

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

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

            $entity->getPicture()->setWorker($entity);
            $entity->getPicture()->setName($entity->getName().'-'.$entity->getLastname());
            $entity->getPicture()->setWhat4('worker');
            $em->persist($entity->getPicture());

            $entity->setFullTime(true);
            $entity->setStatusActive(true);
            $entity->setPayByHour(true);

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

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

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

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

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

        return $form;
    }

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

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

        return $this->render('VGMWOBundle:Worker:new.html.twig');
    }

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

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

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

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

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

        return $this->render('VGMWOBundle:Worker:show.html.twig', array('worker_id' => $id));
    }

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

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

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

       /* $editForm = $this->createForm(new WorkerType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

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

        return $this->render('VGMWOBundle:Worker:edit.html.twig', array('worker_id' => $entity->getId()));
    }

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

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

        return $form;
    }

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

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

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



        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createForm(new WorkerType(), $entity);
        $editForm->handleRequest($request);

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

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

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

    /**
     * Deletes a Worker 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:Worker')->find($id);

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

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

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

    /**
     * Creates a form to delete a Worker 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('workers_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Delete'))
            ->getForm()
        ;
    }

    /**
     * Ajax
     * Search workers with filters: department_id(dep_id), name(name), code(code)
     * @param Request $request[dep_id, name, code]
     * @return Response
     */
    public function getWorkerByCodeAjaxAction(Request $request){
        $em = $this->getDoctrine()->getManager();

        /**
         * Getting data request
         */
        $code = $request->get('code');
        $worker = $em->getRepository('VGMWOBundle:Worker')->getWorkerByCode($code);
        $worker2send = null;
        if($worker){
            $loops = $em->getRepository('VGMWOBundle:LaborLoop')
                        ->getUnfinishedLoopsByWorker_Date($worker->getId(), new \DateTime());
            $loops2send = [];
            if($loops){
                foreach($loops as $loop){
                    $loops2send[] = array("id" => $loop->getId(),
                        "workorder" => $loop->getWorkOrder()->GetNumber(),
                        "as_no" => $loop->getAssignedStockNo(),
                        "area" => $loop->getArea(),
                        "work" => $loop->getDescription(),
                        "started" => $loop->getStartedAt() ? $loop->getStartedAt()->format('H:i') : null);
                }
            }
            /*assigned_stock_no
            area
            description
            */

            /*started_at
            finished_at
            total_time
            hour_cost
            lunch*/

            $worker2send = array("id" => $worker->getId(),
                    "picture" => $worker->getPicture() ? $worker->getPicture()->getFinalWebPath() : "",
                    "code" => $worker->getWorkerCode(),
                    "fullname" => $worker->__toString(),
                    "pay_rate" => $worker->getPayRate(),
                    "department" => $worker->getDepartment()->__toString(),
                    "started_loops" => $loops2send);


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

        return new Response(json_encode($response));
    }
    public function search4WorkersAjaxAction(Request $request){
        $em = $this->getDoctrine()->getManager();

        /**
         * Getting data request
         */
        $dep_id = $request->get('dep_id');
        $name_code = $request->get('name_code');
        $workers = [];

        if($name_code != null && $dep_id != null){
            $workers = $em->getRepository('VGMWOBundle:Worker')->getWorkersByDepNameCode($dep_id, $name_code);
        }
        elseif($name_code != null){
            $workers = $em->getRepository('VGMWOBundle:Worker')->getWorkersByNameCode($name_code);
        }
        elseif($dep_id != null){
            $workers = $em->getRepository('VGMWOBundle:Worker')->getWorkersByDepartment($dep_id);
        }

        $workers_list = [];
        if(count($workers) > 0){
            foreach($workers as $wk){
                $workers_list[] = array("id" => $wk->getId(),
                    "name" => $wk->__toString(),
                    "picture" => $wk->getPicture() ? $wk->getPicture()->getFinalWebPath() : null,
                    "department" => $wk->getDepartment()->__toString(),
                    "code" => $wk->getWorkerCode(),
                    "pay_by_hour" => $wk->getPayByHour(),
                    "pay_rate" => $wk->getPayRate());
            }
        }

        $response = array("code" => 100, "success" => true, "workers" => $workers_list, "message" => count($workers_list));

        return new Response(json_encode($response));
    }
    public function getSupervisorsAjaxAction(Request $request){
        $em = $this->getDoctrine()->getManager();

        $supervisors = $em->getRepository('VGMWOBundle:Worker')->getSupervisors() ?
            $em->getRepository('VGMWOBundle:Worker')->getSupervisors() : [];

        $sups_list = [];
        if(count($supervisors) > 0){
            foreach($supervisors as $sup){
                $sups_list[] = array("id" => $sup->getId(),
                    "picture" => $sup->getPicture() ? $sup->getPicture()->getFinalWebPath() : null,
                    "code" => $sup->getWorkerCode(),
                    "fullname" => $sup->__toString(),
                    "department" => $sup->getDepartment()->__toString());
            }
        }

        $response = array("code" => 100, "success" => true, "supervisors" => $sups_list, "message" => count($sups_list));

        return new Response(json_encode($response));
    }
    public function getSupportAjaxAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();

        /**
         * Getting data request
         */
        $departments = $em->getRepository('VGMWOBundle:NDepartment')->findBy(array(), array('name' => 'ASC'));
        $pay_schedules = $em->getRepository('VGMWOBundle:NPaySchedule')->findBy(array(), array('name' => 'ASC'));
        $units = $em->getRepository('VGMWOBundle:CUnit')->findAllUnits();

        $departments2send = [];
        if(count($departments))
            foreach($departments as $dep){
                $departments2send[] = array("id" => $dep->getId(),
                    "name" => $dep->getName());
            }
        $units2send = [];
        if(count($units))
            foreach($units as $unit){
                $units2send[] = array("id" => $unit->getId(),
                    "name" => $unit->__toString());
            }
        $pay_schedules2send = [];
        if(count($pay_schedules))
            foreach($pay_schedules as $ps){
                $pay_schedules2send[] = array("id" => $ps->getId(),
                    "name" => $ps->getName());
            }

        $response = array("code" => 100, "success" => true,
            "departments" => $departments2send,
            "units" => $units2send,
            "pay_schedules" => $pay_schedules2send);

        return new Response(json_encode($response));
    }
    public function getFilteredWorkersAjaxAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();

        $workers = $em->getRepository('VGMWOBundle:Worker')->findBy(array(), array('name' => 'ASC'));

        $workers2send = [];
        if(count($workers))
            foreach($workers as $w){
                $workers2send[] = array("id" => $w->getId(),
                    "picture" => $w->getPicture() ? $w->getPicture()->getFinalWebPath() : null,
                    "code" => $w->getWorkerCode(),
                    "name" => $w->getName(),
                    "last_name" => $w->getLastname(),
                    "phone_p" => $w->getPhone1(),
                    "phone_w" => $w->getPhone2(),
                    "email_p" => $w->getPemail(),
                    "email_w" => $w->getWemail(),
                    "addrees_street" => $w->getAddress(),
                    "addrees_city" => $w->getCity(),
                    "addrees_state" => $w->getState(),
                    "addrees_zip" => $w->getZipCode(),
                    "date_hire" => $w->getHireDate() ? $w->getHireDate()->format("m/d/Y") : null,
                    "date_birth" => $w->getBirthDate() ? $w->getBirthDate()->format("m/d/Y") : null,
                    "date_fire" => $w->getTerminationDate() ? $w->getTerminationDate()->format("d/m/Y") : null,
                    "department_id" => $w->getDepartment() ? $w->getDepartment()->getId() : null,
                    "pay_standard" => $w->getStandartPay(),
                    "pay_schedule_id" => $w->getNpayschedule() ? $w->getNpayschedule()->getId() : null,
                    "pay_rate" => $w->getPayRate(),
                    "is_pay_by_hour" => $w->getPayByHour(),
                    "is_full_time" => $w->getFullTime(),
                    "is_active" => $w->getStatusActive(),
                    "is_supervisor" => $w->getSupervisor()
                );
            }

        $response = array("code" => 100, "success" => true,
            "workers" => $workers2send);

        return new Response(json_encode($response));
    }
    public function UpdateWorkerAjaxAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();

        /**
         * Getting data request
         */
        $id = $request->get('id') != "null" ? $request->get('id') : null;
        $picture_has_changed = $request->get('picture_has_changed')  === "true";
        if($picture_has_changed)
            $picture = $request->files->get('picture');
        $code = $request->get('code') != "null" ? $request->get('code') : null;
        $name = $request->get('name') != "null" ? $request->get('name') : null;
        $last_name = $request->get('last_name') != "null" ? $request->get('last_name') : null;
        $phone_p = $request->get('phone_p') != "null" ? $request->get('phone_p') : null;
        $phone_w = $request->get('phone_w') != "null" ? $request->get('phone_w') : null;
        $email_p = $request->get('email_p') != "null" ? $request->get('email_p') : null;
        $email_w = $request->get('email_w') != "null" ? $request->get('email_w') : null;
        $addrees_street = $request->get('addrees_street') != "null" ? $request->get('addrees_street') : null;
        $addrees_city = $request->get('addrees_city') != "null" ? $request->get('addrees_city'): null;
        $addrees_state = $request->get('addrees_state') != "null" ? $request->get('addrees_state') : null;
        $addrees_zip = $request->get('addrees_zip') != "null" ? (int)$request->get('addrees_zip') : null;
        $date_birth = $request->get('date_birth') != "null" ? new \DateTime($request->get('date_birth')) : null;
        $date_hire = $request->get('date_hire') != "null" ? new \DateTime($request->get('date_hire')) : null;
        $date_fire = $request->get('date_fire') != "null" ? new \DateTime($request->get('date_fire')) : null;
        $department = $request->get('department') != "null" ? $request->get('department') : null;
        $unit = $request->get('unit') != "null" ? $request->get('unit') : null;
        $pay_standard = $request->get('pay_standard') != "null" ? (float)$request->get('pay_standard') : null;
        $pay_schedule = $request->get('pay_schedule') != "null" ? $request->get('pay_schedule') : null;
        $pay_rate = $request->get('pay_rate') != "null" ? (float)$request->get('pay_rate') : null;
        $is_pay_by_hour = $request->get('is_pay_by_hour') === "true";
        $is_full_time = $request->get('is_full_time') === "true";
        $is_active = $request->get('is_active') === "true";
        $is_supervisor = $request->get('is_supervisor') === "true";
        $delete_picture = $request->get('delete_picture') === "true";


        $worker = $id != null ? $em->getRepository('VGMWOBundle:Worker')->find($id) : new Worker();

        if($picture_has_changed){
            $new_picture = new UploadedFile($picture->getPathname(), true);

            if($id && $worker->getPicture())
                $worker->getPicture()->setFile($new_picture);
            else{
                $image = new Image();
                $image->setFile($new_picture);
                $image->setName($name.'-'.$last_name);
                $image->setAlt($name.'-'.$last_name);
                $image->setWhat4("worker");
                $image->setWorker($worker);
                $worker->setPicture($image);
            }
        }
        $picture_2_delete = null;
        if($delete_picture && $worker->getPicture() != null){
            $picture_2_delete = $worker->getPicture();

            $worker->setPicture(null);
        }
        if($id != null && $worker->getPicture() != null)
            if($worker->getPicture()->getName() != $name.'-'.$last_name){
                $oldfile = $worker->getPicture()->getAbsolutePath();

                $worker->getPicture()->setName($name.'-'.$last_name);

                $newfile = $worker->getPicture()->getAbsolutePath();

                rename($oldfile, $newfile);
            }

        $worker->setWorkerCode($code);
        $worker->setName($name);
        $worker->setLastname($last_name);
        $worker->setPhone1($phone_p);
        $worker->setPhone2($phone_w);
        $worker->setPemail($email_p);
        $worker->setWemail($email_w);
        $worker->setAddress($addrees_street);
        $worker->setCity($addrees_city);
        $worker->setState($addrees_state);
        $worker->setZipCode($addrees_zip);
        if($date_hire != null)
            $worker->setHireDate($date_hire);
        if($date_birth != null)
            $worker->setBirthDate($date_birth);
        if($date_fire != null)
            $worker->setTerminationDate($date_fire);
        $worker->setStandartPay($pay_standard);
        $worker->setPayRate($pay_rate);
        $worker->setPayByHour($is_pay_by_hour);
        $worker->setFullTime($is_full_time);
        $worker->setStatusActive($is_active);
        $worker->setSupervisor($is_supervisor);

        if($department != null){
            $dep = $em->getRepository('VGMWOBundle:NDepartment')->find($department);
            $worker->setDepartment($dep);
        }

        if($unit != null){
            $u = $em->getRepository('VGMWOBundle:CUnit')->find($unit);
            $worker->setUnit($u);
        }

        if($pay_schedule != null){
            $nps = $em->getRepository('VGMWOBundle:NPaySchedule')->find($pay_schedule);
            $worker->setNpayschedule($nps);
        }

        if($id == null)
            $em->persist($worker);
        $em->flush();

        if($picture_2_delete != null){
            $em->remove($picture_2_delete);
            $em->flush();
        }

        $response = array("code" => 100, "success" => true,
            "worker_id" => $worker->getId(),
            "worker_picture" => $worker->getPicture() ? $worker->getPicture()->getFinalWebPath() : null);

        return new Response(json_encode($response));
    }
    public function getWorkerDataAjaxAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();

        $id = $request->get('id') != null ? $request->get('id') : null;

        $w = $em->getRepository('VGMWOBundle:Worker')->find($id);

        if($w != null){
                $worker2send = array("id" => $w->getId(),
                    "picture" => $w->getPicture() ? $w->getPicture()->getFinalWebPath() : null,
                    "code" => $w->getWorkerCode(),
                    "name" => $w->getName(),
                    "last_name" => $w->getLastname(),
                    "phone_p" => $w->getPhone1(),
                    "phone_w" => $w->getPhone2(),
                    "email_p" => $w->getPemail(),
                    "email_w" => $w->getWemail(),
                    "addrees_street" => $w->getAddress(),
                    "addrees_city" => $w->getCity(),
                    "addrees_state" => $w->getState(),
                    "addrees_zip" => $w->getZipCode(),
                    "date_hire" => $w->getHireDate() ? $w->getHireDate()->format("m/d/Y") : null,
                    "date_birth" => $w->getBirthDate() ? $w->getBirthDate()->format("m/d/Y") : null,
                    "date_fire" => $w->getTerminationDate() ? $w->getTerminationDate()->format("d/m/Y") : null,
                    "department_id" => $w->getDepartment() ? $w->getDepartment()->getId() : null,
                    "unit_id" => $w->getUnit() ? $w->getUnit()->getId() : null,
                    "pay_standard" => $w->getStandartPay(),
                    "pay_schedule_id" => $w->getNpayschedule() ? $w->getNpayschedule()->getId() : null,
                    "pay_rate" => $w->getPayRate(),
                    "is_pay_by_hour" => $w->getPayByHour(),
                    "is_full_time" => $w->getFullTime(),
                    "is_active" => $w->getStatusActive(),
                    "is_supervisor" => $w->getSupervisor()
                );
        }

        $response = array("code" => 100, "success" => true,
            "worker" => $worker2send);

        return new Response(json_encode($response));
    }
    public function tryWorkerCodeAjaxAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();

        $id = $request->get('id') != null ? $request->get('id') : null;
        $code = $request->get('code') != null ? $request->get('code') : null;

        $w = $em->getRepository('VGMWOBundle:Worker')->getWorkerByCode($code);

        $ok = true;
        $message = "Ok";
        if($w)
            if($id != $w->getId() || $id == null){
                $ok = false;
                $message = "This code already exists/Ese código ya existe.";
            }

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

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

}
