<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();

$pageTitle = 'Inventory Valuation';

if (file_exists(__DIR__ . '/../../includes/permission_check.php')) {
    require_once __DIR__ . '/../../includes/permission_check.php';
    if (function_exists('require_permission')) {
        require_permission($pdo, 'stock_valuation_report', 'view');
    }
}

if (!function_exists('h')) {
    function h($v): string { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
}
if (!function_exists('money_fmt')) {
    function money_fmt($v): string { return number_format((float)$v, 2); }
}
if (!function_exists('qty_fmt')) {
    function qty_fmt($v): string { return number_format((float)$v, 4); }
}
if (!function_exists('iv_table_exists')) {
    function iv_table_exists(PDO $pdo, string $table): bool {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name=:t");
        $stmt->execute([':t' => $table]);
        return (int)$stmt->fetchColumn() > 0;
    }
}
if (!function_exists('iv_col_exists')) {
    function iv_col_exists(PDO $pdo, string $table, string $column): bool {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name=:t AND column_name=:c");
        $stmt->execute([':t' => $table, ':c' => $column]);
        return (int)$stmt->fetchColumn() > 0;
    }
}

$errors = [];

try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS store_locations (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        location_code VARCHAR(50) NULL,
        location_name VARCHAR(150) NOT NULL,
        location_type ENUM('main_store','bar','restaurant','curio','kitchen','housekeeping','maintenance','other') NOT NULL DEFAULT 'main_store',
        is_pos_location TINYINT(1) NOT NULL DEFAULT 0,
        allow_room_charge TINYINT(1) NOT NULL DEFAULT 1,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        notes TEXT NULL,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_store_location_code (location_code)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS inventory_item_categories (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        category_name VARCHAR(120) NOT NULL,
        category_type ENUM('stock','food','bar','curio','consumable','service','other') NOT NULL DEFAULT 'stock',
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_inventory_category_name (category_name)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS inventory_units (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        unit_code VARCHAR(30) NOT NULL,
        unit_name VARCHAR(80) NOT NULL,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        UNIQUE KEY uq_inventory_unit_code (unit_code)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS inventory_items (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        item_code VARCHAR(60) NULL,
        item_name VARCHAR(180) NOT NULL,
        category_id INT UNSIGNED NULL,
        unit_id INT UNSIGNED NULL,
        supplier_id INT UNSIGNED NULL,
        item_type ENUM('stock','food','bar','curio','consumable','service','recipe','other') NOT NULL DEFAULT 'stock',
        barcode VARCHAR(100) NULL,
        description TEXT NULL,
        cost_price DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        avg_cost DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        selling_price DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        tax_rate DECIMAL(7,4) NOT NULL DEFAULT 0.0000,
        reorder_level DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        reorder_qty DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        is_stock_item TINYINT(1) NOT NULL DEFAULT 1,
        is_pos_item TINYINT(1) NOT NULL DEFAULT 0,
        allow_room_charge TINYINT(1) NOT NULL DEFAULT 1,
        track_expiry TINYINT(1) NOT NULL DEFAULT 0,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY uq_inventory_item_code (item_code),
        INDEX idx_inventory_item_name (item_name)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $pdo->exec("CREATE TABLE IF NOT EXISTS stock_movements (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
        item_id INT UNSIGNED NOT NULL,
        store_id INT UNSIGNED NOT NULL,
        movement_type ENUM('OPENING','GRN','ISSUE','SALE','TRANSFER_IN','TRANSFER_OUT','ADJUSTMENT_IN','ADJUSTMENT_OUT','WASTAGE','RETURN') NOT NULL,
        qty_in DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        qty_out DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        unit_cost DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        total_cost DECIMAL(14,4) NOT NULL DEFAULT 0.0000,
        reference_type VARCHAR(60) NULL,
        reference_id BIGINT UNSIGNED NULL,
        notes TEXT NULL,
        movement_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_stock_item_store (item_id, store_id),
        INDEX idx_stock_movement_date (movement_date),
        INDEX idx_stock_reference (reference_type, reference_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
} catch (Throwable $e) {
    $errors[] = 'Could not prepare inventory valuation tables: ' . $e->getMessage();
}

$valuationDate = trim((string)($_GET['valuation_date'] ?? date('Y-m-d')));
$storeId = (int)($_GET['store_id'] ?? 0);
$categoryId = (int)($_GET['category_id'] ?? 0);
$itemType = trim((string)($_GET['item_type'] ?? ''));
$showZero = (int)($_GET['show_zero'] ?? 0);
$search = trim((string)($_GET['q'] ?? ''));

if (strtotime($valuationDate) === false) {
    $valuationDate = date('Y-m-d');
}

$stores = [];
$categories = [];
$rows = [];
$byStore = [];
$byCategory = [];

$summary = [
    'items' => 0,
    'qty_total' => 0,
    'stock_value' => 0,
    'retail_value' => 0,
    'potential_margin' => 0,
    'negative_items' => 0,
    'zero_cost_items' => 0,
];

try {
    $stores = $pdo->query("SELECT id, location_name FROM store_locations WHERE is_active=1 ORDER BY location_name ASC")->fetchAll(PDO::FETCH_ASSOC);
    $categories = $pdo->query("SELECT id, category_name FROM inventory_item_categories WHERE is_active=1 ORDER BY category_name ASC")->fetchAll(PDO::FETCH_ASSOC);

    $where = "ii.is_active=1 AND ii.is_stock_item=1";
    $params = [':valuation_date' => $valuationDate];

    if ($storeId > 0) {
        $where .= " AND sl.id=:store_id";
        $params[':store_id'] = $storeId;
    }

    if ($categoryId > 0) {
        $where .= " AND ii.category_id=:category_id";
        $params[':category_id'] = $categoryId;
    }

    if ($itemType !== '') {
        $where .= " AND ii.item_type=:item_type";
        $params[':item_type'] = $itemType;
    }

    if ($search !== '') {
        $where .= " AND (ii.item_name LIKE :q OR ii.item_code LIKE :q OR sl.location_name LIKE :q OR c.category_name LIKE :q)";
        $params[':q'] = '%' . $search . '%';
    }

    /*
     * The valuation is based on all movements up to valuation_date.
     * Cost basis = avg_cost if available, else cost_price.
     */
    $stmt = $pdo->prepare("
        SELECT
            ii.id AS item_id,
            ii.item_code,
            ii.item_name,
            ii.item_type,
            ii.avg_cost,
            ii.cost_price,
            ii.selling_price,
            ii.reorder_level,
            COALESCE(NULLIF(ii.avg_cost,0), ii.cost_price, 0) AS valuation_cost,
            u.unit_code,
            c.category_name,
            sl.id AS store_id,
            sl.location_name,
            COALESCE(SUM(sm.qty_in - sm.qty_out),0) AS qty_on_hand,
            COALESCE(SUM(CASE WHEN sm.movement_type='GRN' THEN sm.qty_in ELSE 0 END),0) AS grn_qty,
            COALESCE(SUM(CASE WHEN sm.movement_type='SALE' THEN sm.qty_out ELSE 0 END),0) AS sales_qty,
            COALESCE(SUM(CASE WHEN sm.movement_type IN ('ADJUSTMENT_OUT','WASTAGE') THEN sm.qty_out ELSE 0 END),0) AS shrink_qty
        FROM inventory_items ii
        CROSS JOIN store_locations sl
        LEFT JOIN stock_movements sm
            ON sm.item_id=ii.id
           AND sm.store_id=sl.id
           AND DATE(sm.movement_date) <= :valuation_date
        LEFT JOIN inventory_units u ON u.id=ii.unit_id
        LEFT JOIN inventory_item_categories c ON c.id=ii.category_id
        WHERE {$where}
        GROUP BY
            ii.id, ii.item_code, ii.item_name, ii.item_type, ii.avg_cost, ii.cost_price,
            ii.selling_price, ii.reorder_level, u.unit_code, c.category_name, sl.id, sl.location_name
        HAVING " . ($showZero ? "1=1" : "qty_on_hand <> 0") . "
        ORDER BY sl.location_name ASC, c.category_name ASC, ii.item_name ASC
        LIMIT 5000
    ");
    $stmt->execute($params);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($rows as &$r) {
        $qty = (float)$r['qty_on_hand'];
        $cost = (float)$r['valuation_cost'];
        $selling = (float)$r['selling_price'];
        $stockValue = $qty * $cost;
        $retailValue = $qty * $selling;
        $margin = $retailValue - $stockValue;

        $r['stock_value'] = $stockValue;
        $r['retail_value'] = $retailValue;
        $r['potential_margin'] = $margin;
        $r['stock_status'] = $qty < 0 ? 'negative' : ($qty <= (float)$r['reorder_level'] ? 'low' : 'ok');

        $summary['items']++;
        $summary['qty_total'] += $qty;
        $summary['stock_value'] += $stockValue;
        $summary['retail_value'] += $retailValue;
        $summary['potential_margin'] += $margin;

        if ($qty < 0) $summary['negative_items']++;
        if ($cost <= 0 && abs($qty) > 0) $summary['zero_cost_items']++;

        $storeKey = (int)$r['store_id'];
        if (!isset($byStore[$storeKey])) {
            $byStore[$storeKey] = [
                'store_id' => $storeKey,
                'location_name' => $r['location_name'],
                'items' => 0,
                'qty' => 0,
                'stock_value' => 0,
                'retail_value' => 0,
            ];
        }
        $byStore[$storeKey]['items']++;
        $byStore[$storeKey]['qty'] += $qty;
        $byStore[$storeKey]['stock_value'] += $stockValue;
        $byStore[$storeKey]['retail_value'] += $retailValue;

        $catKey = (string)($r['category_name'] ?: 'Uncategorised');
        if (!isset($byCategory[$catKey])) {
            $byCategory[$catKey] = [
                'category_name' => $catKey,
                'items' => 0,
                'qty' => 0,
                'stock_value' => 0,
                'retail_value' => 0,
            ];
        }
        $byCategory[$catKey]['items']++;
        $byCategory[$catKey]['qty'] += $qty;
        $byCategory[$catKey]['stock_value'] += $stockValue;
        $byCategory[$catKey]['retail_value'] += $retailValue;
    }
    unset($r);

    usort($byStore, fn($a, $b) => $b['stock_value'] <=> $a['stock_value']);
    usort($byCategory, fn($a, $b) => $b['stock_value'] <=> $a['stock_value']);

} catch (Throwable $e) {
    $errors[] = 'Could not load inventory valuation: ' . $e->getMessage();
}

require_once __DIR__ . '/../../includes/header.php';
?>

<div class="hero-band no-print">
    <div class="row g-4 align-items-center">
        <div class="col-lg-8">
            <div class="page-eyebrow text-white-50"><i class="bi bi-bank"></i> Inventory Finance</div>
            <div class="hero-title mt-2">Inventory Valuation</div>
            <div class="hero-subtitle mt-2">
                Real-time stock value by item and store using average/resolved cost as at selected date.
            </div>
        </div>
        <div class="col-lg-4 text-lg-end">
            <button onclick="window.print()" class="btn btn-light me-2">
                <i class="bi bi-printer me-2"></i>Print
            </button>
            <a href="stock_ledger.php" class="btn btn-outline-light">
                <i class="bi bi-journal-text me-2"></i>Stock Ledger
            </a>
        </div>
    </div>
</div>

<?php if ($errors): ?>
    <div class="alert alert-danger no-print">
        <div class="fw-bold mb-2">Please fix the following:</div>
        <ul class="mb-0"><?php foreach ($errors as $err): ?><li><?php echo h($err); ?></li><?php endforeach; ?></ul>
    </div>
<?php endif; ?>

<div class="card panel-card mb-4 no-print">
    <div class="card-body">
        <form method="get" class="row g-3 align-items-end">
            <div class="col-md-2">
                <label class="form-label">Valuation Date</label>
                <input type="date" name="valuation_date" class="form-control" value="<?php echo h($valuationDate); ?>">
            </div>
            <div class="col-md-2">
                <label class="form-label">Store</label>
                <select name="store_id" class="form-select">
                    <option value="0">All stores</option>
                    <?php foreach ($stores as $store): ?>
                        <option value="<?php echo (int)$store['id']; ?>" <?php echo $storeId === (int)$store['id'] ? 'selected' : ''; ?>>
                            <?php echo h($store['location_name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label">Category</label>
                <select name="category_id" class="form-select">
                    <option value="0">All categories</option>
                    <?php foreach ($categories as $cat): ?>
                        <option value="<?php echo (int)$cat['id']; ?>" <?php echo $categoryId === (int)$cat['id'] ? 'selected' : ''; ?>>
                            <?php echo h($cat['category_name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label">Item Type</label>
                <select name="item_type" class="form-select">
                    <option value="">All types</option>
                    <?php foreach (['stock','food','bar','curio','consumable','service','recipe','other'] as $type): ?>
                        <option value="<?php echo h($type); ?>" <?php echo $itemType === $type ? 'selected' : ''; ?>>
                            <?php echo h(ucwords($type)); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label">Search</label>
                <input type="text" name="q" class="form-control" value="<?php echo h($search); ?>" placeholder="Item / code / store">
            </div>
            <div class="col-md-1">
                <label class="form-label">Zero</label>
                <select name="show_zero" class="form-select">
                    <option value="0" <?php echo $showZero === 0 ? 'selected' : ''; ?>>No</option>
                    <option value="1" <?php echo $showZero === 1 ? 'selected' : ''; ?>>Yes</option>
                </select>
            </div>
            <div class="col-md-1 d-grid">
                <button class="btn btn-primary"><i class="bi bi-funnel"></i></button>
            </div>
        </form>
    </div>
</div>

<div class="print-title d-none d-print-block">
    <h2>Inventory Valuation</h2>
    <p>As at <?php echo h($valuationDate); ?></p>
</div>

<div class="row g-4 mb-4">
    <div class="col-md-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-primary-subtle text-primary"><i class="bi bi-bank"></i></div>
            <div><div class="metric-label">Stock Value</div><div class="metric-value small-value"><?php echo money_fmt($summary['stock_value']); ?></div></div>
        </div>
    </div>
    <div class="col-md-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-success-subtle text-success"><i class="bi bi-tags"></i></div>
            <div><div class="metric-label">Retail Value</div><div class="metric-value small-value"><?php echo money_fmt($summary['retail_value']); ?></div></div>
        </div>
    </div>
    <div class="col-md-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-warning-subtle text-warning"><i class="bi bi-graph-up-arrow"></i></div>
            <div><div class="metric-label">Potential Margin</div><div class="metric-value small-value"><?php echo money_fmt($summary['potential_margin']); ?></div></div>
        </div>
    </div>
    <div class="col-md-6 col-xl-3">
        <div class="metric-card">
            <div class="metric-icon bg-danger-subtle text-danger"><i class="bi bi-exclamation-triangle"></i></div>
            <div><div class="metric-label">Issues</div><div class="metric-value"><?php echo (int)$summary['negative_items'] + (int)$summary['zero_cost_items']; ?></div></div>
        </div>
    </div>
</div>

<div class="row g-4 mb-4">
    <div class="col-xl-6">
        <div class="card panel-card h-100">
            <div class="card-header"><h5 class="mb-0">Value by Store</h5></div>
            <div class="card-body p-0">
                <div class="table-responsive mini-table-wrap">
                    <table class="table table-modern mb-0">
                        <thead>
                            <tr>
                                <th>Store</th>
                                <th class="text-end">Items</th>
                                <th class="text-end">Qty</th>
                                <th class="text-end">Stock Value</th>
                                <th class="text-end">Retail Value</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php if (!$byStore): ?>
                            <tr><td colspan="5" class="text-center text-muted py-4">No store valuation found.</td></tr>
                        <?php else: foreach ($byStore as $s): ?>
                            <tr>
                                <td><strong><?php echo h($s['location_name']); ?></strong></td>
                                <td class="text-end"><?php echo (int)$s['items']; ?></td>
                                <td class="text-end"><?php echo qty_fmt($s['qty']); ?></td>
                                <td class="text-end fw-bold"><?php echo money_fmt($s['stock_value']); ?></td>
                                <td class="text-end"><?php echo money_fmt($s['retail_value']); ?></td>
                            </tr>
                        <?php endforeach; endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    <div class="col-xl-6">
        <div class="card panel-card h-100">
            <div class="card-header"><h5 class="mb-0">Value by Category</h5></div>
            <div class="card-body p-0">
                <div class="table-responsive mini-table-wrap">
                    <table class="table table-modern mb-0">
                        <thead>
                            <tr>
                                <th>Category</th>
                                <th class="text-end">Items</th>
                                <th class="text-end">Qty</th>
                                <th class="text-end">Stock Value</th>
                                <th class="text-end">Retail Value</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php if (!$byCategory): ?>
                            <tr><td colspan="5" class="text-center text-muted py-4">No category valuation found.</td></tr>
                        <?php else: foreach ($byCategory as $c): ?>
                            <tr>
                                <td><strong><?php echo h($c['category_name']); ?></strong></td>
                                <td class="text-end"><?php echo (int)$c['items']; ?></td>
                                <td class="text-end"><?php echo qty_fmt($c['qty']); ?></td>
                                <td class="text-end fw-bold"><?php echo money_fmt($c['stock_value']); ?></td>
                                <td class="text-end"><?php echo money_fmt($c['retail_value']); ?></td>
                            </tr>
                        <?php endforeach; endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="card panel-card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <div>
            <h5 class="mb-0">Inventory Valuation Detail</h5>
            <div class="small text-muted">
                <?php echo (int)$summary['items']; ?> item/store lines as at <?php echo h($valuationDate); ?>.
            </div>
        </div>
        <span class="badge text-bg-light border no-print">Cost basis: AVG cost then cost price</span>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive valuation-table-wrap">
            <table class="table table-modern align-middle mb-0">
                <thead>
                <tr>
                    <th>Store</th>
                    <th>Item</th>
                    <th>Category</th>
                    <th>Type</th>
                    <th class="text-end">Qty</th>
                    <th class="text-end">Avg Cost</th>
                    <th class="text-end">Cost Price</th>
                    <th class="text-end">Valuation Cost</th>
                    <th class="text-end">Stock Value</th>
                    <th class="text-end">Retail Value</th>
                    <th>Status</th>
                </tr>
                </thead>
                <tbody>
                <?php if (!$rows): ?>
                    <tr><td colspan="11" class="text-center text-muted py-4">No inventory valuation lines found.</td></tr>
                <?php else: foreach ($rows as $row): ?>
                    <tr class="<?php echo $row['stock_status'] === 'negative' ? 'table-danger' : ($row['stock_status'] === 'low' ? 'table-warning' : ''); ?>">
                        <td><?php echo h($row['location_name']); ?></td>
                        <td>
                            <strong><?php echo h($row['item_name']); ?></strong>
                            <div class="small text-muted"><?php echo h($row['item_code'] ?? ''); ?></div>
                        </td>
                        <td><?php echo h($row['category_name'] ?: 'Uncategorised'); ?></td>
                        <td><span class="badge text-bg-light border"><?php echo h(ucwords($row['item_type'])); ?></span></td>
                        <td class="text-end"><?php echo qty_fmt($row['qty_on_hand']); ?> <?php echo h($row['unit_code'] ?? ''); ?></td>
                        <td class="text-end"><?php echo money_fmt($row['avg_cost']); ?></td>
                        <td class="text-end"><?php echo money_fmt($row['cost_price']); ?></td>
                        <td class="text-end fw-bold"><?php echo money_fmt($row['valuation_cost']); ?></td>
                        <td class="text-end fw-bold"><?php echo money_fmt($row['stock_value']); ?></td>
                        <td class="text-end"><?php echo money_fmt($row['retail_value']); ?></td>
                        <td>
                            <?php if ($row['stock_status'] === 'negative'): ?>
                                <span class="badge text-bg-danger">Negative</span>
                            <?php elseif ((float)$row['valuation_cost'] <= 0 && abs((float)$row['qty_on_hand']) > 0): ?>
                                <span class="badge text-bg-danger">No Cost</span>
                            <?php elseif ($row['stock_status'] === 'low'): ?>
                                <span class="badge text-bg-warning">Low</span>
                            <?php else: ?>
                                <span class="badge text-bg-success">OK</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; endif; ?>
                </tbody>
                <tfoot>
                    <tr>
                        <th colspan="4" class="text-end">TOTAL</th>
                        <th class="text-end"><?php echo qty_fmt($summary['qty_total']); ?></th>
                        <th colspan="3"></th>
                        <th class="text-end"><?php echo money_fmt($summary['stock_value']); ?></th>
                        <th class="text-end"><?php echo money_fmt($summary['retail_value']); ?></th>
                        <th></th>
                    </tr>
                </tfoot>
            </table>
        </div>
    </div>
</div>

<style>
.small-value{font-size:1rem!important;letter-spacing:0!important}
.valuation-table-wrap{max-height:760px;overflow:auto}
.valuation-table-wrap thead th{position:sticky;top:0;z-index:2;background:#f8fafc}
.mini-table-wrap{max-height:360px;overflow:auto}
.print-title{margin-bottom:18px}
@media print{
    .no-print,.sidebar,.enterprise-sidebar,.app-sidebar,.topbar,.navbar,.header,.footer{display:none!important}
    body{background:#fff!important}
    .panel-card,.card,.metric-card{box-shadow:none!important;border:1px solid #ddd!important}
    .valuation-table-wrap,.mini-table-wrap{max-height:none!important;overflow:visible!important}
    .valuation-table-wrap thead th{position:static!important}
    .table{font-size:11px}
}
</style>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
