<?php #ajax/print.php

require_once "../bin/init_ajax.php";
require_once "../lib/content.php";

function getContent($key, $getText = false, $demoMode = false) {
  global $content, $data, $links, $refs, $options;

  $ret = "";
  if (array_key_exists($key, $content)) {
    if ($getText && isset($options[$key])) {
      if (is_array($content[$key])) {
        $ret = array();
        foreach ($options[$key] as $option) {
          if (in_array($option["value"], $content[$key])) {
            $ret[] = $option["display"];
          }
        }
      } else {
        foreach ($options[$key] as $option) {
          $ret = "&nbsp;";
          if ($option["value"]==$content[$key]) {
            $ret = $option["display"];
            break;
          }
        }
      }
    } else {
      $ret = $content[$key];
    }
  } else if (isset($data[$key])) {
    if (isset($data[$key]["default"]) && $data[$key]["default"]!="") {
      $ret = $data[$key]["default"];
    } else if ($demoMode) {
      $ret = $data[$key]["title"];
    }
  } else if (isset($links[$key])) {
    $ret = array();
  } else if (isset($refs[$key])) {
    $ret = array();
  } else {
    $ret = $key;
  }

  if (isset($data[$key]["prefix"]) && !is_array($ret)) {
    $ret = $data[$key]["prefix"].$ret;
  }
  if (isset($data[$key]["postfix"]) && !is_array($ret)) {
    $ret.= $data[$key]["postfix"];
  }
  
  return $ret;
}

function moveIfOverlap(&$floating, &$left, &$top, $width, $height, $dir = "none", $lastdir = "none") {
  $moved = false;
  foreach ($floating as $key => $float) {
    if (
      $left < $float["right"] && 
      $left+$width > $float["left"] && 
      $top < $float["bottom"] &&        
      $top+$height > $float["top"]
    ) {
      if ($float["dir"]=="left" && $lastdir!="right") {
        $left = $float["right"];
      } else if ($float["dir"]=="right" && $lastdir!="left") {
        $left = $float["left"] - $width;
      } else if ($float["dir"]=="up" && $lastdir!="down") {
        $top = $float["bottom"];
      } else if ($float["dir"]=="down" && $lastdir!="up") {
        $top = $float["top"] - $height;
      }
      $lastdir = $float["dir"];
      $moved = true;
    }
  }
  if ($moved) {
    moveIfOverlap($floating, $left, $top, $width, $height, $dir, $lastdir);
  } else if ($dir!="none") {
    $floating[] = array(
      "left" => $left,
      "right" => $left + $width,
      "top" => $top,
      "bottom" => $top + $height,
      "dir" => $dir
    );
  }
}

if (lgnCheckLogin($mysqli) && isset($_POST["page"], $_POST["layout"]) && $_POST["layout"]!="") {
  $page = $_POST["page"];
  $data = $_POST["data"];
  $links = $_POST["links"] ?? array();
  $refs = $_POST["refs"] ?? array();
  $options = $_POST["options"];

  $content = array();
  $id = null;
  if (isset($_POST["ID"]) && $_POST["ID"]!="") {
    $id = $_POST["ID"];
    $cntRow = cntGetRow($mysqli, $page, $id, $links, $refs);
    $content = $cntRow["erg"];
    if ($cntRow["err"]!="") {
      echo "<div>".$cntRow["err"]."</div>";
    }      
  }
  $res = $mysqli->query("select * from print_layouts where ID='".$_POST["layout"]."'");
  $layout = $res->fetch_assoc();
  $floating = array();

  echo "<div style='float: none; position: relative; display: inline-block; vertical-align: top; width: ".($layout["width"]/10)."mm; height: ".($layout["height"]/10)."mm; border: 1px solid #000000; background-color: #ffffff;'>";

  $res = $mysqli->query("select * from print_elements where key_layout_ID='".$layout["ID"]."' order by ord asc");
  while ($row = $res->fetch_assoc()) {
    $do_print = false;
    $cond = explode("|", $row["cond"]);
	if ($row["params"]=="") {
        $row["params"] = "{}";
      }
    $params = json_decode($row["params"], true);
    switch ($cond[0]) {
      case null:
      case "":
      case "0": //Print always
        $do_print = true;
        break;
      case "1": //Field has to be NOT null and not empty text
        if (sizeof($cond)>1 && (getContent($cond[1])!=null && getContent($cond[1], true)!=""))
          $do_print = true;
        break;
      case "2": //Field has to be null or empty text
        if (sizeof($cond)>1 && (getContent($cond[1])==null || getContent($cond[1], true)==""))
          $do_print = true;
        break;
      case "3": //Field has to be value (second parameter) or include value if is link
        if (sizeof($cond)>2 && ((array_key_exists($cond[1], $links) && in_array($cond[2], getContent($cond[1]))) || (getContent($cond[1])==$cond[2])))
          $do_print = true;
        break;
      case "4": //Field has to be NOT value (second parameter) or DONT include value if is link
        if (sizeof($cond)>2 && ((array_key_exists($cond[1], $links) && !in_array($cond[2], getContent($cond[1]))) && (getContent($cond[1])!=$cond[2])))
          $do_print = true;
        break;
      case "5": //Field has to be text (second parameter) or include text if it is link
        if (sizeof($cond)>2 && ((array_key_exists($cond[1], $links) && in_array($cond[2], getContent($cond[1], true))) || (getContent($cond[1], true)==$cond[2])))
          $do_print = true;
        break;
      case "6": //Field has to be NOT text (second parameter) or DONT include text if it is link
        if (sizeof($cond)>2 && ((array_key_exists($cond[1], $links) && !in_array($cond[2], getContent($cond[1], true))) && (getContent($cond[1], true)!=$cond[2])))
          $do_print = true;
        break;
    }
    if ($id===null) {//Demo mode
      $do_print = true;
    }
    $print_count = 0;
    if ($do_print) {
      $print_count = $params["repeat"] ?? 1;
    }
		
    while ($print_count>0) {
      $print_count--;
      $border = array();
      $border["top"] = isset($params["border-top"]) ? $params["border-top"] : (isset($params["border"]) ? $params["border"] : "0");
      $border["bottom"] = isset($params["border-bottom"]) ? $params["border-bottom"] : (isset($params["border"]) ? $params["border"] : "0");
      $border["left"] = isset($params["border-left"]) ? $params["border-left"] : (isset($params["border"]) ? $params["border"] : "0");
      $border["right"] = isset($params["border-right"]) ? $params["border-right"] : (isset($params["border"]) ? $params["border"] : "0");
      $border["color"] = isset($params["border-color"]) ? $params["border-color"] : "#000000";
      $border["string"] = "";
      if ($border["left"]!="0") {
        $border["string"].= "border-left: 1px solid ".$border["color"]."; ";
      }
      if ($border["right"]!="0") {
        $border["string"].= "border-right: 1px solid ".$border["color"]."; ";
      }
      if ($border["top"]!="0") {
        $border["string"].= "border-top: 1px solid ".$border["color"]."; ";
      }
      if ($border["bottom"]!="0") {
        $border["string"].= "border-bottom: 1px solid ".$border["color"]."; ";
      }
      
      $cnt = $row["content"];
      $fields = array();
      if (preg_match_all("/#([^#]+)#/", $cnt, $matches, PREG_SET_ORDER)) {
        foreach ($matches as $match) {
          $replace = "";
          $fields[] = $match[1];
          if (array_key_exists($match[1], $links)) {
            $replace = implode(", ", getContent($match[1], true, $id===null));
          } else if (array_key_exists($match[1], $data)) {
            $replace = getContent($match[1], true, $id===null);
          } else {
            foreach ($data as $key => $val) {
              if ($val["group"]==$match[1]) {
                $replace.=getContent($key, true, $id===null);
              }
            }
          }
          $cnt = str_replace("#".$match[1]."#", $replace, $cnt);
        }
      }
      
      $left = $row["posl"];
      $top = $row["post"];
      $width = $row["dimw"];
      if ($width == 0) {
        $width = 10;
      }
      $height = $row["dimh"];
      if ($height == 0) {
        $height = 10;
      }
      moveIfOverlap($floating, $left, $top, $width, $height, isset($params["float"]) ? $params["float"] : "none");
      
      switch ($row["type"]) {
        case "img":
          if (isset($params["aspect"]) && $params["aspect"]=="keep") {
            $imgsize = "max-width: ".$width."mm; max-height: ".$height."mm; width: auto; height: auto; ";
          }
          if (isset($params["aspect"]) && $params["aspect"]=="height") {
            $imgsize = "height: ".$height."mm; width: auto; ";
          } else {
            $imgsize = "width: ".$width."mm; height: ".$height."mm; ";
          }
          $path = $cnt;
          if (count($fields)) {
            $path = "uploads/".$page."/".$fields[0]."/".$cnt;
          }
          if (file_exists("../".$path)) {
            echo "<img src='".$path."' style='position: absolute; left: ".$left."mm; top: ".$top."mm; ".$imgsize."' />";
          }
          break;
        case "text":
          $rotate = "";
          if (isset($params["rotate"]) && $params["rotate"]=="1") {
            $rotate = "transform: rotate(-90deg); ";
            $left = "calc(".($left + ($height - $width)/2)."mm - ".$border["left"]."px); ";
            $top = "calc(".($top + ($width - $height)/2)."mm - ".$border["top"]."px); ";
          } else {
            $left.= "mm; ";
            $top.= "mm; ";
          }
          $font = "font-family: ".(isset($params["font"]) && $params["font"]=="narrow" ? "Calibri, Carlito, Arial Narrow, Liberation Sans Narrow, Arial, Liberation Sans; " : "Arial, Liberation Sans; ");
          $font.= "font-size: ".(isset($params["size"]) ? $params["size"] : $height)."mm; ";
          if (isset($params["weight"])) {
            $font.= "font-weight: ".$params["weight"]."; ";
          }
          if (isset($params["align"])) {
            $font.= "text-align: ".$params["align"]."; ";
          }
          echo "<span style='position: absolute; left: ".$left."top: ".$top."width: ".$width."mm; height: ".$height."mm; ".$font.$border["string"].$rotate."'>".$cnt."</span>";
          break;
      }
    }
  }
  echo "</div>";
}

?>