<?php
$strModulo = 'PRUEBA';

$boolError = true;
$arrOrdenes = [
    "0100" => [
        "cTrab" => "#315",
        "maq" => "Rechazadora ZENN",
        "fol" => "0100",
        "fIni" => "22/10/21",
        "fFin" => "22/10/21",
        "desc" => "Cambio de rulina de trabajo",
        "prio" => "Muy alta",
        "tMan" => "Preventivo",
        "nEmp" => "88516",
        "obse" => "Se hizo el cambio de la rulina de trabajo al observarse un desgaste importante en la pieza.",
        "eva" => "Excelente",
        "cau" => "Mecánica",
        "mat" => [
            "conc" => "Rulina de trabajo",
            "uni" => "Pieza",
            "cant" => "1",
            "imp" => "795.00",
            "cTot" => "795.00"
        ],
        "rTiem" => [
            "fech" => "22/10/21",
            "hIni" => "10:00:00",
            "hFin" => "10:30:00",
            "tUti" => "00:30:00",
            "cosH" => "1,500.00",
            "impT" => "1,500.00"
        ]
    ],
    "0098" => [
        "cTrab" => "#613",
        "maq" => "Paneladora Salvagnini",
        "fol" => "0098",
        "fIni" => "19/10/21",
        "fFin" => "22/10/21",
        "desc" => "Cambio de el láser",
        "prio" => "Muy alta",
        "tMan" => "Preventivo",
        "nEmp" => "88550",
        "obse" => "Se hizo el cambio de el láser ya que se rompio.",
        "eva" => "Excelente",
        "cau" => "Mecánica",
        "mat" => [
            "conc" => "Láser",
            "uni" => "Pieza",
            "cant" => "1",
            "imp" => "1000.00",
            "cTot" => "1000.00"
        ],
        "rTiem" => [
            "fech" => "22/10/21",
            "hIni" => "10:00:00",
            "hFin" => "10:30:00",
            "tUti" => "00:30:00",
            "cosH" => "1,500.00",
            "impT" => "1,500.00"
        ]
    ],
    "0095" => [
        "cTrab" => "#613",
        "maq" => "Paneladora Salvagnini",
        "fol" => "0095",
        "fIni" => "22/10/21",
        "fFin" => "22/10/21",
        "desc" => "Cambio de rulina de trabajo",
        "prio" => "Muy alto",
        "tMan" => "Preventivo",
        "nEmp" => "88516",
        "obse" => "Cambio en la Bastidora Punzonadora",
        "eva" => "Excelente",
        "cau" => "Mecánica",
        "mat" => [
            "conc" => "Bastidora Punzonadora",
            "uni" => "Pieza",
            "cant" => "1",
            "imp" => "1200.00",
            "cTot" => "1200.00"
        ],
        "rTiem" => [
            "fech" => "28/10/21",
            "hIni" => "11:00:00",
            "hFin" => "12:30:00",
            "tUti" => "00:40:00",
            "cosH" => "1,800.00",
            "impT" => "1,800.00"
        ]
    ],
    "0080" => [
        "cTrab" => "#315",
        "maq" => "Rechazadora ZENN",
        "fol" => "0080",
        "fIni" => "22/10/21",
        "fFin" => "22/10/21",
        "desc" => "Cambio de rulina de trabajo",
        "prio" => "Muy alta",
        "tMan" => "Preventivo",
        "nEmp" => "88516",
        "obse" => "Se hizo el cambio de la rulina de trabajo al observarse un desgaste importante en la pieza.",
        "eva" => "Excelente",
        "cau" => "Mecánica",
        "mat" => [
            "conc" => "Rulina de trabajo",
            "uni" => "Pieza",
            "cant" => "1",
            "imp" => "795.00",
            "cTot" => "795.00"
        ],
        "rTiem" => [
            "fech" => "22/10/21",
            "hIni" => "10:00:00",
            "hFin" => "10:30:00",
            "tUti" => "00:30:00",
            "cosH" => "1,500.00",
            "impT" => "1,500.00"
        ]
    ],
    "0075" => [
        "cTrab" => "#613",
        "maq" => "Paneladora Salvagnini",
        "fol" => "0075",
        "fIni" => "22/10/21",
        "fFin" => "22/10/21",
        "desc" => "Cambio de rulina de trabajo",
        "prio" => "Muy alta",
        "tMan" => "Preventivo",
        "nEmp" => "88516",
        "obse" => "Se hizo el cambio de la rulina de trabajo al observarse un desgaste importante en la pieza.",
        "eva" => "Excelente",
        "cau" => "Mecánica",
        "mat" => [
            "conc" => "Rulina de trabajo",
            "uni" => "Pieza",
            "cant" => "1",
            "imp" => "795.00",
            "cTot" => "795.00"
        ],
        "rTiem" => [
            "fech" => "22/10/21",
            "hIni" => "10:00:00",
            "hFin" => "10:30:00",
            "tUti" => "00:30:00",
            "cosH" => "1,500.00",
            "impT" => "1,500.00"
        ]
    ],
    "0065" => [
        "cTrab" => "#023",
        "maq" => "Punzonadora",
        "fol" => "0065",
        "fIni" => "22/10/21",
        "fFin" => "22/10/21",
        "desc" => "Cambio de rulina de trabajo",
        "prio" => "Muy alta",
        "tMan" => "Preventivo",
        "nEmp" => "88516",
        "obse" => "Se hizo el cambio de la rulina de trabajo al observarse un desgaste importante en la pieza.",
        "eva" => "Excelente",
        "cau" => "Mecánica",
        "mat" => [
            "conc" => "Rulina de trabajo",
            "uni" => "Pieza",
            "cant" => "1",
            "imp" => "795.00",
            "cTot" => "795.00"
        ],
        "rTiem" => [
            "fech" => "22/10/21",
            "hIni" => "10:00:00",
            "hFin" => "10:30:00",
            "tUti" => "00:30:00",
            "cosH" => "1,500.00",
            "impT" => "1,500.00"
        ]
    ],
];

$arrCampos = [
    "cTrab" => "Centro de Trabajo",
    "maq" => "Máquina",
    "fol" => "Folio",
    "fIni" => "Fecha de Inicio",
    "fFin" => "Fecha de Termino",
    "desc" => "Descripción del Servicio de Mantenimiento",
    "prio" => "Prioridad",
    "tMan" => "Tipo de Mantenimiento",
    "nEmp" => "ID del Técnico",
    "obse" => "Observaciones",
    "eva" => "Evaluación del servicio",
    "cau" => "Causa de la falla",
    "mat" => [
        "conc" => "Concepto",
        "uni" => "Unidad",
        "cant" => "Cantidad",
        "imp" => "Importe",
        "cTot" => "Costo total"
    ],
    "rTiem" => [
        "fech" => "Fecha",
        "hIni" => "Hora Inicio",
        "hFin" => "Hora Termino",
        "tUti" => "Tiempo utilizado",
        "cosH" => "Costo HH",
        "impT" => "Importe"
    ],
];

if($_SERVER['REQUEST_METHOD'] == "POST"){
    $numOrden = $_POST["numOrden"];
    $boolError = empty($numOrden);
    $detallesOrden = [];

    if(array_key_exists("pdf", $_POST)){
        $datos = json_encode($arrOrdenes[$_POST["pdf"]]);
        $fields = array("infoPDF" => base64_encode($datos));
        $fieldsStr = http_build_query($fields);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://smart.solerpalau.mx/QA/api/pdfIOS/crearPdfTmp.php");
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fieldsStr);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $data = curl_exec($ch);
        curl_close($ch);

        $strInfo = base64_decode($data);
        $arrInfo = json_decode($strInfo, true);

        $filename = $arrInfo["name"];
        $fileinfo = $arrInfo["content"];

        // Header content type
        header('Content-type: application/pdf');
        header('Content-Disposition: inline; filename="' . $filename . '"');
        header('Content-Transfer-Encoding: binary');
        header('Accept-Ranges: bytes');

        // Read the file
        echo base64_decode($fileinfo);
        exit;
    }

    if(!$boolError){
        $detallesOrden = $arrOrdenes[$numOrden];
        $link = $_POST["from"];

        $cont = 0;
        $strOut = "";
        foreach($detallesOrden as $key=>$val){
            if($cont == 0 && !is_array($val)){
                $strOut .= "<tr> \n";
                $strOut .= "<td width=\"15%\" colspan=\"3\" class=\"etiquetaFormulario\"> \n";
                $strOut .= "<label class=\"noTopPadding\" for='". $key ."'>". $arrCampos[$key] ."</label> \n";
                $strOut .= "</td> \n";
                $strOut .= "<td width=\"30%\" colspan=\"6\" class=\"etiquetaFormulario\"> \n";
                $strOut .= "<input id='". $key ."' name='" . $key . "' value='" . $detallesOrden[$key] . "' data-dojo-type=\"dijit/form/ValidationTextBox\" style=\"width:100%\" required=\"false\" data-dojo-props=\"placeHolder:'Automático.'\"/> \n";
                $strOut .= "</td> \n";
                $cont++;
            }else if(!is_array($val)){
                $strOut .= "<td width=\"20%\" colspan=\"4\" class=\"etiquetaFormulario\"> \n";
                $strOut .= "<label class=\"noTopPadding\" for='". $key ."'>". $arrCampos[$key] ."</label> \n";
                $strOut .= "</td> \n";
                $strOut .= "<td width=\"35%\" colspan=\"7\" class=\"etiquetaFormulario\"> \n";
                $strOut .= "<input id='". $key ."' name='" . $key . "' value='" . $detallesOrden[$key] . "' data-dojo-type=\"dijit/form/ValidationTextBox\" style=\"width:100%\" required=\"false\" data-dojo-props=\"placeHolder:'Automático.'\"/> \n";
                $strOut .= "</td> \n";
                $strOut .= "</tr> \n";
                $cont = 0;
            }else{
                $bandName = $key == "mat" ? "Materiales y/o refacciones" : "Registro de tiempo";
                $strOut .= "<tr> \n";
                $strOut .= "<td>&nbsp;</td> \n";
                $strOut .= "</tr> \n";
                $strOut .= "<tr> \n";
                $strOut .= "<td width=\"100%\" colspan=\"20\" bgcolor=\"#FF0000\" style=\"height:23px;color:#FFFFFF;padding-left:5px;\">$bandName</td> \n";
                $strOut .= "</tr> \n";
                $strOut .= "<tr> \n";
                $strOut .= "<td>&nbsp;</td> \n";
                $strOut .= "</tr> \n";

                $cont1 = 0;
                foreach($val as $key0=>$val0){
                    if($cont1 == 0){
                        $strOut .= "<tr> \n";
                        $strOut .= "<td width=\"15%\" colspan=\"3\" class=\"etiquetaFormulario\"> \n";
                        $strOut .= "<label class=\"noTopPadding\" for='". $key0 ."'>". $arrCampos[$key][$key0] ."</label> \n";
                        $strOut .= "</td> \n";
                        $strOut .= "<td width=\"30%\" colspan=\"6\" class=\"etiquetaFormulario\"> \n";
                        $strOut .= "<input id='". $key0 ."' name='" . $key0 . "' value='" . $detallesOrden[$key][$key0] . "' data-dojo-type=\"dijit/form/ValidationTextBox\" style=\"width:100%\" required=\"false\" data-dojo-props=\"placeHolder:'Automático.'\"/> \n";
                        $strOut .= "</td> \n";
                        $cont1++;
                    }else{
                        $strOut .= "<td width=\"20%\" colspan=\"4\" class=\"etiquetaFormulario\"> \n";
                        $strOut .= "<label class=\"noTopPadding\" for='". $key0 ."'>". $arrCampos[$key][$key0] ."</label> \n";
                        $strOut .= "</td> \n";
                        $strOut .= "<td width=\"35%\" colspan=\"7\" class=\"etiquetaFormulario\"> \n";
                        $strOut .= "<input id='". $key0 ."' name='" . $key0 . "' value='" . $detallesOrden[$key][$key0] . "' data-dojo-type=\"dijit/form/ValidationTextBox\" style=\"width:100%\" required=\"false\" data-dojo-props=\"placeHolder:'Automático.'\"/> \n";
                        $strOut .= "</td> \n";
                        $strOut .= "</tr> \n";
                        $cont1 = 0;
                    }
                }
                $cont = 0;
            }
        }
    }
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta http-equiv="imagetoolbar" content="no" />
    <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Poppins:400,500,700,300,600">
    <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Open+Sans">
    <link media="screen" rel="stylesheet" type="text/css" href="css/principal.css" />
    <!--<link media="screen" rel="stylesheet" type="text/css" href="css/pagination.css"  />--> <!--Paginador-->
    <link rel="shortcut icon" type="image/x-icon" href="css/layout/global/sp.ico" />

    <link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/dojo/1.14.1/dijit/themes/claro/claro.css">
    <script src="//ajax.googleapis.com/ajax/libs/dojo/1.14.1/dojo/dojo.js" data-dojo-config="async: true, parseOnLoad:true"></script>

    <script type="application/javascript">
        // Cargamos los complementos de dojo
        require(["dojo/dom", "dojo/_base/fx", "dojo/_base/array", "dojo/query", "dojo/dom-construct", "dijit/registry", "dojo/dom-style", "dojo/ready", "dojo/on", "dojo/window",
                "dojo/store/Memory", "dijit/form/FilteringSelect", "dijit/form/Button", "dojo/dom-class", "dijit/Dialog",
                "dojo/_base/lang", "dojox/grid/DataGrid", "dojo/data/ItemFileWriteStore", "dojox/grid/enhanced/plugins/DnD", "dojox/grid/EnhancedGrid", "dojox/grid/enhanced/plugins/Selector", "dojox/grid/enhanced/plugins/IndirectSelection", "dojox/grid/enhanced/plugins/NestedSorting",
                "dijit/ProgressBar", "dijit/ConfirmDialog", "dojo/dom-style", "dijit/form/ComboButton", "dijit/Menu", "dijit/MenuItem", "dijit/MenuSeparator", "dijit/Tooltip", "dijit/form/Form", "dijit/form/TextBox",
                "dojox/grid/enhanced/plugins/Filter", "dijit/form/ValidationTextBox", "dijit/form/NumberSpinner", "dojo/request", "dojo/parser"],
            function(dom, fx, array, query, domConstruct, dijit, style, ready, on, win,
                     Memory, FilteringSelect, Button, domClass, Dialog,
                     lang, DataGrid, ItemFileWriteStore, DnDConfig, EnhancedGrid, Selector, indirectSelection, nestedSorting,
                     ProgressBar, ConfirmDialog, style, ComboButton, Menu, MenuItem, MenuSeparator, Tooltip, Form, TextBox, filter, ValidationTextBox, NumberSpinner, request) {

                const urlPeticiones = "plantillaEjemplo_DO.php";
                const idModulo = "<?php echo($strModulo);?>";

                // Para Mostrar de Mensajes de "error o éxito"
                var dgEjecuta = new Dialog({title: 'Procesando...', style: 'width:300px'});
                var pbMarcar = new ProgressBar({value: Number.POSITIVE_INFINITY, layoutAlign: 'left'});
                dgEjecuta.setContent(pbMarcar);
                dgResultadoError = new ConfirmDialog({ title:"<b>Error</b>", style: "min-width:300px; heigth; auto" });
                style.set(dgResultadoError.cancelButton.domNode, 'display', 'none');
                dgResultadoExito = new ConfirmDialog({ title:"<b>Éxito</b>", style: "min-width:300px; heigth; auto" });
                style.set(dgResultadoExito.cancelButton.domNode, 'display', 'none');


                /****************************************************************** Botones ******************************************************************/
                // Limpiar
                new Button({
                    label: "Regresar",
                    iconClass: "dijitEditorIcon dijitEditorIconUndo",
                    showLabel: true,
                    onClick: function() {
                        window.parent.frames.app_modulo.location.href = '<?php echo $link; ?>';
                    }
                }, "BTNCERRAR").startup();

                /****************************************************************** Acciones ******************************************************************/
                realizaAccion = function (accion){
                    dgEjecuta.set("title", "Consultando...");
                    dgEjecuta.show();

                    request.post(urlPeticiones, {
                        data: {
                            accion: accion,
                            idModulo: idModulo,
                            dato1: "prueba"
                        }
                    }).then(
                        function (response) {
                            var objResponse = JSON.parse(response);
                            if (objResponse['estatus'] == "ERROR") {
                                dgEjecuta.hide();
                                dgResultadoError.setContent(objResponse['errorDescripcion']);
                                dgResultadoError.show();
                            } else {
                                let datosRecibidos = objResponse["datosRecibidos"];

                                console.log(datosRecibidos);

                                dgEjecuta.hide();
                            }
                        }
                    );


                };

                ready(function() {
                    // Actualizar el tamaño del TabContainer en función del tamaño de página
                    var ventana = win.getBox();
                    var strVentana = (ventana.h-75-100)+"px";
                    style.set(dijit.byId("djTab").id, { height:strVentana });
                    dijit.byId("djTab").resize();

                    // Actualizar el tamaño del TabContainer en función del tamaño de página
                    on(window, "resize", function() {
                        var ventana = win.getBox();
                        var strVentana = (ventana.h-75-100)+"px";
                        style.set(dijit.byId("djTab").id, { height:strVentana });
                        dijit.byId("djTab").resize();
                    });
                    // Eliminar la cortina de entrada
                    fx.fadeOut({node: dom.byId("loadingOverlay"), duration: 1}).play();
                    setTimeout(function () {
                        domConstruct.destroy("loadingOverlay");
                    }, 1);

                });
            });
    </script>

</head>

<body class="claro">
<div id="loadingOverlay" class="loadingOverlay pageOverlay">
    <div class="loadingMessage">Espere...</div>
</div>

<div id="wrapper_container_module">
    <div id="wrapper_table" style="position:relative;">
        <div data-dojo-type="dijit/form/Form" id="frm" data-dojo-id="frm" encType="multipart/form-data"
             action="<?php echo($_SERVER['PHP_SELF']); ?>" method="post" style="position:relative;">
            <script type="dojo/on" data-dojo-event="submit">return true;</script>
            <div id="wrapper_table_head">Órden de Mantenimiento</div>
            <div id="wrapper_table_body_mod_app">
                <table width="100%" height="auto">
                    <tr>
                        <td width="100%" colspan="20" align="center">
                    </tr>

                    <tr>
                        <td width="100%" colspan="20" align="center">
                            <button id="BTNCERRAR" type="button"></button>
                        </td>
                    </tr>
                </table>


                <div id="djTab" data-dojo-type="dijit/layout/TabContainer" data-dojo-props="tabPosition:'top'" style="width:100%;">
                    <div data-dojo-type="dijit/layout/ContentPane" title="Detalles" data-dojo-props="selected:true">
                        <table width="100%" heifght="auto">
                            <?php echo $strOut; ?>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

</body>

