<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Stock Register Report</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.4.0/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<style>
body {
    margin: 0;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 12px;
    background-color: #fff;
}
@media print {
    thead { display: table-header-group; }
    tfoot { display: table-footer-group; }
    .button-row, .pagination { display: none; }
    .container {
        width: 100%;
        margin: 0;
        padding: 0;
        background: transparent;
    }
    .footer { display: none; } /* hide footer in print */
}
table {
    width: 100%;
    border-collapse: collapse;
    font-size: 11px;
    table-layout: fixed;
    word-wrap: break-word;
}
th, td {
    border: 1px dashed #999999 !important;
    padding: 5px;
    text-align: left;
}
th { background-color: #CCCCCC; }
.container {
    width: 95%;
    margin: 0 auto;
    padding: 20px 20px 50px 20px; /* increased bottom padding for PDF/Print */
    background-color: #f9f9f9;
}
.button-row {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 20px;
}
button {
    padding: 10px 20px;
    margin: 0 10px;
    font-size: 16px;
    cursor: pointer;
    background-color: #407cbb;
    color: white;
    border: none;
    border-radius: 5px;
    transition: background-color 0.3s ease;
}
button:hover { background-color: #0056b3; }
.footer {
    position: fixed;
    bottom: 10px;
    left: 0;
    right: 0;
    display: flex;
    justify-content: space-around;
    align-items: center;
    font-size: 14px;
    padding: 5px 15px;
    background: white;
    z-index: 9999;
}
.pagination {
    display: flex;
    justify-content: center;
    margin-top: 20px;
}
.pagination a {
    padding: 5px 10px;
    margin: 0 5px;
    border: 1px solid #ddd;
    text-decoration: none;
    color: #333;
}
.pagination a.active {
    background-color: #407cbb;
    color: white;
    border-color: #407cbb;
}
.no-results {
    text-align: center;
    padding: 20px;
    color: #666;
    font-style: italic;
}
</style>
</head>
<body>
<?php
include 'config.php';

$category_id = isset($_GET['category']) ? intval($_GET['category']) : 0;
$product_name = isset($_GET['product']) ? mysqli_real_escape_string($con, $_GET['product']) : '';
$color = isset($_GET['color']) ? mysqli_real_escape_string($con, $_GET['color']) : '';
$is_full = isset($_GET['full']); // load all rows for print/PDF
$records_per_page = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $records_per_page;

$query = "SELECT SQL_CALC_FOUND_ROWS s.*, c.category_name 
          FROM tbl_stock_items s
          LEFT JOIN tbl_categories c ON s.category = c.id
          WHERE 1=1";

if ($category_id > 0) $query .= " AND s.category = $category_id";
if (!empty($product_name)) $query .= " AND s.item_name LIKE '%$product_name%'";
if (!empty($color)) $query .= " AND s.product_color LIKE '%$color%'";

// if full, remove LIMIT for Print/PDF
$query .= $is_full ? " ORDER BY s.id DESC" : " ORDER BY s.id DESC LIMIT $offset, $records_per_page";
$result = mysqli_query($con, $query);
$total_rows = mysqli_fetch_assoc(mysqli_query($con, "SELECT FOUND_ROWS() AS total"))['total'];
$total_pages = ceil($total_rows / $records_per_page);
?>

<div class="button-row">
    <button onclick="window.location.href='?full=1<?php 
        echo $category_id>0?'&category='.$category_id:''; 
        echo !empty($product_name)?'&product='.$product_name:''; 
        echo !empty($color)?'&color='.$color:''; 
    ?>&action=print'">Print</button>

    <button onclick="window.location.href='?full=1<?php 
        echo $category_id>0?'&category='.$category_id:''; 
        echo !empty($product_name)?'&product='.$product_name:''; 
        echo !empty($color)?'&color='.$color:''; 
    ?>&action=pdf'">Download</button>

    <button onclick="window.location.href='addstock.php'">Back</button>
</div>

<div id="invoice" class="container">
    <div style="text-align:left; margin-top:5px; font-weight:bold; font-size:20px; display:flex; justify-content:space-between; align-items:center;">
        <strong style="color:red;"><u>PIPSCART</u></strong>
        <small style="font-size:13px;">Date: <?php echo date('d/m/Y'); ?></small>
    </div>

    <div style="margin-top:5px; margin-bottom:5px;">
        <h3>Stock Register Report</h3>
        <?php if($category_id>0): 
            $cat_name = mysqli_fetch_assoc(mysqli_query($con,"SELECT category_name FROM tbl_categories WHERE id=$category_id"))['category_name']; ?>
            <p>Category: <?=htmlspecialchars($cat_name)?></p>
        <?php endif; ?>
        <?php if(!empty($product_name)): ?><p>Product: <?=htmlspecialchars($product_name)?></p><?php endif; ?>
        <?php if(!empty($color)): ?><p>Color: <?=htmlspecialchars($color)?></p><?php endif; ?>
    </div>

    <table>
        <thead>
            <tr style="text-align:center;">
                <th style="width:6%">I.Code</th>
                <th style="width:12%">Category</th>
                <th style="width:15%">Item Name</th>
                <th style="width:20%">Description</th>
                <th style="width:8%">P.Code</th>
                <th style="width:7%">Stock</th>
                <th style="width:8%">P.Color</th>
                <th style="width:8%">Price</th>
                <th style="width:8%">Tax%</th>
                <th style="width:8%">Net Amt</th>
            </tr>
        </thead>
        <tbody>
            <?php if(mysqli_num_rows($result)>0): 
                while($row=mysqli_fetch_assoc($result)): ?>
                <tr style="text-align:center;">
                    <td><?=htmlspecialchars($row['id'])?></td>
                    <td><?=htmlspecialchars($row['category_name'])?></td>
                    <td><?=htmlspecialchars($row['item_name'])?></td>
                    <td><?=htmlspecialchars($row['description'])?></td>
                    <td><?=htmlspecialchars($row['p_code'])?></td>
                    <td><?=htmlspecialchars($row['stock'])?></td>
                    <td><?=htmlspecialchars($row['product_color'])?></td>
                    <td><?=htmlspecialchars($row['price'])?></td>
                    <td><?=htmlspecialchars($row['tax'])?></td>
                    <td><?=htmlspecialchars($row['net_amt'])?></td>
                </tr>
            <?php endwhile; else: ?>
                <tr><td colspan="10" class="no-results">No records found</td></tr>
            <?php endif; ?>
        </tbody>
    </table>
<style>
    @media print{
        .footer{
            display:none;
        }
    }
</style>
    <?php if($total_pages>1 && !$is_full): ?>
    <div class="pagination">
        <?php if($page>1): ?>
            <a href="?page=1<?php echo $category_id>0?'&category='.$category_id:''; ?><?php echo !empty($product_name)?'&product='.$product_name:''; ?><?php echo !empty($color)?'&color='.$color:''; ?>">First</a>
            <a href="?page=<?=$page-1?><?php echo $category_id>0?'&category='.$category_id:''; ?><?php echo !empty($product_name)?'&product='.$product_name:''; ?><?php echo !empty($color)?'&color='.$color:''; ?>">Prev</a>
        <?php endif; ?>
        <?php
        $start_page=max(1,$page-2);
        $end_page=min($total_pages,$page+2);
        for($i=$start_page;$i<=$end_page;$i++): ?>
            <a <?=$i==$page?'class="active"':''?> href="?page=<?=$i?><?php echo $category_id>0?'&category='.$category_id:''; ?><?php echo !empty($product_name)?'&product='.$product_name:''; ?><?php echo !empty($color)?'&color='.$color:''; ?>"><?=$i?></a>
        <?php endfor; ?>
        <?php if($page<$total_pages): ?>
            <a href="?page=<?=$page+1?><?php echo $category_id>0?'&category='.$category_id:''; ?><?php echo !empty($product_name)?'&product='.$product_name:''; ?><?php echo !empty($color)?'&color='.$color:''; ?>">Next</a>
            <a href="?page=<?=$total_pages?><?php echo $category_id>0?'&category='.$category_id:''; ?><?php echo !empty($product_name)?'&product='.$product_name:''; ?><?php echo !empty($color)?'&color='.$color:''; ?>">Last</a>
        <?php endif; ?>
    </div>
    <?php endif; ?>

    <div class="footer">
        <small>IP: <?=$_SERVER['REMOTE_ADDR']?></small>
        <small>Page <?=$page?> of <?=$total_pages?></small>
        <small>By PROGRAMERS.in</small>
    </div>
</div>

<script>
const params = new URLSearchParams(window.location.search);
const action = params.get('action');

if(action==='print'){
    window.print();
}

if(action==='pdf'){
    window.onload = function(){
        const element = document.getElementById('invoice');
        const footer = element.querySelector('.footer');
        footer.style.display = 'none'; // hide footer in PDF

        const pdf = new jspdf.jsPDF('p','mm','a4');
        const pageWidth = pdf.internal.pageSize.getWidth();
        const margin = 20;

        html2canvas(element, {
            scale:2,
            useCORS:true,
            scrollX:0,
            scrollY:0,
            windowWidth:document.body.scrollWidth
        }).then(canvas=>{
            const imgData = canvas.toDataURL('image/png');
            const imgWidth = pageWidth - (margin*2);
            const imgHeight = (canvas.height * imgWidth) / canvas.width;
            let heightLeft = imgHeight;
            let position = 10;

            pdf.addImage(imgData,'PNG',margin,position,imgWidth,imgHeight);
            heightLeft -= pdf.internal.pageSize.getHeight();

            while(heightLeft>0){
                pdf.addPage();
                position = 0;
                pdf.addImage(imgData,'PNG',margin,position - heightLeft,imgWidth,imgHeight);
                heightLeft -= pdf.internal.pageSize.getHeight();
            }

            pdf.save('Stock_Report.pdf');
            footer.style.display = ''; // restore footer
            window.history.replaceState({},document.title,window.location.pathname);
        });
    };
}
</script>
</body>
</html>
