<?php
require_once __DIR__ . '/../config/user_functions.php';

function smp_get_printer_config(): array {
    $file = __DIR__ . '/../config/printer_settings.json';
    $cfg = [
        "selected_printer"=>"",
        "labels_printer"=>"",
        "print_after_generation"=>false,
        "label_width_in"=>4,
        "label_height_in"=>2,
        "label_options"=>[
            "grower"=>true,"variety"=>true,"received"=>true,"lot"=>true,"quantity"=>true
        ]
    ];
    if(file_exists($file)){
        $d=json_decode(file_get_contents($file),true);
        if(is_array($d)) $cfg=array_merge($cfg,$d);
    }
    return $cfg;
}

function smp_generate_bin_labels_zpl(array $row,int $count=0): string {
    $cfg=smp_get_printer_config();
    $opts=$cfg["label_options"];
    $g=$row["grower"]??''; $v=$row["variety"]??''; $d=$row["date"]??''; $l=$row["lot"]??''; 
    $q=(int)($row["quantity"]??1); $id=(int)($row["id"]??0);
    $c=$count>0?$count:$q; if($c<=0)$c=1;

    $W=(int)round($cfg["label_width_in"]*203);
    $H=(int)round($cfg["label_height_in"]*203);

    $qr=json_encode([
        "type"=>"BIN","id"=>$id,"grower"=>$g,"variety"=>$v,
        "received"=>$d,"lot"=>$l,"quantity"=>$q
    ], JSON_UNESCAPED_SLASHES);
    $qr=str_replace(["^","~"],[" "," "],$qr);

    $z="";
    for($i=0;$i<$c;$i++){
        $z.="^XA
^PW{$W}
^LL{$H}
";
        $y=40;
        if($opts["grower"]){$z.="^FO40,{$y}^A0N,40,40^FDGROWER: ".strtoupper($g)."^FS
";$y+=50;}
        if($opts["variety"]){$z.="^FO40,{$y}^A0N,40,40^FDVARIETY: ".strtoupper($v)."^FS
";$y+=50;}
        if($opts["received"]){$z.="^FO40,{$y}^A0N,35,35^FDRECEIVED: {$d}^FS
";$y+=50;}
        if($opts["quantity"]){$z.="^FO40,{$y}^A0N,35,35^FDBINS IN LOT: {$q}^FS
";$y+=50;}
        if($opts["lot"]&&$l!==""){$z.="^FO40,{$y}^A0N,35,35^FDLOT: ".strtoupper($l)."^FS
";}
        $z.="^FO".($W-300).",40^BQN,2,10
^FDLA,{$qr}^FS
";
        if($id>0){
            $z.="^FO40,".($H-120)."^BCN,80,Y,N,N
^FD{$id}^FS
";
        }
        $z.="^XZ
";
    }
    return $z;
}

function smp_print_zpl_for_bin(array $row,int $count=0): bool {
    $cfg=smp_get_printer_config();
    $printer=$cfg["labels_printer"]??"";
    if(!$printer) return false;

    $zpl=smp_generate_bin_labels_zpl($row,$count);

    @file_put_contents("tcp://{$printer}:9100",$zpl);

    $tmp=tempnam(sys_get_temp_dir(),"zpl");
    file_put_contents($tmp,$zpl);

    $ps='Get-Content -Path "' . $tmp . '" | Out-Printer -Name "' . $printer . '"';
    $cmd='powershell -command "' . $ps . '"';
    @shell_exec($cmd);

    return true;
}
?>
