<?php

namespace LivraisonParSecteurs\Controller\backOffice;

use LivraisonParSecteurs\LivraisonParSecteurs;
use LivraisonParSecteurs\Model\LpsArea;
use LivraisonParSecteurs\Model\LpsAreaQuery;
use Propel\Runtime\ActiveQuery\Criteria;
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 GeneralController
 * @package LivraisonParSecteurs\Controller
 */
class GeneralController extends BaseAdminController
{

    public function updatePrice($params = [])
    {
        return $this->render("deliveryarea-list");
    }


    public function viewArea()
    {
        $selectedArea = LpsAreaQuery::create()->findOneById($this->getRequest()->query->get("area_id"));

        return $this->render("deliveryarea-edit", array('module_code' => LivraisonParSecteurs::getModuleCode(),
                                                                    'area_id' => $selectedArea));
    }


    public function editArea()
    {
        // Check current user authorization
        if (null !== $response = $this->checkAuth(AdminResources::MODULE, LivraisonParSecteurs::getModuleCode(), AccessManager::VIEW))
            return $response;

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

        $error_msg = "";
        $changeForm = $this->createForm("lps-area-general-update", "form");

        try {
            $form = $this->validateForm($changeForm, "POST");

            $data = $form->getData();
            $area = LpsAreaQuery::create()->findOneById($data['area_id']);
            if ($area === null) {
                $error_msg = "Delivery area not found by Id";
            }
            else {
                $area->fromArray($data, TableMap::TYPE_FIELDNAME);
                $area->save();
                $con->commit();
            }
        } catch (FormValidationException $ex) {
            $error_msg = $this->createStandardFormValidationErrorMessage($ex);
        }

        if ($this->getRequest()->get('save_mode') == 'stay')
            return $this->render("deliveryarea-edit");

        return $this->render("deliveryarea-list");
    }


    public function createArea()
    {
        // Check current user authorization
        if (null !== $response = $this->checkAuth(AdminResources::MODULE, LivraisonParSecteurs::getModuleCode(), AccessManager::VIEW))
            return $response;

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

        $error_msg = "";
        $createForm = $this->createForm("lps-area-create", "form");

        try {
            $form = $this->validateForm($createForm, "POST");
            $data = $form->getData();

            $newArea = new LpsArea();
            $newArea->fromArray($data, TableMap::TYPE_FIELDNAME);
            $newArea->setId(LpsAreaQuery::create()->orderById(Criteria::DESC)->findOne($con)->getId() + 1);
            $newArea->save();
            $con->commit();

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

        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")));
        }
    }


    public function deleteArea()
    {
        // Check current user authorization
        if (null !== $response = $this->checkAuth(AdminResources::MODULE, LivraisonParSecteurs::getModuleCode(), AccessManager::VIEW))
            return $response;

        $areaCity_id = $this->getRequest()->get('attr-area-id');
        $query = LpsAreaQuery::create()->findById($areaCity_id);
        if ($query === null)
            $error_msg = "Area 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")));
        }
    }

}