<?php

namespace LivraisonParSecteurs\Controller\backOffice;

use LivraisonParSecteurs\LivraisonParSecteurs;
use LivraisonParSecteurs\Model\LpsAreaSchedule;
use LivraisonParSecteurs\Model\LpsAreaScheduleQuery;
use Propel\Runtime\Map\TableMap;
use Propel\Runtime\Propel;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Thelia\Controller\Admin\BaseAdminController;
use Thelia\Core\Security\AccessManager;
use Thelia\Core\Security\Resource\AdminResources;
use Thelia\Form\Exception\FormValidationException;
use Thelia\Tools\URL;

/**
 * Class ScheduleController
 * @package LivraisonParSecteurs\Controller
 */
class ScheduleController extends BaseAdminController
{

    /*
     * Delete a day in an area's delivery schedule
     */
    public function deleteSchedule()
    {
        // Check current user authorization
        if (null !== $response = $this->checkAuth(AdminResources::MODULE, LivraisonParSecteurs::getModuleCode(), AccessManager::UPDATE))
            return $response;

        $areaSchedule_id = $this->getRequest()->get('area-schedule_id');
        $query = LpsAreaScheduleQuery::create()->findById($areaSchedule_id);
        if ($query === null)
            $error_msg = "Delivery area schedule not found by Id";
        else
        {
            $con = Propel::getConnection();
            $con->beginTransaction();
            $query->delete($con);
            $con->commit();
        }

        if ($this->getRequest()->request->get("success_url") == null) {
            return new RedirectResponse(URL::getInstance()->absoluteUrl("/admin/module/LivraisonParSecteurs"));
        } else {
            return new RedirectResponse(URL::getInstance()->absoluteUrl($this->getRequest()->request->get("success_url")));
        }
    }


    /*
     * Update a day in an area's delivery schedule
     */
    public function updateSchedule()
    {
        // Check current user authorization
        if (null !== $response = $this->checkAuth(AdminResources::MODULE, LivraisonParSecteurs::getModuleCode(), AccessManager::UPDATE))
            return $response;

        $con = Propel::getConnection();
        $con->beginTransaction();

        $error_msg = "";
        $changeForm = $this->createForm("lps-area-schedule-update", "form");
        try {
            $form = $this->validateForm($changeForm, "POST");
            $data = $form->getData();

            $areaSchedule_id = $this->getRequest()->get('area-schedule_id');
            $query = LpsAreaScheduleQuery::create()->findOneById($areaSchedule_id);
            if ($query === null)
                $error_msg = "Delivery area schedule not found by Id";
            else
            {
                $query->fromArray($data, TableMap::TYPE_FIELDNAME);
                $query->save($con);
                $con->commit();
            }
        } catch (FormValidationException $ex) {
            $error_msg = $this->createStandardFormValidationErrorMessage($ex);

            if (false !== $error_msg) {
                $this->setupFormErrorContext(
                    $this->getTranslator()->trans("Schedule update"),
                    $error_msg,
                    $changeForm,
                    $ex
                );

                return $this->generateErrorRedirect($changeForm);
            }
        }

        if ($data['success_url'] == null) {
            return new RedirectResponse(URL::getInstance()->absoluteUrl("/admin/module/LivraisonParSecteurs"));
        } else {
            return $this->generateSuccessRedirect($changeForm);
        }
    }


    /*
     * Add a new delivery day in an area
     */
    public function createSchedule()
    {
        // Check current user authorization
        if (null !== $response = $this->checkAuth(AdminResources::MODULE, LivraisonParSecteurs::getModuleCode(), AccessManager::UPDATE))
            return $response;

        $con = Propel::getConnection();
        $con->beginTransaction();

        $error_msg = "";
        $changeForm = $this->createForm("lps-area-schedule-create", "form");
        try {
            $form = $this->validateForm($changeForm, "POST");
            $data = $form->getData();

            $query = new LpsAreaSchedule();
            $query->fromArray($data, TableMap::TYPE_FIELDNAME);
            $query->setIdArea($data['area_id']);
            $query->save($con);
            $con->commit();

        } catch (FormValidationException $ex) {
            $error_msg = $this->createStandardFormValidationErrorMessage($ex);

            if (false !== $error_msg) {
                $this->setupFormErrorContext(
                    $this->getTranslator()->trans("Schedule update"),
                    $error_msg,
                    $changeForm,
                    $ex
                );

                return $this->generateErrorRedirect($changeForm);
            }
        }

        if ($data['success_url'] == null) {
            return new RedirectResponse(URL::getInstance()->absoluteUrl("/admin/module/LivraisonParSecteurs"));
        } else {
            return $this->generateSuccessRedirect($changeForm);
        }
    }

}