<?php 
$controller = 'PosBrand';
$action = '';
if(isset($_POST['action'])){
    $action = $_POST['action'];
    if (isset($_POST['id'])) {$id = $_POST['id'];}
}elseif(isset($_GET['action'])){
    $action = $_GET['action'];
    if (isset($_GET['id'])) {$id = $_GET['id'];}
}
include $_SERVER["DOCUMENT_ROOT"].'/app/include/bootstrap.php';

$_form = new PosMarcaForm();
$_marca = new PosMarcaRepository();
$_listaMarcas = $_marca->getListaMarcas();

switch($action){
    case 'insert':
        $_form->populate($_POST);
        if($_form->isValid()){
            $_marca->setOptions($_POST);
            $result = $_marca->save($_marca->getOptions());
            if($result){
                $flashmessenger->addMessage(array('success'=>'Genial !! La Marca se registro exitosamente.'));
                header('Location: PosBrand.php');
            }else{
                $flashmessenger->addMessage(array('danger'=>'Error. Intenta nuevamente o contacta a tu proveedor de sistemas.'));
            }
        }else{
            $vista = 'PosMarca.php';
            include $root.'/View/Template.php';
        }
        break;
   
    case 'edit':
        if($_GET){$_marcaData = $_marca->getById($id);}
        if($_POST){$_marcaData = $_POST;}
        
        $_form->setActionController('edit');
        $_form->setId($id);
        $_form->populate($_marcaData);
        
        if(isset($_POST['id'])){
            if($_form->isValid()){
                $_marca->setOptions($_marcaData);
                $result = $_marca->update($id,$_marca->getOptions()); //no tengo id porque viene de post
                if($result){
                    $flashmessenger->addMessage(array('success'=>'Estupendo !! La Marca se actualizo exitosamente.'));
                    header("Location: PosBrand.php?action=edit&id=$id");
                }else{
                    $flashmessenger->addMessage(array('danger'=>'Error. Intenta nuevamente o contacta a tu proveedor de sistemas.'));
                }       
            }else{
                $vista = 'PosMarca.php';
                include $root . '/View/Template.php';
            }
        }else{
            $vista = 'PosMarca.php';
            include $root . '/View/Template.php';
        }        
        break;
    
    case 'delete': 
        if(!$_marca->isUsedInRecord($id)){
            if($_marca->delete($id)){
                $flashmessenger->addMessage(array('success'=>'Hecho !! La Marca fue eliminada satisfactoriamente.'));
            }
        }else{
            $message = 'Hola !! esta Marca no puede ser eliminada, esta siendo utilizada en almenos un registro.';
            $flashmessenger->addMessage(array('info'=>$message));
        }
        header('Location: PosBrand.php');
        break;
    
    default:
        $vista = 'PosMarca.php';
        include $root.'/View/Template.php';
}