<?php
require_once('includes/load.php');
require_once('includes/database.php');

$page_title = 'product';
page_require_level(3);

include_once('layouts/header.php');

$db = new MySqli_DB();

$records_per_page = 100;
$current_page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($current_page - 1) * $records_per_page;

$search_query = isset($_GET['search_query']) ? $db->escape($_GET['search_query']) : '';
$search_option = isset($_GET['search_option']) ? $db->escape($_GET['search_option']) : '';

$where_clause = '';
if (!empty($search_query) && !empty($search_option)) {
    $where_clause = "WHERE $search_option LIKE '%$search_query%'";
}

$sql = "SELECT * FROM data $where_clause LIMIT $offset, $records_per_page";
$result = $db->query($sql);

$total_records = $db->num_rows($db->query("SELECT COUNT(*) AS total FROM data $where_clause"));
$total_pages = ceil($total_records / $records_per_page);
?>

<h2>View Data</h2>

<div class="float-right">
    <a href="#" id="exportCSV" class="btn btn-success">Export</a>
</div>

<div class="mb-3">
    <form class="form-inline" method="get">
        <div class="form-group mr-2">
            <input type="text" class="form-control" name="search_query" placeholder="Search...">
        </div>
        <div class="form-group">
            <select class="form-control" name="search_option">
                <option value="part_number">Search by Part Number</option>
                <option value="description">Search by Description</option>
            </select>
        </div>
        <button type="submit" class="btn btn-primary ml-2">Search</button>
    </form>
</div>

<table class="table table-bordered">
    <thead>
        <tr>
            <th>ID</th>
            <th>Part Number</th>
            <th>Description</th>
            <th>Color</th>
            <th>Categories</th>
            <th>Unit Price</th>
            <th>Unit Measurements</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
        <?php while ($row = $db->fetch_assoc($result)) : ?>
            <tr>
                <td><?php echo $row['id']; ?></td>
                <td><?php echo htmlspecialchars($row['part_number']); ?></td>
                <td><?php echo htmlspecialchars($row['description']); ?></td>
                <td><?php echo htmlspecialchars($row['color']); ?></td>
                <td><?php echo htmlspecialchars($row['categories']); ?></td>
                <td><?php echo $row['unit_price']; ?></td>
                <td><?php echo htmlspecialchars($row['unit_measurements']); ?></td>
                <td>
                    <a href="edit_data.php?id=<?php echo $row['id']; ?>" class="btn btn-info btn-xs" title="Edit" data-toggle="tooltip">
                        <span class="glyphicon glyphicon-edit"></span>
                    </a>
                    <a href="delete_data.php?id=<?php echo $row['id']; ?>" class="btn btn-danger btn-xs" title="Delete" data-toggle="tooltip">
                        <span class="glyphicon glyphicon-trash"></span>
                    </a>
                </td>
            </tr>
        <?php endwhile; ?>
    </tbody>
</table>

<nav aria-label="Page navigation">
    <ul class="pagination justify-content-center">
        <?php if ($current_page > 1) : ?>
            <li class="page-item">
                <a class="page-link" href="?page=<?php echo $current_page - 1; ?>" aria-label="Previous">
                    <span aria-hidden="true">&laquo;</span>
                    <span class="sr-only">Previous</span>
                </a>
            </li>
        <?php endif; ?>

        <?php for ($i = 1; $i <= $total_pages; $i++) : ?>
            <li class="page-item <?php echo ($i == $current_page) ? 'active' : ''; ?>">
                <a class="page-link" href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
            </li>
        <?php endfor; ?>

        <?php if ($current_page < $total_pages) : ?>
            <li class="page-item">
                <a class="page-link" href="?page=<?php echo $current_page + 1; ?>" aria-label="Next">
                    <span aria-hidden="true">&raquo;</span>
                    <span class="sr-only">Next</span>
                </a>
            </li>
        <?php endif; ?>
    </ul>
</nav>

<script>
document.addEventListener('DOMContentLoaded', function () {
    document.getElementById('exportCSV').addEventListener('click', function () {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'export_csv.php', true);
        xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        xhr.responseType = 'blob';
        
        xhr.onreadystatechange = function () {
            if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
                var blob = xhr.response;
                var link = document.createElement('a');
                link.href = window.URL.createObjectURL(blob);
                link.download = 'export_data.csv';
                link.style.display = 'none';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }
        };
        
        xhr.send();
    });
});
</script>

<?php include_once('layouts/footer.php'); ?>
