<?php include 'header.php'; ?>
<h3>概要</h3>
<?php if (!empty($clearanceData['clearance']['total_sold']) && !empty($clearanceData['clearance']['clearance_amount'])): ?>
    <span>销售量: <?php echo $clearanceData['clearance']['total_sold']; ?></span>
    <span>总金额: <?php echo $clearanceData['clearance']['clearance_amount']; ?></span>
<?php else: ?>
    <p>暂无结算商品</p>
<?php endif; ?>

<h3>待结算商品</h3>
<table>
    <thead>
        <tr>
            <th>品名</th>
            <th>总量</th>
            <th>存量</th>
            <th>单价</th>
            <th>销售</th>
            <th>退回</th>
        </tr>
    </thead>
    <tbody>
        <?php
        $hasItems = false; // Flag to check if any items are displayed
        foreach ($clearanceData['orders'] as $order):
            // Check if Sold or Returned is non-zero
            if ($order['sold'] != 0 || $order['returned'] != 0):
                $hasItems = true;
        ?>
        <tr>
            <td><?php echo htmlspecialchars($order['item_name']); ?></td>
            <td><?php echo $order['quantity']; ?></td>
            <td><?php echo $order['stock']; ?></td>
            <td><?php echo $order['unit_price']; ?></td>
            <td><?php echo $order['sold']; ?></td>
            <td><?php echo $order['returned']; ?></td>
        </tr>
        <?php
            endif;
        endforeach;

        // If no items were displayed, show a message
        if (!$hasItems):
        ?>
        <tr>
            <td colspan="6">无商品结算</td>
        </tr>
        <?php endif; ?>
    </tbody>
</table>


<h1>已结算历史账单</h1>

<?php if ($_SESSION['user_id'] == 1 && !empty($users)): ?>
    <form action="index.php" method="get">
        <input type="hidden" name="view" value="clearance">
        <select name="user_id" onchange="this.form.submit()">
            <option value="">Select a user</option>
            <?php foreach ($users as $user): ?>
                <option value="<?php echo $user['id']; ?>" <?php echo isset($selectedUserId) && $selectedUserId == $user['id'] ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($user['username']); ?>
                </option>
            <?php endforeach; ?>
        </select>
    </form>
<?php endif; ?>

<table>
    <thead>
        <tr>
            <th>时间</th>
            <th>销量</th>
            <th>退回</th>
            <th>金额</th>
            <th>详细</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($clearanceHistory as $history): ?>
        <?php
        $sold_items = json_decode($history['sold_items'], true);
        foreach ($sold_items as &$item) {
            $item['item_name'] = preg_replace('/u([0-9a-fA-F]{4})/', '\\u$1', $item['item_name']);
            $item['item_name'] = json_decode('"' . $item['item_name'] . '"');
        }
        unset($item); // Break the reference
        $data_items = htmlspecialchars(json_encode($sold_items, JSON_UNESCAPED_UNICODE));
        ?>
        <tr>
            <td><?php echo $history['created_at']; ?></td>
            <td><?php echo (int)$history['total_sold']; ?></td>
            <td>
                <?php
                $total_returned = 0;
                foreach ($sold_items as $item) {
                    $total_returned += (int)$item['returned']; // Sum all returned items
                }
                echo $total_returned;
                ?>
            </td>
            <td><?php echo $history['clearance_amount']; ?></td>
            <td>
                <a href="#" class="details-link" data-items='<?php echo $data_items; ?>'>查询明细</a>
            </td>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>

<!-- Modal for Details -->
<div id="myModal" class="modal">
    <div class="modal-content">
        <span class="close">&times;</span>
        <div id="modal-body"></div>
    </div>
</div>

<!-- JavaScript -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Modal handling
    var modal = document.getElementById('myModal');
    var span = document.querySelector(".close");

    span.onclick = function() {
        modal.style.display = "none";
    }

    window.onclick = function(event) {
        if (event.target == modal) {
            modal.style.display = "none";
        }
    }

    document.querySelectorAll('.details-link').forEach(function(link) {
        link.onclick = function(event) {
            event.preventDefault();
            var soldItems = JSON.parse(this.dataset.items);
            var modalBody = document.getElementById('modal-body');
            modalBody.innerHTML = ''; // Clear existing content
            var list = document.createElement('ul');
            soldItems.forEach(function(item) {
                var listItem = document.createElement('li');
                var parts = [];
                if (item.sold != 0) {
                    parts.push(`销售: ${item.sold}`);
                }
                if (item.returned != 0) {
                    parts.push(`退回: ${item.returned}`);
                }
                var info = parts.join(', ');
                listItem.textContent = `${item.item_name}¥${item.unit_price}`;
                if (info) {
                    listItem.textContent += ` ----- ${info}`;
                }
                list.appendChild(listItem);
            });
            modalBody.appendChild(list);
            modal.style.display = "block";
        }
    });
});
</script>

<style>
/* Modal styles */
.modal {
  display: none;
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgba(0,0,0,0.4);
}

.modal-content {
  background-color: #fefefe;
  margin: 10% auto;
  padding: 20px;
  border: 1px solid #888;
  width: 80%;
}

.close {
  color: #aaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: black;
  text-decoration: none;
  cursor: pointer;
}

table tbody tr td:nth-child(2) {
    color: red;
    text-align: center;
    font-weight: bold;
}
</style>
<br><br>
<?php include 'footer.php'; ?>