<?php
/**
 * Created by PhpStorm.
 * User: vlade
 * Date: 6/5/15
 * Time: 12:41 AM
 */

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 Doctrine\ORM\EntityRepository;
use VGM\WOBundle\Entity\NoticeLoop;
use VGM\WOBundle\Entity\Worker;


class NoticeController extends Controller
{
    public function WorkersTimeNotificationsAction()
    {
        $em = $this->getDoctrine();

        $departments = $em->getRepository('VGMWOBundle:NDepartment')->findAll();

        $date = new \DateTime();
        $date->modify('-1 day');
        $date_to = new \DateTime();
        $date_to->modify('+1 day');

        $list = $em->getRepository('VGMWOBundle:Worker')->getWorkerWithOvertimeByDateRange($date, $date_to);

        return $this->render('VGMWOBundle:Notifications:timeNotifications.html.twig', array(
            'departments' => $departments));
    }
    //OK
    public function getThereNewLoopNoticesAjaxAction(Request $request){
        $em = $this->getDoctrine()->getManager();

        $user = $this->getUser();
        $newNotices = 0;

        if($user->hasRole('ROLE_ADMIN') || $user->hasRole('ROLE_SUPER_SUPERVISOR'))
            $newNotices = $em->getRepository('VGMWOBundle:NoticeLoop')->getNewLoopNoticesCount();
        else if($user->hasRole('ROLE_SUPERVISOR'))
            $newNotices = $em->getRepository('VGMWOBundle:NoticeLoop')
                ->getNewLoopNoticesCount($user->getWorker()->supDepartmentsIds());
        $style_color = ((int)$newNotices) > 0 ? 'red' : '';
        $style_font_size = ((int)$newNotices) > 0 ? '14px' : '';
        $notices = array("cant" => $newNotices,
                        "style_color" => $style_color,
                        "style_font_size" => $style_font_size);

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

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

        $user = $this->getUser();
        $active_notices = null;

        if($user->hasRole('ROLE_ADMIN') || $user->hasRole('ROLE_SUPER_SUPERVISOR'))
            $active_notices = $em->getRepository('VGMWOBundle:NoticeLoop')->getActiveLoopNotices();
        else if($user->hasRole('ROLE_SUPERVISOR'))
            $active_notices = $em->getRepository('VGMWOBundle:NoticeLoop')
                ->getActiveLoopNotices($user->getWorker()->supDepartmentsIds());

        //$active_notices = $em->getRepository('VGMWOBundle:NoticeLoop')->getActiveLoopNotices();

        $notices = [];

        foreach($active_notices as $notice){
            $alert_type = 0;
            $time = abs($notice->getLoop()->getPOvertime());
            if($notice->getCOvertime() == true){
                $alert_type = 2;
                $time = $notice->getLoop()->getCOvertime();
            }
            elseif($notice->getPOvertime() == true)
                $alert_type = 1;
            $notices[] = array("own_id" => $notice->getId(),
                "worker_id" => $notice->getLoop()->getWorker()->getId(),
                "worker" => $notice->getLoop()->getWorker()->__toString()/*.
                            '('.$notice->getLoop()->getWorker()->getWorkerCode().')'*/,
                "loop_id" => $notice->getLoop()->getId(),
                "generated" => $notice->getGenerated()->format('m/d/Y'),
                "loop_date" => $notice->getLoop()->getDate()->format('m/d/Y'),
                "alert_type" => $alert_type,
                "time" => $time,
                "text" => $notice->getText(),
                "hour_cost" => $alert_type == 0 ? $notice->getLoop()->getHourCost()
                                                : $notice->getLoop()->getOvertimeCost());
        }

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

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

        $user = $this->getUser();
        $dismissed_notices = null;

        if($user->hasRole('ROLE_ADMIN') || $user->hasRole('ROLE_SUPER_SUPERVISOR'))
            $dismissed_notices = $em->getRepository('VGMWOBundle:NoticeLoop')->getDismissedLoopNotices();
        else if($user->hasRole('ROLE_SUPERVISOR'))
            $dismissed_notices = $em->getRepository('VGMWOBundle:NoticeLoop')
                ->getDismissedLoopNotices($user->getWorker()->supDepartmentsIds());

        //$dismissed_notices = $em->getRepository('VGMWOBundle:NoticeLoop')->getDismissedLoopNotices();

        $notices = [];

        foreach($dismissed_notices as $notice){
            $alert_type = 0;
            $time = abs($notice->getLoop()->getPOvertime());
            if($notice->getCOvertime() == true){
                $alert_type = 2;
                $time = $notice->getLoop()->getCOvertime();
            }
            elseif($notice->getPOvertime() == true)
                $alert_type = 1;
            $notices[] = array("own_id" => $notice->getId(),
                "worker_id" => $notice->getLoop()->getWorker()->getId(),
                "worker" => $notice->getLoop()->getWorker()->__toString()/*.
                    '('.$notice->getLoop()->getWorker()->getWorkerCode().')'*/,
                "loop_id" => $notice->getLoop()->getId(),
                "generated" => $notice->getGenerated()->format('m/d/Y'),
                "loop_date" => $notice->getLoop()->getDate()->format('m/d/Y'),
                "dismissed" => $notice->getDismissed()->format('m/d/Y'),
                "alert_type" => $alert_type,
                "time" => $time,
                "text" => $notice->getText(),
                "hour_cost" => $alert_type == 0 ? $notice->getLoop()->getHourCost()
                        : $notice->getLoop()->getOvertimeCost());
        }

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

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

        $notice_id = $request->get('notice_id');

        $notice = $em->getRepository('VGMWOBundle:NoticeLoop')->find($notice_id);

        $notice->setDismissed(new \DateTime());

        $em->flush($notice);

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

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

        $notice_id = $request->get('notice_id');

        $notice = $em->getRepository('VGMWOBundle:NoticeLoop')->find($notice_id);

        $notice->setDismissed(null);

        $em->flush($notice);

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

        return new Response(json_encode($response));
    }
    public function getNoticeLoopsNoticesAjaxAction(Request $request){
        $em = $this->getDoctrine()->getManager();
        /**
         * Getting data request
         * initializing others vars
         */
        $loop_id = $request->get('loop_id');
        $alert_type = $request->get('alert_type');

        $dbloop = $em->getRepository('VGMWOBundle:LaborLoop')->find($loop_id);

        $loops = $alert_type < 2 ?
            $em->getRepository('VGMWOBundle:LaborLoop')->getLoopsByWorkerDate(
                $dbloop->getWorker()->getId(), $dbloop->getDate())
            : $em->getRepository('VGMWOBundle:LaborLoop')->getLoopsByWorkerWeek(
                $dbloop->getWorker()->getId(),
                $this->get('utils')->getFirstWeekDay($dbloop->getDate()),
                $this->get('utils')->getLastWeekDay($dbloop->getDate()));

        $loops2send = [];

        foreach($loops as $loop){
            $loops2send[] = array("id" => $loop->getId(),
                "labor_id" => $loop->getId(),
                "department" => $loop->getDepartment() ?
                        $loop->getDepartment()->__toString() : null,
                "worker" => $loop->getWorker() ? $loop->getWorker()->__toString() : null,
                "workorder" => $loop->getWorkOrder() ? $loop->getWorkOrder()->getNumber() : null,
                "assigned_stock_no" => $loop->getAssignedStockNo() ?
                        $loop->getAssignedStockNo() : null,
                "area" => $loop->getArea(),
                "description" => $loop->getDescription(),
                "date" => $loop->getDate() ? $loop->getDate()->format('m/d/Y') : null,
                "starts" => $loop->getStartedAt() ? $loop->getStartedAt()->format('H:i') : null,
                "ends" => $loop->getFinishedAt() ? $loop->getFinishedAt()->format('H:i') : null,
                "hour_cost"  => $loop->getHourCost() ?  $loop->getHourCost() : null,
                "rTime" => $loop->getTotalTime(),
                "lunch" => $loop->getLunch(),
                "overtime" => $loop->getPOvertime(),
                "c_overtime" => $loop->getCOvertime(),
                "overtime_cost" => $loop->getOvertimeCost());
        }

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

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