<?php
ob_start();
require("includes/check_auth_user.php");
require("includes/dbconnect.php");
include('includes/function.php');


$admin = $_SESSION["admin_" . $dbname];
$zdb = $_SESSION["zdbyear_" . $dbname];
$zroot = $_SESSION['zdir'];

$zyear = right($zdb, 4);
$mfrdate = getzdates($zyear, 'S');
$mtodate = getzdates($zyear, 'E');

$myyear = $_SESSION[$myyear];
mysqli_select_db($conn, $zdb);

/* ✅ GET ITEMS FROM FORM */
$items = json_decode($_POST['label_items'], true);

$labels = [];

/* ✅ EXPAND ITEMS BASED ON QTY */
foreach ($items as $item) {

    $name = $item['name'];
    $mrp  = $item['mrp'];
    $qty  = $item['qty'];

    for ($i = 0; $i < $qty; $i++) {
        $labels[] = [
            'name' => $name,
            'mrp'  => $mrp
        ];
    }
}

/* ✅ TOTAL LABELS */
$total_labels = count($labels);
$per_page = 48;
$total_pages = ceil($total_labels / $per_page);

$index = 0;



include("includes/linkshead.php");
?>



<style>
@page {
    size: A4;
    margin: 0;
}

body {
    margin: 0;
}

/* EACH PAGE */
.sheet {
    width: 210mm;
    height: 297mm;

    display: grid;
    grid-template-columns: repeat(4, 1fr);
    grid-template-rows: repeat(12, 1fr);

    gap: 2.5mm;
    /* padding: 5mm; */
    /* move all labels slightly left */
    padding: 5mm 5mm 5mm 3mm;  
    /* top right bottom left */
    box-sizing: border-box;
    

    page-break-after: always;
}

/* LABEL */
.label {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;

    font-size: 14px;
    color: black;
    /* DEBUG (REMOVE LATER) */
    /* border: 1px solid red; */
}

.title {
    font-weight: bold;
}
</style>
</head>

<body>

<?php
for ($p = 0; $p < $total_pages; $p++) {

    echo '<div class="sheet">';

    for ($i = 0; $i < $per_page; $i++) {

        if (!isset($labels[$index])) break;

        $row = $labels[$index];

        echo '<div class="label">
                <div class="title">'.$row['name'].'</div>
                <div class="title">M.R.P. '.number_format($row['mrp'],2).'</div>
              </div>';

        $index++;
    }

    echo '</div>';
}
?>

<script>
window.print();
</script>

</body>
</html>