<?php

namespace LivraisonParSecteurs\Controller;

use LivraisonParSecteurs\LivraisonParSecteurs;
use LivraisonParSecteurs\Model\LpsAreaQuery;
use Propel\Runtime\Map\TableMap;
use Propel\Runtime\Propel;
use Thelia\Controller\Admin\BaseAdminController;
use Thelia\Core\Security\AccessManager;
use Thelia\Core\Security\Resource\AdminResources;
use Thelia\Form\Exception\FormValidationException;

/**
 * Class BackOfficeController
 * @package LivraisonParSecteurs\Controller
 */
class BackOfficeController extends BaseAdminController
{
    public function viewAction($params = [])
    {
        return $this->render("deliveryarea-list");
    }

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

        $deliveryarea = LpsAreaQuery::create()->findOneById($id);
        $deliveryarea->setActive($deliveryarea->getActive() ? 0 : 1)->save();

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

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

        /* Laurent : à faire --> changer le redirect si "Enregistrer et fermer" */

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

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