<div class="cs-space-20 cs-space-md-120"></div>
<div class="d-none d-md-block cs-space-40"></div>

<div class="container">
<div class="row">
  <div class="cs-space-20 d-md-none"></div>
	
	
	 
	
	
  <?php
  foreach ($categories as $key => $category) {
    if($category['title'] == $current_parent) {
      $childs = $category["sub_crb_cat"];
      if($key == intval($_GET['cid'])){
          $current_img  = $category["crb_cat_photo"];
      }
        foreach ($childs as $scid => $child) {
          if($child["title"] == $_GET['son']){
            if(! empty($child["sub_sub_crb_cat"])) {          
              foreach ($child["sub_sub_crb_cat"] as $k => $vv) {
                  if($key == intval($_GET['cid']) && $scid == intval($_GET['scid']) && $k == intval($_GET['scsid']) && $_GET['son'] == $child["title"]) {
                    $desc_cat1 = $vv["desc"];
                    $desc_cat2 = $desc_cat1;
                    $unidadM = $vv["desc_medida"];
                  }
              }
            }else {
              $desc_cat2 = $child["desc"];
              $unidadM = $child["desc_medida"];
            }
          }

          if($scid == intval($_GET['scid'])){
            $extra1 = $child["extra1"];
            $ex_2 = $child["extra2"];
            $ex_tit1 = $child["extra1tit"];
            $ex_tit2 = $child["extra2tit"];
          }

        }

    }
  }
  ?>
  <!-- breadcrums -->
  <div class="col-12 breadcrums" data-ipc="<?php echo $_GET['scid'] ?>">
    <a href="<?php echo get_permalink($repo_page); ?>">Temas/<?php echo $current_parent ?></a>
    <?php foreach ($categories as $key => $catogory):
      $childs = $catogory["sub_crb_cat"];
        foreach ($childs as $x => $child):
          if($catogory['title'] == $current_parent):
          if($key == $_GET['cid'] && $x == $_GET['scid']):
            $maintitle = $child["title"];?>
        <a href="#">/<?php echo $child["title"]; ?></a>
    <?php
      endif;
      foreach ($child['sub_sub_crb_cat'] as $k => $last_child):
      if($key == $_GET['cid'] && $x == $_GET['scid'] && $k == $_GET['scsid'] && isset($_GET['scsid'])):
        $maintitle = $last_child["title"];
        ?>
        <a href="#">/<?php echo $last_child["title"]; ?></a>
        <?php
      endif;
      endforeach;
      endif;
      endforeach;
    endforeach; ?>
  </div>
  <!-- breadcrums -->
  <div class="cs-space-20 d-md-none"></div>
</div>
</div>
<div class="d-none d-md-block cs-space-40"></div>
<section id="single-params">
  <div class="container">
    <div class="row">
      <div class="col-12 col-md-4">
        <div class="lateral-menu">
          <div class="header-lateral-menu">
            <div class="row">
              <div class="col-4 d-flex align-items-center">
                <img class="logo" src="<?php echo $current_img; ?>">
              </div>
              <div class="col-8">
                <h4><?php echo $current_parent; ?></h4>
              </div>
            </div>
          </div>
          <div class="body-lateral-menu">
            <?php foreach ($categories as $cid => $category) {
              if($category['title'] == $current_parent) {
                $childs = $category["sub_crb_cat"];
                foreach ($childs as $scid => $child) {
                $child_title = str_replace(".", "", $child["title"]);
            ?>
              <div class="row">
                <div class="align-items-end col-2 col-md-2  flex-column">
                  <a class="more " data-toggle="collapse" href="#<?php echo "op-" . $scid ?>" role="button" aria-expanded="false" aria-controls="<?php echo "op-" . $scid ?>">
                    <?php if(!empty($child['sub_sub_crb_cat'])) : ?>
                      <p>+</p>
                    <?php else: ?>
                      <p>-</p>
                    <?php endif; ?>
                  </a>
                </div>
                <div class="col-10 col-md-8">
                  <a href="<?php echo get_permalink($pageID); ?>/?scid=<?php echo $scid ?>&cid=<?php echo $cid ?>&data=<?php echo $child['api_title'] ?>&parent=<?php echo $category['title'] ?>&son=<?php echo $child['title'] ?>&list">
                    <h3 class="<?php echo ($scid == $_GET['scid']) ? 'active' : '' ?> js-ids"  data-cid="<?php echo $_GET['cid']; ?>" data-scid=<?php echo $_GET['scid']; ?>  aria-expanded="false" aria-controls="<?php echo $child_title; ?>">
                      <?php echo $child["title"]; ?>
                    </h3>
                  </a>
                </div>
              </div>
              <div class="multi-collapse row collapse <?php echo ($scid == $_GET['scid']) ? 'show' : '' ?> collapse-info" id="<?php echo "op-" . $scid ?>">
                <div class="col-2 col-md-2"></div>
                <div class="col-10 col-md-12" style="margin-left: 40px;">
                  <?php if(! empty($child['sub_sub_crb_cat'])) : ?>
                    <ul>
                      <?php $count = 0; ?>
                      <?php foreach ($child['sub_sub_crb_cat'] as $k => $last_child):?>
                        <?php if(isset($_GET['list'])): ?>
                          <?php if($count == 0 && $_GET['son'] == $child["title"]) {
                            $maintitle = $last_child["title"];
                            $desc_cat1 = $last_child["desc"];
                          } ?>
                          <li class="<?php echo ($count == 0 && $_GET['son'] == $child["title"]) ? 'active' : '' ?>">
                            <a class="js-ids1" href="<?php echo get_permalink($pageID); ?>/?scsid=<?php echo $k; ?>&cid=<?php echo $cid ?>&scid=<?php echo $scid ?>&data=<?php echo $last_child['api_title'] ?>&parent=<?php echo $current_parent; ?>&son=<?php echo $child['title'] ?>" data-scsid="<?php echo $_GET['scsid']; ?>"><?php echo $subcat['title'] ?>
                              <?php echo $last_child["title"]; ?>
                            </a>
                          </li>
                        <?php else: ?>
                          <li class="<?php echo ($cid == $_GET['cid'] && $scid == $_GET['scid'] && $k == $_GET['scsid'] && isset($_GET['scsid'])) ? 'active' : '' ?>">
                            <a class="js-ids1" href="<?php echo get_permalink($pageID); ?>/?scsid=<?php echo $k; ?>&cid=<?php echo $cid ?>&scid=<?php echo $scid ?>&data=<?php echo $last_child['api_title'] ?>&parent=<?php echo $current_parent; ?>&son=<?php echo $child['title'] ?>" data-scsid="<?php echo $_GET['scsid']; ?>"><?php echo $subcat['title'] ?>
                              <?php echo $last_child["title"]; ?>
                            </a>
                          </li>
                        <?php endif; ?>
                    <?php
                    $count = $count + 1;
                  endforeach; ?>
                    </ul>
                  <?php endif; ?>
                </div>
              </div>
            <?php }
              }
            }?>
          </div>
        </div>
      </div>
        <div class="cs-space-20 d-md-none"></div>
        <div class="col-12 col-md-8" id="parameters">
          <h2 class="main-t"><?php echo $maintitle; ?></h2>
          <div class="d-none d-md-block cs-space-10"></div>
          <p class="params-p"><?php echo $desc_cat2; ?></p>
          <p style="font-weight: bold;color: black;">Unidad de medida:<span class="params-p"><?php echo $unidadM; ?></span></p>
          <div class="cs-space-20 d-md-none"></div>
          <div class="d-none d-md-block cs-space-20"></div>
          <div class="graphic-container">
            <div class="header-graphic">
              <?php
              foreach ($categories as $key => $category) {
                if($category['title'] == $current_parent) {
                  $childs = $category["sub_crb_cat"];
                  if($key == intval($_GET['cid'])){
                    $current_img  = $category["crb_cat_photo"];
                    foreach ($childs as $scid => $child) {
                      if($scid == intval($_GET['scid'])){
                        $desc_cat1 = $child["desccat1"];
                        if(!empty($child["sub_sub_crb_cat"])) {
                          foreach ($child["sub_sub_crb_cat"] as $x => $vx) {
                            if($x == intval($_GET['scsid'])){
                              $metaemail = $vx["emailmeta"];
                              $metadesc = $vx["descmeta"];
                              $metalc = $vx["alccmeta"];
                              $metcar = $vx["carmeta"];
                              $metunidad = $vx["unidadmeta"];
                              $metpermeta = $vx["permeta"];
                              $metoport = $vx["opormeta"];
                              $metarev = $vx["revmeta"];
                              $metafu = $vx["fumeta"];
                              $metaacc = $vx["accmeta"];
                              $metanot = $vx["notmeta"];
                              $commeta = $vx["commeta"];
                              $calregmeta = $vx["calregmeta"];
                              $reddatafumetameta = $vx["reddatafumeta"];
                              $notes = $vx["tablenotes"];
                              $pdfneta = $vx["pdfmeta"];
                              $metaact = $vx["actualizacionemeta"];
                            }
                          }
                        }else {
                          $metaemail = $child["emailmeta"];
                          $metadesc = $child["descmeta"];
                          $metalc = $child["alccmeta"];
                          $metcar = $child["carmeta"];
                          $metunidad = $child["unidadmeta"];
                          $metpermeta = $child["permeta"];
                          $metoport = $child["opormeta"];
                          $metarev = $child["revmeta"];
                          $metafu = $child["fumeta"];
                          $metaacc = $child["accmeta"];
                          $metanot = $child["notmeta"];
                          $commeta = $child["commeta"];
                          $calregmeta = $child["calregmeta"];
                          $reddatafumetameta = $child["reddatafumeta"];
                          $notes = $child["tablenotes"];
                          $metaact = $child["actualizacionemeta"];
                          $pdfneta = $child["pdfmeta"];
                          // var_dump($child);
                        }
                      }
                    }
                  }
                }
              }
               ?>
              <!-- <h3 class="col-md-12">Parámetros de la consulta</h3> -->
              <div class="container">
                <button class="btn btn-primary hBack" type="button">Volver a la consulta</button>
              </div>
              <div class="container">
                <div class="row">
                  <div class="col-6 col-md-3 col-md-3 col-space-down">
                    <div class="graphic-box">
                      <img src="https://www.secmca.org/wp-content/themes/CM/src/images/131972@2x.png" alt="">
                      <h5>Exportar</h5>
                      <div class="arrow-down"></div>
                      <div class="dropdown js-hover-dropdown" id="js-downland">
                        <ul>
                          <li id="txt" ><a href="#" >Txt</a></li>
                          <li id="csv" ><a href="#">csv</a></li>
                          <li id="ex" ><a href="#">Excel</a></li>
                          <li id="xls2" ><a href="#">Excel</a></li>
                        </ul>
                        <span style="height: 38px;padding-left: 20px;display: flex;align-items: center;background: #f2f2f2;color: black;font-weight: bold;" id="dre">Json</span>
                      </div>
                    </div>
                  </div>
                  <div class="col-6 col-md-3 col-md-3 col-space-down">
                    <div class="graphic-box">
                      <img src="https://www.secmca.org/wp-content/themes/CM/src/images/1170718-copy@2x.png" alt="">
                      <h5>Graficar</h5>
                      <div class="arrow-down"></div>
                      <div class="dropdown js-hover-dropdown">
                        <ul>
                          <li class="js-showtab"><a href="#" id="line">por Líneas</a></li>
                          <li class="js-showtab" id="bar-chart"><a href="#" id="bar">por Barras</a></li>
                        </ul>
                      </div>
                    </div>
                  </div>
                  <div class="col-6 col-md-3 col-md-3 col-space-down">
                    <div class="graphic-box share-box-wrapper js-share-box-wrapper">
                      <div class="graphic-box-helper"></div>
                      <img src="https://www.secmca.org/wp-content/themes/CM/src/images/149722@2x.png" alt="">
                      <h5>Compartir</h5>
                      <div class="arrow-down js-arrowToex"></div>
                      <div class="share-box">
                        <div class="social">
                          <?php $actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
                          $fac_link = urldecode($actual_link);
                          ?>
                          <a target="_blank" href="https://www.facebook.com/sharer.php?cid=<?php echo $_GET['scsid']; ?>&u=<?=urlencode($actual_link)?>"><img src="https://www.secmca.org/wp-content/themes/CM/src/images/face-ico@2x.png" alt=""></a>
                          <a target="_blank" href="https://twitter.com/intent/tweet?url=<?=urlencode($actual_link)?>"><img src="https://www.secmca.org/wp-content/themes/CM/src/images/twi-ico@2x.png" alt=""></a>
                          <a target="_blank" href="mailto:?subject=SECMCA DATOS: Resultado de <?php echo $current_parent; ?> ( <?php echo $maintitle ?> ) &amp;body=resultado de <?php echo $maintitle ?>-><?=urlencode($actual_link)?>"><img src="https://www.secmca.org/wp-content/themes/CM/src/images/mail-ico@2x.png" alt=""></a>
                        </div>
                        <div class="share-link">
                          <p class="text-link">Compartir link</p>
                          <div class="copy">
                            <img src="https://www.secmca.org/wp-content/themes/CM/src/images/link@2x.png" alt="">
                            <button onclick="copyLink()"  id="cpy" style="background: transparent;
      height: 31px;width: 43px;font-size: 11px;border: none;">Copiar</buxtton>
                          </div>
                        </div>
                        <div class="box-link">
                          <p><input type="text" value="<?php echo $actual_link; ?>" id="myInput" readonly style="background: transparent;border: none;"></p>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div class="col-6 col-md-3 col-md-3 col-space-down boxx">
                    <div class="graphic-box graphic-blue-box">
                      <div class="circle-wrapper">
                        <div class="circle-info">i</div>
                        <h5>Metadatos</h5>
                      </div>
                      <div class="arrow"></div>
                    </div>
                    <div class="white-box">
                      <div class="accordion md-accordion" id="accordionEx" role="tablist" aria-multiselectable="true">
                        <div class="card">
                          <div class="card-header" role="tab" id="headingOne1">
                            <a data-toggle="collapse" data-parent="#accordionEx" href="#collapseOne1" aria-expanded="true"
                              aria-controls="collapseOne1">
                              <h5 class="mb-0 d-flex justify-content-between">
                                Contacto <i class="fas fa-angle-down rotate-icon"></i>
                              </h5>
                            </a>
                          </div>
                          <div id="collapseOne1" class="collapse show contact-table" role="tabpanel" aria-labelledby="headingOne1"
                            data-parent="#accordionEx">
                            <div class="card-body fixed-card">
                              <div class="row">
                                <div class="col-12 col-md-12 col-wrapper-contact">
                                  <div class="row">
                                    <div class="col-12 col-md-6 d-flex align-items-center justify-content-left">
                                      <p>Contacto</p>
                                    </div>
                                    <div class="col-12 col-md-6 d-flex align-items-center justify-content-left">
                                      <p><pre><?php echo $metaemail; ?></pre></p>
                                    </div>
                                  </div>
                                  <div class="row">
                                    <div class="col-12 col-md-6 d-flex align-items-center justify-content-left">
                                      <p>Fecha de actualización de los metadatos</p>
                                    </div>
                                    <div class="col-12 col-md-6 d-flex align-items-center justify-content-left">
                                      <p><pre><?php echo $metaact; ?></pre></p>
                                    </div>
                                  </div>
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                        <div class="card">
                          <div class="card-header" role="tab" id="headingTwo2">
                            <a class="collapsed" data-toggle="collapse" data-parent="#accordionEx" href="#collapseTwo2"
                              aria-expanded="false" aria-controls="collapseTwo2">
                              <h5 class="mb-0 d-flex justify-content-between">
                                Características de los datos <i class="fas fa-angle-down rotate-icon"></i>
                              </h5>
                            </a>
                          </div>
                          <div id="collapseTwo2" class="collapse" role="tabpanel" aria-labelledby="headingTwo2"
                            data-parent="#accordionEx">
                            <div class="card-body">
                              <div class="col-12 col-md-12 col-wrapper-contact">
                                <div class="row">
                                  <div class="col-12 col-md-6 d-flex align-items-center justify-content-left">
                                    <p>Descripción</p>
                                  </div>
                                  <div class="col-12 col-md-6 d-flex align-items-center justify-content-left">
                                    <p><pre><?php echo $metadesc; ?></pre></p>
                                  </div>
                                </div>
                                <div class="row">
                                  <div class="col-12 col-md-6 d-flex align-items-center justify-content-left">
                                    <p>Alcance Cobertura y desagregaciones</p>
                                  </div>
                                  <div class="col-12 col-md-6 d-flex align-items-center justify-content-left">
                                    <p><pre><?php echo $metalc; ?></pre></p>
                                  </div>
                                </div>
                                <div class="row">
                                  <div class="col-12 col-md-6 d-flex align-items-center justify-content-left col-wrapper-contact">
                                    <p>Características</p>
                                  </div>
                                  <div class="col-12 col-md-6 d-flex align-items-center justify-content-left">
                                    <p><pre><?php echo $metcar; ?></pre></p>
                                  </div>
                                </div>
                                <div class="row">
                                  <div class="col-12 col-md-6 d-flex align-items-center justify-content-left col-wrapper-contact">
                                    <p>Unidad de medida</p>
                                  </div>
                                  <div class="col-12 col-md-6 d-flex align-items-center justify-content-left">
                                    <p><pre><?php echo $metunidad; ?></pre></p>
                                  </div>
                                </div>
                                <div class="row">
                                  <div class="col-12 col-md-6 d-flex align-items-center justify-content-left col-wrapper-contact">
                                    <p>Periodicidad</p>
                                  </div>
                                  <div class="col-12 col-md-6 d-flex align-items-center justify-content-left">
                                    <p><pre><?php echo $metpermeta; ?></pre></p>
                                  </div>
                                </div>
                                <div class="row">
                                  <div class="col-12 col-md-6 d-flex align-items-center justify-content-left">
                                    <p>Oportunidad</p>
                                  </div>
                                  <div class="col-12 col-md-6 d-flex align-items-center justify-content-left">
                                    <p><pre><?php echo $metoport; ?></pre></p>
                                  </div>
                                </div>
                                <div class="row">
                                  <div class="col-12 col-md-6 d-flex align-items-center justify-content-left">
                                    <p>Revisión</p>
                                  </div>
                                  <div class="col-12 col-md-6 d-flex align-items-center justify-content-left">
                                    <p><pre><?php echo $metarev; ?></pre></p>
                                  </div>
                                </div>
                                <div class="row">
                                  <div class="col-12 col-md-6 d-flex align-items-center justify-content-left">
                                    <p>Fuente primaria de información</p>
                                  </div>
                                  <div class="col-12 col-md-6 d-flex align-items-center justify-content-left">
                                    <p><pre><?php echo $metafu; ?></pre></p>
                                  </div>
                                </div>
                                <div class="row">
                                  <div class="col-12 col-md-6 d-flex align-items-center justify-content-left">
                                    <p>Acceso a los datos</p>
                                  </div>
                                  <div class="col-12 col-md-6 d-flex align-items-center justify-content-left">
                                    <p><pre><?php echo $metaacc; ?></pre></p>
                                  </div>
                                </div>
                                <div class="row">
                                  <div class="col-12 col-md-6 d-flex justify-content-left">
                                    <p>Notas por país</p>
                                  </div>
                                  <div class="col-12 col-md-6 d-flex align-items-center justify-content-left">
                                    <p><pre><?php echo $metanot; ?></pre></p>
                                  </div>
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                        <div class="card">
                          <div class="card-header" role="tab" id="headingThree3">
                            <a class="collapsed" data-toggle="collapse" data-parent="#accordionEx" href="#collapseThree3"
                              aria-expanded="false" aria-controls="collapseThree3">
                              <h5 class="mb-0 d-flex justify-content-between">
                                Comparación entre países y cálculo regional <i class="fas fa-angle-down rotate-icon"></i>
                              </h5>
                            </a>
                          </div>
                          <div id="collapseThree3" class="collapse" role="tabpanel" aria-labelledby="headingThree3"
                            data-parent="#accordionEx">
                            <div class="card-body">
                              <div class="row">
                                <div class="col-12 col-md-12 col-wrapper-contact">
                                  <div class="row">
                                    <div class="col-12 col-md-6 d-flex align-items-center justify-content-left">
                                      <p>Comparabilidad regional</p>
                                    </div>
                                    <div class="col-12 col-md-6 d-flex align-items-center justify-content-left">
                                      <p><?php echo $commeta; ?></p>
                                    </div>
                                  </div>
                                  <div class="row">
                                    <div class="col-12 col-md-6 d-flex justify-content-left">
                                      <p>Cálculo regional</p>
                                    </div>
                                    <div class="col-12 col-md-6 d-flex align-items-center justify-content-left">
                                      <p><?php echo $calregmeta; ?></p>
                                    </div>
                                  </div>
                                  <div class="row">
                                    <div class="col-12 col-md-6 d-flex align-items-center justify-content-left">
                                      <p>Fuente datos regionales</p>
                                    </div>
                                    <div class="col-12 col-md-6 d-flex align-items-center justify-content-left">
                                      <p><?php echo $reddatafumetameta; ?></p>
                                    </div>
                                  </div>
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                        <div class="downland-meta">
                          <a href="<?php echo wp_get_attachment_url( $pdfneta ); ?>" download>
                            <div class="button">
                              <img src="https://www.secmca.org/wp-content/themes/CM/src/images/131972@2x.png" alt="">
                              <span>Exportar</span>
                            </div>
                          </a>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="d-none d-md-block cs-space-40"></div>
                <div class="row">
                  <div class="col-12">
                    <div class="space"></div>
                  </div>
                </div>
                <div class="d-none d-md-block cs-space-30"></div>
                <div class="row">
                  <div class="col-md-8">
                    <?php 
                    // Order variables
                    sort($ajustes);
     
     
     if (in_array("Serie original", $ajustes) && count($ajustes) == 1) {
    // Si solo hay "Serie original", agregamos "Tendencia-ciclo"
    array_push($ajustes, "Tendencia-ciclo");

    // Duplicar las variables existentes en $variables para incluir tanto "Serie original" como "Tendencia-ciclo"
    $duplicatedVars = [];
    foreach ($variables as $valVar) {
        $varExp = explode("|", $valVar);

        // Mantener la variable con "Serie original" tal como está
        array_push($duplicatedVars, implode("|", $varExp));

        // Crear la nueva variable duplicada con "Tendencia-ciclo"
        $varExp[1] = "Tendencia-ciclo"; // Cambiar el ajuste a "Tendencia-ciclo"
        array_push($duplicatedVars, implode("|", $varExp));
    }

    // Reemplazamos el contenido de $variables con el nuevo array duplicado
    $variables = $duplicatedVars;
} elseif (in_array("Tendencia-ciclo", $ajustes) && count($ajustes) == 1) {
    // Si solo hay "Tendencia-ciclo", agregamos "Serie original"
    array_push($ajustes, "Serie original");

    // Duplicar las variables existentes en $variables para incluir tanto "Tendencia-ciclo" como "Serie original"
    $duplicatedVars = [];
    foreach ($variables as $valVar) {
        $varExp = explode("|", $valVar);

        // Mantener la variable con "Tendencia-ciclo" tal como está
        array_push($duplicatedVars, implode("|", $varExp));

        // Crear la nueva variable duplicada con "Serie original"
        $varExp[1] = "Serie original"; // Cambiar el ajuste a "Serie original"
        array_push($duplicatedVars, implode("|", $varExp));
    }

    // Reemplazamos el contenido de $variables con el nuevo array duplicado
    $variables = $duplicatedVars;
} elseif (in_array("Serie original", $ajustes) && in_array("Tendencia-ciclo", $ajustes) && count($ajustes) == 2) {
    // El caso original cuando hay ambos valores en $ajustes
    $ajusvars = [];
    $all_vars = explode("*", $all_vars);
    foreach ($ajustes as $kaju => $valAju) {
        foreach ($all_vars as $kvar => $valVar) {
            $varExp = explode("|", $valVar);
            array_splice($varExp, 1, 0, $valAju);
            array_push($ajusvars, implode("|", $varExp));
        }
    }
} else {
    // Si no se cumplen las condiciones anteriores, solo procesamos $all_vars
    $all_vars = explode("*", $all_vars);
}





                      natcasesort($variables); 
                        
                      foreach($countries as $k => $country) {
                        foreach($ajustes as $z => $aju) {
                          ksort($data[$country][$aju], SORT_NATURAL);
                        }
                      }

                    //custom order countries by sandra. 

                      $orderArray = array(
                                          1 => "Costa Rica",
                                          2 => "El Salvador",
                                          3 => "Guatemala",
                                          4 => "Honduras",
                                          5 => "Nicaragua",
                                          6 => "República Dominicana",
                                          7 => "Panamá"
                                      );

                      sort($countries);

                      if(in_array('CAPARD', $countries) || in_array('CARD', $countries) || in_array('CA', $countries)) {

                        $orderArrayReg = array(
                                        1 => "CA",
                                        2 => "CARD",
                                        3 => "CAPARD",
                                    );
                        $testarr = $countries;
                        $countriesx = sortArrayByArray($orderArrayReg, $countries);
                        $filteredFoo = array_diff($countries, $orderArrayReg);
                        $countries = array_merge($filteredFoo, $countriesx);
                        foreach ($countries as $key => $value) {
                          if(!in_array($value, $testarr)) {
                            unset($countries[$key]);
                          }
                        }
                      }

                      if (in_array('Panamá', $countries) && in_array('República Dominicana', $countries)) {
                         for ($i=0; $i < count($countries); $i++) { 
                            if($countries[$i] == "Panamá"){
                              $countries[$i] = "República Dominicana";
                            }elseif ($countries[$i] == "República Dominicana") {
                              $countries[$i] = "Panamá";
                            }
                          }
                      }

                      $arr = sortArrayByArray($data, $orderArray);
                       if(in_array("Serie original", $ajustes) && in_array("Tendencia-ciclo", $ajustes) && count($ajustes) == 2) {

                         $original_Ser_arr = [];
                      foreach ($variables as $keyvar => $valuevar) {
                        $exv = explode("|",$valuevar);
                        if(strpos($valuevar, "Serie original") > 0){
                          array_push($original_Ser_arr,$exv[1] . "|" . $exv[2]);
                          unset($variables[$keyvar]);
                        }else {
                          unset($variables[$keyvar]);
                          $variables[$keyvar] = $exv[1] . "|" . $exv[2];
                        }  
                        
                      }

                      $ajuVars = array_merge($original_Ser_arr, $variables);   


                          foreach ($arr as $kcount => $countr) {
                           foreach ($countr as $kaj => $vaj) {
                            foreach ($vaj as $key => $value) {
                              $exv = explode("|",$key);
                              $arr[$kcount][$kaj][$exv[1] . "|" . $exv[2]] = $arr[$kcount][$kaj][$key];
                              unset($arr[$kcount][$kaj][$key]);
                            }
                           }
                          }
                       }

                      function sortArrayByArray(array $array, array $orderArray) {
                          $ordered = array();
                          foreach ($orderArray as $key) {
                              if (array_key_exists($key, $array)) {
                                  $ordered[$key] = $array[$key];
                                  unset($array[$key]);
                              }
                          }
                          return $ordered + $array;
                      }

                      function array_insert(&$array, $position, $insert){
                            if (is_int($position)) {
                                array_splice($array, $position, 0, $insert);
                            } else {
                                $pos   = array_search($position, array_keys($array));
                                $array = array_merge(
                                    array_slice($array, 0, $pos),
                                    $insert,
                                    array_slice($array, $pos)
                                );
                            }
                        }

                      // test vars

                     
                       
                      //remove some vars from some countries.. again by Sandra
                        if($maintitle != "PIB en constantes (volumenes encadenados) anual") {
                           foreach ($arr as $cKey => $arrint) {
                              ksort($arr[$cKey]);
                              foreach ($arrint as $vKey => $sa) {
                                $arr[$cKey][trim($vKey)] = $sa;
                                if($vKey == "7|Deuda interna consolidada anual/ PIB") { // viene mal los paises del ws
                                  if($cKey != "República Dominicana" && $cKey != "Honduras" && $cKey != "Guatemala") {
                                    unset($arr[$cKey][$vKey]);
                                  }
                                }elseif($vKey == "3|Deuda interna consolidada - ME anual"){ // vienen paises correctos del ws
                                  if($cKey != "República Dominicana" && $cKey != "Honduras" && $cKey != "Guatemala") {
                                    unset($arr[$cKey][$vKey]);
                                  } 
                                  if(empty($arr[$cKey])) {
                                   unset($arr[$cKey]); 
                                  }
                                }elseif($vKey == "3|Deuda interna consolidada - ME") { // vienen paises correctos del ws 
                                  if($cKey != "República Dominicana" && $cKey != "Honduras" && $cKey != "Guatemala") {
                                    unset($arr[$cKey][$vKey]);
                                  } 
                                  if(empty($arr[$cKey])) {
                                   unset($arr[$cKey]); 
                                  }
                                }elseif($vKey == "22|Deuda interna consolidada - ME") { // vienen paises correctos del ws 
                                  if($cKey != "República Dominicana" && $cKey != "Honduras" && $cKey != "Guatemala") {
                                    unset($arr[$cKey][$vKey]);
                                  } 
                                  if(empty($arr[$cKey])) {
                                   unset($arr[$cKey]); 
                                  }
                                }elseif($vKey == "11|Deuda interna consolidada") { // vienen paises correctos del ws 
                                  if($cKey != "República Dominicana" && $cKey != "Honduras" && $cKey != "Guatemala") {
                                    unset($arr[$cKey][$vKey]);
                                  } 
                                  if(empty($arr[$cKey])) {
                                   unset($arr[$cKey]); 
                                  }
                                }elseif($vKey == "7|Deuda interna consolidada / PIB") { // no vienen los paises correctos del ws 
                                  if($cKey != "República Dominicana" && $cKey != "Honduras" && $cKey != "Guatemala") {
                                    unset($arr[$cKey][$vKey]);
                                  } 
                                  if(empty($arr[$cKey])) {
                                   unset($arr[$cKey]); 
                                  }
                                }
                              }
                            }
                        }

                      $countryfinal = [];
                      $varfinal = [];
                      $colspan = [];
                      $simpleColspan = [];

                        
                            
                      foreach ($arr as $cKey => $arrint) {
                        $sum = 0;
                        foreach ($arrint as $vKey => $sa) {
                          $sum += count($sa);
                          array_push($simpleColspan,count($sa));
                          if( !in_array($cKey, $countryfinal) ) {
                            $countryfinal[] = $cKey;
                          }
                          if( !in_array($vKey, $varfinal) ) {
                            $varfinal[] = $vKey;
                          }
                        }
                        array_push($colspan,$sum);
                      }
                      
                      if(in_array('CAPARD', $countryfinal) || in_array('CARD', $countryfinal) || in_array('CA', $countryfinal)) {

                        $orderArrayReg = array(
                                        1 => "CA",
                                        2 => "CARD",
                                        3 => "CAPARD",
                                    );
                        $testarr = $countryfinal;
                        $countryfinalx = sortArrayByArray($orderArrayReg, $countryfinal);
                        $filteredFoo = array_diff($countryfinal, $orderArrayReg);
                        $countryfinal = array_merge($filteredFoo, $countryfinalx);
                        foreach ($countryfinal as $key => $value) {
                          if(!in_array($value, $testarr)) {
                            unset($countryfinal[$key]);
                          }
                        }
                      }
                      natsort($varfinal);
                       natsort($all_vars);  
                        
                        
                       if($maintitle == "PIB en constantes (volumenes encadenados) anual") {
                         foreach ($arr as $key => $value) {
                           if($key == "República Dominicana") {
                            foreach ($value as $x => $value2) {
                              $new = explode("|",$x);
                              if(count($new) == 2) {
                                unset($arr[$key][$x]);
                              }
                            }
                           }elseif ($key == "El Salvador") {
                             foreach ($value as $xx => $valuex) {
                              $newx = explode("|",$xx);
                              if(count($newx) == 2) {
                                unset($arr[$key][$xx]);
                              }
                            }
                           }else{
                            foreach ($value as $x2 => $value3) {
                              $new2 = explode("|",$x2);
                              if(count($new2) == 3) {
                                unset($arr[$key][$x2]);
                              }else {
                                unset($arr[$key][$x2]);
                                $arr[$key][trim($x2)] = $value3;  
                              }
                            }
                           }
                         }
                         $newarr = [];
                         $newvars = [];
                         foreach ($arr as $j => $val) {
                          foreach ($val as $key => $value) {
                             if(!in_array($key, $newvars, true)){
                                  array_push($newvars, $key);
                              }
                            foreach ($value as $p => $pval) {
                                if(!isset($newarr[$key . ' - ' . $j]))
                                  $new2 = explode("|",$key);
                                  $newarr[$new2[1] . ' - ' . $j] = [];
                                  $newarr[$new2[1] . ' - ' . $j][$p] =  $pval["valorCalculado"];
                                  $newarr[$new2[1] . ' - ' . $j]["Color"] =  $pval["color"];
                            }
                          }
                         }
                         natsort($newvars);
                        }  
                        
                        function customKeySort($a, $b) {
                            $order = array("Costa Rica","El Salvador","Guatemala","Honduras","Nicaragua","República Dominicana","Panamá","CA", "CARD", "CAPARD");
                            $indexA = array_search($a, $order);
                            $indexB = array_search($b, $order);
                        
                            return $indexA - $indexB;
                        }
                        
                        uksort($arr, "customKeySort");
                    ?>
                    <h3>Resultado de la consulta</h3>
                  </div>
                  <div class="col-md-4 d-flex align-items-center justify-content-end">
                    <ul class="nav nav-pills mb-3" id="pills-tab" role="tablist">
                      <li class="nav-item js-nav-mode js-cuadro">
                        <a class="nav-link active active-mode d-flex align-items-center justify-content-center" id="pills-table1-tab" data-toggle="pill" href="#pills-table1" role="tab" aria-controls="pills-table1" aria-selected="true"><p>Cuadro</p></a>
                      </li>
                      <li class="nav-item js-nav-mode js-chart">
                        <a class="nav-link noactive-mode d-flex align-items-center justify-content-center" id="pills-chart-tab" data-toggle="pill" href="#pills-chart" role="tab" aria-controls="pills-chart" aria-selected="false"><p>Gráfico</p></a>
                      </li>
                    </ul>
                  </div>
                </div>
                <div class="d-none d-md-block cs-space-30"></div>
                <div class="row">
                  <div class="graphic w-100">
                    <div class="tab-content" id="pills-tabContent">
                      <div class="tab-pane fade show active" id="pills-table1" role="tabpanel" aria-labelledby="pills-table1-tab">
                        <div class="wraper-tadiv">
                            <!-- <div class="search-placeholder">
                              <span>Buscar</span>
                            </div> -->
                            <?php if($variableEncontrada):
                            
                            //var_dump($tipoCambio);?>
 <?php
// Obtener todos los países
$paises = array_keys($tipoCambio);








// Buscar el índice de "Panamá - Balboas"
$panamaKey = array_search("Panamá - Balboas", $paises);

if ($panamaKey !== false) {
    // Extraer "Panamá - Balboas" del arreglo
    $panamaValue = $paises[$panamaKey];
    array_splice($paises, $panamaKey, 1); // Eliminar del arreglo
    $paises[] = $panamaValue; // Agregar al final
}




// Obtener todas las fechas únicas y ordenarlas cronológicamente
$fechasUnicas = [];
foreach ($tipoCambio as $variables) {
    foreach ($variables as $fechas) {
        foreach ($fechas as $fecha => $valores) {
            if (!in_array($fecha, $fechasUnicas)) {
                $fechasUnicas[] = $fecha;
            }
        }
    }
}

// Ordenar las fechas cronológicamente
usort($fechasUnicas, function($a, $b) {
    return strtotime($a) - strtotime($b);
});

 
 
?>
							
<div class="table-wrapper">
<table id="tabl" class="table table-striped table-results search-table">
    <thead>
        <tr style="text-align: left!important; border:none!important;">
            <th colspan="<?php echo array_sum(array_map(function($pais) use ($tipoCambio) {
                return count($tipoCambio[$pais]); // Número de variables por país
            }, array_keys($tipoCambio))) + 1; ?>" style="border: none!important;text-align: left!important;padding: 0;">
                <p style="font-weight: bold;">Secretaría Ejecutiva del Consejo Monetario Centroamericano</p>
            </th>
        </tr>
        <tr style="border: none!important;">
            <th colspan="<?php echo array_sum(array_map(function($pais) use ($tipoCambio) {
                return count($tipoCambio[$pais]); // Número de variables por país
            }, array_keys($tipoCambio))) + 1; ?>" style="border: none!important;text-align: left!important;padding: 0;">
                <p style="font-weight: bold;">Tipo de Cambio Diario</p>
            </th>
        </tr>
        <tr>
            <th class="text-center p-2">Fechas</th>
            <?php foreach ($paises as $pais) : ?>
                <?php
                $colspan = count($tipoCambio[$pais]); // Número de variables por país
                ?>
                <th class="text-center p-2" colspan="<?php echo $colspan; ?>"><?php echo $pais; ?></th>
            <?php endforeach; ?>
        </tr>
        <tr>
            <td></td>
            <?php foreach ($paises as $pais) : ?>
                <?php foreach ($tipoCambio[$pais] as $variable => $fechas) : ?>
                    <th class="text-center p-2"><?php echo $variable; ?></th>
                <?php endforeach; ?>
            <?php endforeach; ?>
        </tr>
    </thead>
    <tbody>
        <?php
        // Generar filas de la tabla
        foreach ($fechasUnicas as $fecha) :
        ?>
            <tr>
                <td class="text-left p-2">
                    <p class="text-left">
                        <?php echo $fecha; ?>
                    </p>
                </td>
                <?php foreach ($paises as $pais) : ?>
                    <?php
                    foreach ($tipoCambio[$pais] as $variable => $fechas) {
                        $valor = "--"; // Valor por defecto cuando no hay datos
                        if (isset($fechas[$fecha])) {
                            $valor = $fechas[$fecha][0];
                        }
                        echo "<td class='text-center t4'><p class='text-right'>{$valor}</p></td>";
                    }
                    ?>
                <?php endforeach; ?>
            </tr>
        <?php endforeach; ?>
    </tbody>
</table>
</div>

                            <?php else: ?>
                            <div class="table-wrapper">
                              <?php if(! empty($arr)): 
                                      if(in_array("Serie original", $ajustes) && in_array("Tendencia-ciclo", $ajustes) && count($ajustes) == 2 && $_GET['son'] != "Volumen transado por mercado " && $_GET['son'] != "Volumen transado por moneda" && $_GET['son'] != "Volumen transado por sector"):
                              ?>
                                      <table id="tabl" class="table table-striped table-results search-table">
                                        <thead>
                                          <tr style="text-align: left!important; border:none!important;">
                                            <th colspan="7" style="border: none!important;text-align: left!important;padding: 0;"><p style="font-weight: bold;">Secretaría Ejecutiva del Consejo Monetario Centroamericano</p></th>
                                          </tr>
                                          <tr style="border: none!important;">
                                            <th colspan="7" style="border: none!important;text-align: left!important;padding: 0;"><p style="font-weight: bold;"><?php echo $current_parent; ?></p></th>
                                          </tr>
                                          <tr style="border: none!important;">
                                            <th colspan="7" style="border: none!important;text-align: left!important;padding: 0;"><p style="font-weight: bold;"><?php echo $_GET['son']; ?></p></th>
                                          </tr>
                                          <tr>
                                             <th colspan="7" style="border: none!important;text-align: left!important;padding: 0;"><p style="font-weight: bold;">Unidad de medida: <?php echo $unidadM; ?></p></th>
                                          </tr>
                                          <tr>
                                            <th class="text-center p-2">Fechas</th>
                                              <?php  $x = 0; foreach($countries as $country): ?>
                                                   <th class="text-center p-2" colspan=<?php echo count($ajuVars); ?>><?php echo $country; ?></th>
                                              <?php $x++; endforeach; ?>
                                          </tr>
                                          <tr>
                                             <th class="text-center p-2"></th>
                                             <?php $x = 0; foreach($countries as $country): ?>
                                               <?php  foreach($ajustes as $ajuste): ?>
                                                   <th class="text-center p-2" colspan=<?php echo count($ajuVars) / count($ajustes); ?>>
                                                      <?php 
                                                      if(in_array("Serie original", $ajustes) && in_array("Tendencia-ciclo", $ajustes) && count($ajustes) == 2) {
                                                          echo $ajuste;
                                                      }else if(count($ajustes) == 1){
                                                         echo '';
                                                      }else {
                                                         echo '';
                                                      }
                                                      ?>
                                                    </th>
                                              <?php $x++; endforeach; ?>
                                            <?php endforeach; ?>
                                          </tr>
                                          <tr>
                                            <td></td>
                                            <!--  <?php foreach($countries as $k => $country): ?>
                                              <?php foreach($ajustes as $z => $aju): ?>
                                                  <?php foreach ($arr[$country][$aju] as $t => $value): ?>
                                                    <td><?php 
                                                      $new = explode("|",$t);
                                                      echo $new[2]; 
                                                      ?>
                                                    </td>    
                                                  <?php endforeach; ?>                                        
                                                <?php endforeach; ?>
                                            <?php endforeach; ?> -->

                                            <?php foreach($countries as $k => $country): ?>
                                              <?php  foreach($ajuVars as $u => $va):
                                                $newvar = explode("|", $va); ?>
                                                    <td><?php echo $newvar[1]; ?></td>
                                              <?php endforeach; ?>
                                            <?php endforeach; ?>
                                          </tr>
                                        </thead>
                                        <tbody>
                                          <?php foreach($periodos as $periodo): 
                                                  $newper = explode("-", $periodo);
                                          ?>
                                            <tr>
                                              <td class="text-left p-2">
                                                <p class="text-left">
                                                  <?php 
                                                    $findme   = 'XII';
                                                    $pos = strpos($periodo, $findme);
                                                    if($pos !== false){
                                                      $newper = explode("-", $periodo);
                                                      echo $newper[0];
                                                    }else {
                                                      echo $periodo;
                                                    }
                                                    ?>
                                                </p>
                                              </td>
                                               <?php foreach($arr as $k => $country): ?>
                                                <?php foreach($ajustes as $x => $z): ?>
                                                  <?php foreach($ajuVars as $o => $zo): 
                                                    if(strpos($zo,$z) === 0) :
                                                      if(!is_null($arr[$k][$z][$zo])):
                                                        if($arr[$k][$z][$zo][$periodo]["Fictisio"] == "N" ) :
                                                          if(!is_null($arr[$k][$z][$zo][$periodo]["valorCalculado"])): ?>
                                                            <td class="text-center "><p class="text-right ss"><?php
                                                             echo number_format((float)$arr[$k][$z][$zo][$periodo]["valorCalculado"], 2, '.', ''); ?></p></td>
                                                          <?php else: ?>
                                                            <td class="text-center "><p class="text-right">--</p></td> 
                                                          <?php endif; ?>
                                                    <?php else: ?>
                                                          <td class="text-center " ><p class="text-right"><?php echo "--"; ?></p></td>
                                                    <?php endif; else: ?>
                                                      <td class="text-center "><p class="text-right"><?php echo "--"; ?></p></td>
                                                  <?php endif;endif; endforeach; ?>
                                                <?php endforeach; ?>
                                               <?php endforeach; ?>


                                            <!--   <?php foreach($countries as $k => $country): ?>
                                                <?php foreach($ajustes as $o => $aju): ?>
                                                  <?php foreach($ajusvars as $k => $var): 
                                                     ?>
                                                   <?php 

                                                   if(!is_null($arr[$country][$aju][$var])){
                                                    ?>
                                                    <?php if($arr[$country][$aju][$var][$periodo]["Fictisio"] == "S" ): ?>
                                                      <td class="text-center "><p class="text-right">--</p></td>  
                                                    <?php else: ?>
                                                    <td class="text-center "><p class="text-right"><?php echo isset($arr[$country][$aju][$var][$periodo]["valorCalculado"]) ? number_format((float)$arr[$country][$aju][$var][$periodo]["valorCalculado"], 2, '.', '') : '--' ?></p></td>
                                                    <?php endif; ?>
                                                    <?php 
                                                  }else {
                                                    ?>
                                                    <td></td>
                                                    <?php 
                                                   }
                                                    ?>
                                                    <?php endforeach; ?>
                                                  <?php endforeach; ?>
                                              <?php endforeach; ?> -->
                                            </tr>
                                          <?php endforeach; ?>
                                        </tbody>
                                      </table>
                          <?php 
                            else :
                          ?>
                            <table id="tabl" class="table table-striped table-results search-table">
                              <thead>
                                <tr style="text-align: left!important; border:none!important;">
                                  <th colspan="7" style="border: none!important;text-align: left!important;padding: 0;"><p style="font-weight: bold;">Secretaría Ejecutiva del Consejo Monetario Centroamericano</p></th>
                                </tr>
                                <tr style="border: none!important;">
                                  <th colspan="7" style="border: none!important;text-align: left!important;padding: 0;"><p style="font-weight: bold;"><?php echo $current_parent; ?></p></th>
                                </tr>
                                <tr style="border: none!important;">
                                  <th colspan="7" style="border: none!important;text-align: left!important;padding: 0;"><p style="font-weight: bold;"><?php echo $_GET['son']; ?></p></th>
                                </tr>
                                <tr>
                                   <th colspan="7" style="border: none!important;text-align: left!important;padding: 0;"><p style="font-weight: bold;">Unidad de medida: <?php echo $unidadM; ?></p></th>
                                </tr>
                                <tr>
                                  <th class="text-center p-2">Fechas</th>
                                  <?php foreach($countryfinal as $country): 
                                    if($maintitle == "PIB en constantes (volumenes encadenados) anual") :?>
                                     <th class="text-center p-2" colspan="<?php echo (count($newvars) != 2) ? count($newvars) - 2 : count($all_vars);?>"><?php echo $country; ?></th>
                                     <?php else: ?>
                                      <th class="text-center p-2 test" colspan="<?php echo count($all_vars); ?>"><?php echo $country; ?></th>
                                  <?php endif; endforeach ?>
                                </tr>
                                <tr>
                                  <td></td>
                                  <?php if($maintitle == "PIB en constantes (volumenes encadenados) anual"): ?>
                                  <?php foreach($countryfinal as $country): 
                                    if($country == "República Dominicana" || $country == "El Salvador"):?>
                                      <?php foreach($newvars as $var): 
                                            $new = explode("|",$var);
                                            if(count($new) == 3):        
                                        ?>
                                          <td class="text-center p-2 vars-label"><?php echo $new[1]; ?></td>
                                        <?php 
                                            endif;
                                          endforeach;
                                      ?>
                                      <?php else: ?>
                                        <?php foreach($newvars as $var): 
                                                      $new = explode("|",$var);
                                                       if(count($new) == 2):
                                        ?>
                                          <td class="text-center p-2 vars-label"><?php echo $new[1]; ?></td>
                                        <?php 
                                          endif;
                                          endforeach;
                                      ?>
                                      <?php endif; ?>
                                    <?php endforeach; ?>
                                  <?php else: ?>
                                      <?php foreach($countryfinal as $country): ?>
                                      <?php foreach($all_vars as $var): 
                                            $new = explode("|",$var); ?>
                                          <td class="text-center p-2 vars-label"><?php echo $new[1]; ?></td>
                                        <?php 
                                          endforeach;
                                        endforeach;
                                      ?>
                                  <?php endif; ?>
                                </tr>
                              </thead>
                              <tbody>
                          <?php foreach($periodos as $periodo) : ?>
                                <tr>
                                  <td class="text-left p-2">
                                    <p class="text-left">
                                      <?php 
                                        $findme   = 'XII';
                                        $pos = strpos($periodo, $findme);
                                        if($pos !== false){
                                          $newper = explode("-", $periodo);
                                          echo $newper[0];
                                        }else {
                                          echo $periodo;
                                        }
                                      ?>
                                    </p>
                                  </td>
                                  <?php if($maintitle == "PIB en constantes (volumenes encadenados) anual"): ?>
                                    <?php foreach($countryfinal as $k => $country): 
                                    if($country == "República Dominicana" || $country == "El Salvador"): ?>
                                   <?php foreach($newvars as $var): 
                                    $new = explode("|",$var);
                                    if(count($new) == 3):
                                      $new = explode("|",$var);
                                      if(!is_null($arr[$country][$var][$periodo]["valorCalculado"])): 
                                        if($arr[$country][$var][$periodo]["valorCalculado"] == 0):
                                          if($arr[$country][$var][$periodo]["Fictisio"] == "S") :
                                            ?>
                                            <td class="text-center  ns"><p class="text-right"><?php echo '--'; ?></p></td>
                                          <?php else: 
                                            if(!is_null($arr[$country][$var][$periodo]["valorCalculado"])): ?>
                                              <td class="text-center  ns"><p class="text-right"><?php echo $arr[$country][$var][$periodo]["valorCalculado"]; ?></p></td>
                                            <?php else: ?>
                                              <td class="text-center  ns"><p class="text-right">--</p></td>
                                            <?php endif; ?>
                                          <?php endif; ?>
                                        <?php else: ?>
                                          <!-- si no es 0 -->
                                            <td class="text-center t1"><p class="text-right"><?php echo number_format((float)$arr[$country][$var][$periodo]["valorCalculado"], 2, '.', ''); ?></p></td>
                                        <?php endif; ?>
                                      <?php else: ?>
                                         <!-- si es nulo -->
                                         <td class="text-center"><p class="text-right"><?php echo "--"?></p></td>
                                      <?php endif; ?> 
                                    <?php endif; ?>
                                    <?php endforeach; ?>
                                  <?php else: ?>
                                    <?php foreach($all_vars as $var): 
                                      $new = explode("|",$var);
                                      if(count($new) == 2):
                                      if(!is_null($arr[$country][$var][$periodo]["valorCalculado"])): 
                                        if($arr[$country][$var][$periodo]["valorCalculado"] == 0):
                                          if($arr[$country][$var][$periodo]["Fictisio"] == "S") :
                                            ?>
                                            <td class="text-center  ns"><p class="text-right"><?php echo '--'; ?></p></td>
                                          <?php else: 
                                            if(!is_null($arr[$country][$var][$periodo]["valorCalculado"])): ?>
                                              <td class="text-center  ns"><p class="text-right"><?php echo $arr[$country][$var][$periodo]["valorCalculado"]; ?></p></td>
                                            <?php else: ?>
                                              <td class="text-center  ns"><p class="text-right">--</p></td>
                                            <?php endif; ?>
                                          <?php endif; ?>
                                        <?php else: ?>
                                          <!-- si no es 0 -->
                                            <td class="text-center t1"><p class="text-right"><?php echo number_format((float)$arr[$country][$var][$periodo]["valorCalculado"], 2, '.', ''); ?></p></td>
                                        <?php endif; ?>
                                      <?php else: ?>
                                         <!-- si es nulo -->
                                         <td class="text-center "><p class="text-right"><?php echo "--" ?></p></td>
                                      <?php endif; ?> 
                                    <?php endif; ?> 
                                    <?php endforeach ?>
                                  <?php endif; ?>

                                  <?php endforeach ?>
                                    <?php else: ?>
                                      <?php foreach($countryfinal as $k => $country): ?>
                                   <?php foreach($all_vars as $var): 
                                    $new = explode("|",$var);
                                    if(count($new) == 3):
                                      $new = explode("|",$var);
                                      if(!is_null($arr[$country][$var][$periodo]["valorCalculado"])): 
                                        if($arr[$country][$var][$periodo]["valorCalculado"] == 0):
                                          if($arr[$country][$var][$periodo]["Fictisio"] == "S") :
                                            ?>
                                            <td class="text-center  ns"><p class="text-right"><?php echo '--'; ?></p></td>
                                          <?php else: 
                                            if(!is_null($arr[$country][$var][$periodo]["valorCalculado"])): ?>
                                              <td class="text-center  ns"><p class="text-right"><?php echo $arr[$country][$var][$periodo]["valorCalculado"]; ?></p></td>
                                            <?php else: ?>
                                              <td class="text-center  ns"><p class="text-right">--</p></td>
                                            <?php endif; ?>
                                          <?php endif; ?>
                                        <?php else: ?>
                                          <!-- si no es 0 -->
                                           <td class="text-center t3"><p class="text-right"><?php echo number_format((float)$arr[$country][$var][$periodo]["valorCalculado"], 2, '.', ''); ?></p></td>
                                        <?php endif; ?>
                                      <?php else: ?>
                                         <!-- si es nulo -->
                                         <td class="text-center "><p class="text-right"><?php echo "--" ?></p></td>
                                      <?php endif; ?> 
                                    <?php endif; ?>
                                    <?php endforeach; ?>
                                    <?php foreach($all_vars as $var): 
                                      $new = explode("|",$var);
                                      if(count($new) == 2):
                                      if(!is_null($arr[$country][$var][$periodo]["valorCalculado"])): 
                                        if($arr[$country][$var][$periodo]["valorCalculado"] == 0):
                                          if($arr[$country][$var][$periodo]["Fictisio"] == "S") :
                                            ?>
                                            <td class="text-center  ns"><p class="text-right"><?php echo '--'; ?></p></td>
                                          <?php else: 
                                            if(!is_null($arr[$country][$var][$periodo]["valorCalculado"])): ?>
                                              <td class="text-center  ns"><p class="text-right"><?php echo $arr[$country][$var][$periodo]["valorCalculado"]; ?></p></td>
                                            <?php else: ?>
                                              <td class="text-center  ns"><p class="text-right">--</p></td>
                                            <?php endif; ?>
                                          <?php endif; ?>
                                        <?php else: ?>
                                          <!-- si no es 0 -->
                                           <?php if($maintitle != "Tipo de cambio de mercado") : ?>
                                           <td class="text-center t4"><p class="text-right"><?php echo number_format((float)$arr[$country][$var][$periodo]["valorCalculado"], 2, '.', ''); ?></p></td>
                                           <?php else: ?>
                                            <td class="text-center t4"><p class="text-right"><?php echo number_format((float)$arr[$country][$var][$periodo]["valorCalculado"], 2, '.', ''); ?></p></td>
                                           <?php endif; ?>
                                        <?php endif; ?>
                                      <?php else: ?>
                                         <!-- si es nulo -->
                                         <td class="text-center "><p class="text-right"><?php echo "--" ?></p></td>
                                      <?php endif; ?> 
                                    <?php endif; ?> 
                                    <?php endforeach ?>

                                  <?php endforeach ?>
                                  <?php endif; ?>    
                                </tr>
                            <?php endforeach ?>
                              </tbody>
                            </table>
                        <?php
                          endif;
                          else:
                            echo "No se encontraron datos con esos criterios.";
                          endif ?>
                          </div>
                            <?php endif; ?>
                          </div>
                          <div class="table-notes">
                          <div class="d-none d-md-block cs-space-20"></div>
                          <?php if($notes): ?>
                          <h2 class="mb-2">Notas</h2>
                          <pre style="width: 97%;"><?php echo $notes; ?></pre>
                        <?php endif; ?>
                          <div class="d-none d-md-block cs-space-20"></div>
                        </div>
                        </div>
                        <div class="tab-pane fade" id="pills-chart" role="tabpanel" aria-labelledby="pills-chart-tab">
                          <div class="">
                            <h2 clas="text-center" style="text-align: center;padding-top: 20px;">Filtros</h2>
                          </div>
                          <div id="do_legend"></div>
                          <div class="" style="position: relative;">
                            <div class="ticks js-ticks"></div>
                          </div>  
                            <div class="chartWrapper">
                              <?php if(count($periodos) <  30): ?>
                                <div class="chartContainer chartContainer-xs">
                                    <canvas id="chart"></canvas>
                                </div>
                              <?php elseif (count($periodos) > 30 && count($periodos) < 70): ?>
                                <div class="chartContainer chartContainer-s">
                                    <canvas id="chart"></canvas>
                                </div>
                              <?php elseif (count($periodos) > 70 && count($periodos) < 90): ?>
                                <div class="chartContainer chartContainer-md">
                                    <canvas id="chart"></canvas>
                                </div>
                              <?php elseif (count($periodos) > 90): ?>
                                <div class="chartContainer chartContainer-lg">
                                    <canvas id="chart"></canvas>
                                </div>
                              <?php  endif; ?>
                          </div>
                          <a id="download" download="<?php echo $_GET['son'] ?>.jpg" href="" class="btn btn-primary float-left bg-flat-color-1" title="Descargar Gráfico" style="display: flex;justify-content: space-around;align-items: center;width: 184px;background: #f7b903;border: #f7b903;">Exportar gráfico<i class="fa fa-download"></i></a>
                        </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
    </div>
  </div>
</section>
<div class="d-none d-md-block cs-space-40"></div>
<?php $json_string = json_encode($arr); ?>
<script type="text/javascript">
//# sourceURL= chart_SCRIPTS.js
    var data = <?php echo $variableEncontrada ? json_encode($tipocambiodata) : json_encode($data_arr); ?>;
    
    // Iterar sobre las claves del objeto
Object.keys(data).forEach(key => {
    // Verificar si la clave es una de las que buscamos y contiene "| SV-DO"
    if (
        key === "PIB anual en constantes-variación | SV-DO - El Salvador" || 
        key === "PIB anual en constantes-variación | SV-DO - República Dominicana"
    ) {
        // Crear la nueva clave sin "| SV-DO"
        const newKey = key.replace(" | SV-DO", "");
        // Asignar el valor existente a la nueva clave
        data[newKey] = data[key];
        // Eliminar la clave original
        delete data[key];
    }
});

    var labels = <?php echo $variableEncontrada ? json_encode($tipocambiolabel) : json_encode($data_label); ?>;
    
  var ctx = document.getElementById('chart').getContext('2d');
  var xAxisLabelMinWidth = 90;
  var datasets = [];
  var color;
  for(var i in data) {
    var values = [];
    for(var j in labels) {
      console.log(labels[j]);
      if (data[i].hasOwnProperty(labels[j])) {
        values.push( data[i][labels[j]]);
      }else
        // values.push(NaN);
        values.push(NaN);
    }
    if(data[ i ]["Color"] == null){
      data[ i ]["Color"] = 'rgba(255, 8, 8, 1)';
    }
    datasets.push({
      label: i,
      borderWidth:1.6,
      backgroundColor: 'rgba(0, 0, 0, 0)',
      borderColor: data[ i ]["Color"],
      data: values,
      pointRadius: 0
    });
  };

  var configchart = {
    type: 'line',

    data: {
        labels: labels,
        datasets: datasets
    },

    options: {
        responsive: true,
        maintainAspectRatio: false,
        legendCallback: function (chart) {
            // Return the HTML string here.
            console.log(chart.data.datasets);
            var text = [];
            text.push('<ul class="' + chart.id + '-legend">');
            for (var i = 0; i < chart.data.datasets.length; i++) {
              // style="background-color:' + chart.data.datasets[i].borderColor + '"
                text.push('<li><span class="js-kabel" id="legend-' + i + '-item"  onclick="updateDataset(event, ' + '\'' + i + '\'' + ')">');
                if (chart.data.datasets[i].label) {
                    text.push(chart.data.datasets[i].label);
                }
                text.push('</span><input type="color" class="js-color-bar" name="favcolor" value="'+chart.data.datasets[i].borderColor+'"></li>');
            }
            text.push('</ul>');
            return text.join("");
        },
        title: {
            display: true,
            position: 'top',
            text: [ $('.main-t').text() ,'Secretaría Ejecutiva del Consejo Monetario Centroamericano'],
            fontSize: 14
        },
        legend: {
           display: true,
           position: 'bottom'
       },
       tooltips: {
            mode: 'nearest',
            intersect: false,
            callbacks: {
                label: function (tooltipItem, data) {
                    let label = data.datasets[tooltipItem.datasetIndex].label + ' - ' + data.labels[tooltipItem.index];
                    let datasetLabel = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
                    return label + ': ' + datasetLabel.toLocaleString();
                }
            }
        },
        scales: {
          yAxes: [{
              ticks: {
                  display: true,
                  fontSize: 18
              },
              barPercentage: 0.40
          }],
          xAxes: [{
            ticks: {
                fontSize: 18
            },
              offset: true,
            }]
      }
    },
  };

  var ctxd = document.getElementById('chart').getContext('2d');

      window.mychart = new Chart(ctxd, configchart);
      $("#do_legend").html(window.mychart.generateLegend());

  // Show/hide chart by click legend
  updateDataset = function (e, datasetIndex) {
      var index = datasetIndex;
      var ci = e.view.mychart;
      var meta = ci.getDatasetMeta(datasetIndex);
      if(meta.hidden == null){
        meta.hidden = false;
      }
      var result= (meta.hidden == true) ? false : true;
      if(result==true)
      {
            meta.hidden = true;
          $('#' + e.path[0].id).css("text-decoration", "line-through");
      }else{
          $('#' + e.path[0].id).css("text-decoration","");
            meta.hidden = false;
      }

      ci.update();
  };
  function fitChart(){
      var chartCanvas = document.getElementById('chart');
      var maxWidth = chartCanvas.parentElement.parentElement.clientWidth;
      var width = Math.max(mayChart.data.labels.length * xAxisLabelMinWidth, maxWidth);

      chartCanvas.parentElement.style.width = width +'px';
  }


  function fillCanvasBackgroundWithColor(canvas, color) {
  // Get the 2D drawing context from the provided canvas.
  const context = canvas.getContext('2d');

  // We're going to modify the context state, so it's
  // good practice to save the current state first.
  context.save();

  // Normally when you draw on a canvas, the new drawing
  // covers up any previous drawing it overlaps. This is
  // because the default `globalCompositeOperation` is
  // 'source-over'. By changing this to 'destination-over',
  // our new drawing goes behind the existing drawing. This
  // is desirable so we can fill the background, while leaving
  // the chart and any other existing drawing intact.
  // Learn more about `globalCompositeOperation` here:
  // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  context.globalCompositeOperation = 'destination-over';

  // Fill in the background. We do this by drawing a rectangle
  // filling the entire canvas, using the provided color.
  context.fillStyle = color;
  context.fillRect(0, 0, canvas.width + 400, canvas.height + 200);

  // Restore the original context state from `context.save()`
  context.restore();
}
function downloadJSON(data, filename) {
  const jsonString = JSON.stringify(data);
  const downloadLink = document.createElement("a");
  downloadLink.setAttribute("href", "data:text/json;charset=utf-8," + encodeURIComponent(jsonString));
  downloadLink.setAttribute("download", filename);
  document.body.appendChild(downloadLink);
  downloadLink.click();
  document.body.removeChild(downloadLink);
   var newWindow = window.open();
      newWindow.document.write("<pre>" + jsonString + "</pre>");
}

var objeto_js = JSON.parse('<?php echo $json_string; ?>');

document.getElementById("dre").addEventListener('click', function(e){
    e.preventDefault();
console.log("err");
  downloadJSON(objeto_js, "data.json");
});

document.getElementById("download").addEventListener('click', function(){
  const canvas = document.getElementById('chart');
fillCanvasBackgroundWithColor(canvas, 'white');
  /*Get image of canvas element*/
  var url_base64jp = document.getElementById("chart").toDataURL("image/png", 1.0);
  /*get download button (tag: <a></a>) */
  var a =  document.getElementById("download");
  /*insert chart image url to download button (tag: <a></a>) */
  a.href = url_base64jp;
});
  // function done(){
  //   var url=window.mychart.toBase64Image();
  //   document.getElementById("downloadPNG").href=url;
  // }

  var myChart;

  $("#line").click(function(e) {
    e.preventDefault();
    change('line');
  });

  $("#bar").click(function(e) {
    e.preventDefault();
    change('bar');
  });

  function change(newType) {
  var ctx = document.getElementById("chart").getContext("2d");

  // Remove the old chart and all its event handles
  if (window.mychart) {
    window.mychart.destroy();
  }

  // Chart.js modifies the object you pass in. Pass a copy of the object so we can use the original object later
  var temp = jQuery.extend(true, {}, configchart);
  temp.type = newType;
   for (var i = 0; i < $('.js-color-bar').length; i++) {
      var input = $('.js-color-bar')[i];
      temp.data.datasets[i].borderColor = input.value;
       if(newType == "bar") {
        temp.data.datasets[i].backgroundColor = input.value;
       }
   }
  if(newType == "bar") {
    var datasets = temp.data.datasets;
    $.each( datasets, function( key, value ) {
      value.backgroundColor = value.borderColor;
    });
  }
  myChart = new Chart(ctx, temp);
  window.mychart = myChart;
};


</script>
<script>
        document.addEventListener('DOMContentLoaded', function () {
            // Función para obtener los parámetros de la URL
            function getQueryParams() {
                const params = {};
                const queryString = window.location.search.substring(1);
                const queryParts = queryString.split('&');

                queryParts.forEach(part => {
                    const [key, value] = part.split('=');
                    params[decodeURIComponent(key)] = decodeURIComponent(value);
                });

                return params;
            }

            // Verifica el parámetro de la URL
            const params = getQueryParams();
            console.log(params['son']);
            if (params['son'] === 'Tipo de cambio diario') {
                // Oculta el gráfico de barras
                document.getElementById('bar-chart').classList.add('d-none');
                document.getElementById('ex').classList.add('d-none');
            }else {
                document.getElementById('xls2').classList.add('d-none');
            }

            // Aquí puedes agregar más lógica para manejar el cambio entre gráficos
        });
    </script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
