<?php
session_start();
require_once('includes/vendor-security.php');
include_once('../includes/config.php');

$vendorId = $_SESSION['vendor_id'];
$filterPid = isset($_GET['pid']) ? intval($_GET['pid']) : 0;
$filterTitle = "All Inventory Logs";

// Verify ownership if filtering by product
if ($filterPid > 0) {
    $checkOwner = mysqli_query($con, "SELECT productName FROM products WHERE id='$filterPid' AND vendor_id='$vendorId'");
    if (mysqli_num_rows($checkOwner) > 0) {
        $row = mysqli_fetch_array($checkOwner);
        $filterTitle = "Inventory Logs: " . $row['productName'];
        $query = "SELECT l.*, p.productName, p.sku 
                  FROM inventory_logs l 
                  JOIN products p ON l.product_id = p.id 
                  WHERE l.vendor_id='$vendorId' AND l.product_id='$filterPid' 
                  ORDER BY l.created_at DESC";
    } else {
        $_SESSION['error'] = "Product not found or access denied.";
        header("Location: inventory.php");
        exit;
    }
} else {
    $query = "SELECT l.*, p.productName, p.sku 
              FROM inventory_logs l 
              JOIN products p ON l.product_id = p.id 
              WHERE l.vendor_id='$vendorId' 
              ORDER BY l.created_at DESC";
}

$result = mysqli_query($con, $query);
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <title>Inventory History - Vendor Portal</title>
    <link href="https://cdn.jsdelivr.net/npm/simple-datatables@latest/dist/style.css" rel="stylesheet" />
    <link href="../__admin__/css/styles.css" rel="stylesheet" />
    <link href="../__admin__/css/admin-professional.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/js/all.min.js"></script>
</head>

<body class="sb-nav-fixed">
    <?php include_once('includes/header.php'); ?>
    <div id="layoutSidenav">
        <?php include_once('includes/sidebar.php'); ?>
        <div id="layoutSidenav_content">
            <main>
                <div class="container-fluid px-4">
                    <div class="page-header mt-4">
                        <div>
                            <h1><i class="fas fa-history me-2"></i> Inventory History</h1>
                            <p>View stock changes and adjustments.</p>
                        </div>
                        <?php if ($filterPid > 0): ?>
                            <div>
                                <a href="inventory.php" class="btn btn-secondary"><i class="fas fa-arrow-left me-2"></i>Back
                                    to Inventory</a>
                            </div>
                        <?php endif; ?>
                    </div>

                    <div class="table-card">
                        <div class="card-header">
                            <h5 class="mb-0"><i class="fas fa-list me-2"></i>
                                <?php echo htmlentities($filterTitle); ?>
                            </h5>
                        </div>
                        <div class="card-body">
                            <table id="datatablesSimple">
                                <thead>
                                    <tr>
                                        <th>Date/Time</th>
                                        <?php if ($filterPid == 0): ?>
                                            <th>Product</th>
                                        <?php endif; ?>
                                        <th>Reason</th>
                                        <th>Change</th>
                                        <th>Previous</th>
                                        <th>New Stock</th>
                                        <th>User</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php while ($row = mysqli_fetch_array($result)) {
                                        $adj = intval($row['adjustment']);
                                        $adjClass = ($adj >= 0) ? 'text-success' : 'text-danger';
                                        $adjSign = ($adj >= 0) ? '+' : '';
                                        ?>
                                        <tr>
                                            <td>
                                                <?php echo date('M d, Y h:i A', strtotime($row['created_at'])); ?>
                                            </td>
                                            <?php if ($filterPid == 0): ?>
                                                <td>
                                                    <strong>
                                                        <?php echo htmlentities($row['productName']); ?>
                                                    </strong><br>
                                                    <small class="text-muted">
                                                        <?php echo htmlentities($row['sku']); ?>
                                                    </small>
                                                </td>
                                            <?php endif; ?>
                                            <td>
                                                <?php echo htmlentities($row['reason']); ?>
                                            </td>
                                            <td class="<?php echo $adjClass; ?> fw-bold">
                                                <?php echo $adjSign . $adj; ?>
                                            </td>
                                            <td>
                                                <?php echo $row['previous_stock']; ?>
                                            </td>
                                            <td><span class="badge bg-secondary">
                                                    <?php echo $row['current_stock']; ?>
                                                </span></td>
                                            <td>
                                                <?php echo ($row['created_by']) ? 'Manual (User #' . $row['created_by'] . ')' : 'System'; ?>
                                            </td>
                                        </tr>
                                    <?php } ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </main>
            <?php include_once('includes/footer.php'); ?>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="../__admin__/js/scripts.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/simple-datatables@latest"></script>
    <script src="../__admin__/js/datatables-simple-demo.js"></script>
</body>

</html>