<?php
session_start();
if (!isset($_SESSION['username'])) {
    echo "<script>window.top.location.href='index.php';</script>"; // Redirect parent window to login page
    exit();
}

include 'connect.php';

$search = isset($_POST['search']) ? mysqli_real_escape_string($conn, $_POST['search']) : '';
$page = isset($_POST['page']) ? (int)$_POST['page'] : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

$sql = "SELECT * FROM products_table WHERE pr_Name LIKE '%$search%' LIMIT $limit OFFSET $offset";
$result = mysqli_query($conn, $sql);

$serialNo = $offset + 1;

if ($result) {
    while ($row = mysqli_fetch_assoc($result)) {
        echo '<tr>
            <th scope="row">' . $serialNo++ . '</th>
            <td>' . $row['pr_Name'] . '</td>
            <td>' . $row['product_number'] . '</td>
            <td>' . number_format($row['pr_Price']) . '</td>
            <td>' . number_format($row['pr_Cost']) . '</td>
            <td>' . $row['qty_Onhand'] . '</td>
            <td>
                <!-- Update Button -->
                <a href="updateproduct.php?updateid=' . $row['product_id'] . '" class="btn btn-primary text-light">
                    <i class="fas fa-edit"></i>
                </a>

                <!-- View Button -->
                <a href="viewproduct.php?viewid=' . $row['product_id'] . '" class="btn btn-info text-light">
                    <i class="fas fa-eye"></i>
                </a>
            </td>
        </tr>';
    }
} else {
    echo '<tr><td colspan="7">No products found.</td></tr>';
}
?>
