<?php
require_once __DIR__ . '/../../includes/functions.php';
requireLogin();

$search = trim($_GET['search'] ?? '');
$where = '';
$params = [];
if ($search) {
    $where = "WHERE i.item_name LIKE ? OR i.item_code LIKE ?";
    $params = ["%$search%","%$search%"];
}

$stmt = $pdo->prepare("SELECT i.*, c.category_name,
                        COALESCE(sl.purchased_qty,0) purchased_qty,
                        COALESCE(sl.available_qty,0) available_qty,
                        COALESCE(sl.freeze_qty,0) freeze_qty,
                        COALESCE(sl.sold_qty,0) sold_qty,
                        COALESCE(sl.avg_purchase_price,0) avg_purchase_price
                        FROM items i
                        LEFT JOIN categories c ON c.id = i.category_id
                        LEFT JOIN stock_ledger sl ON sl.item_id = i.id
                        $where
                        ORDER BY i.item_name");
$stmt->execute($params);
$stock = $stmt->fetchAll();

// Totals
$totalPurchaseValue = 0; $totalAvailableValue = 0; $totalFreezeValue = 0; $totalSoldValue = 0;
foreach ($stock as $s) {
    $totalPurchaseValue += $s['purchased_qty'] * $s['avg_purchase_price'];
    $totalAvailableValue += $s['available_qty'] * $s['avg_purchase_price'];
    $totalFreezeValue += $s['freeze_qty'] * $s['avg_purchase_price'];
    $totalSoldValue += $s['sold_qty'] * $s['avg_purchase_price'];
}

// View movement history for specific item
$movements = [];
$movementItem = null;
if (isset($_GET['item_id'])) {
    $itemId = (int)$_GET['item_id'];
    $stmt = $pdo->prepare("SELECT i.item_name FROM items i WHERE i.id=?");
    $stmt->execute([$itemId]);
    $movementItem = $stmt->fetch();

    $stmt = $pdo->prepare("SELECT sm.*, u.name as user_name FROM stock_movements sm
                            LEFT JOIN users u ON u.id = sm.created_by
                            WHERE sm.item_id = ? ORDER BY sm.id DESC LIMIT 50");
    $stmt->execute([$itemId]);
    $movements = $stmt->fetchAll();
}

// All logic/redirects above are done - safe to render layout now
$pageTitle = 'Stock Overview';
require_once __DIR__ . '/../../includes/header.php';
?>

<div class="page-header">
    <div>
        <div class="eyebrow">Stock</div>
        <h2 class="mb-0">Stock Overview</h2>
    </div>
    <div class="flex gap-8">
        <form method="GET" class="flex gap-8">
            <input type="text" name="search" placeholder="Search items..." value="<?= sanitize($search) ?>" style="width:220px">
            <button class="btn btn-icon" title="Search" style="width:38px;height:38px;"><?= icon('search') ?></button>
        </form>
        <a href="stock_export.php?format=csv<?= $search ? '&search='.urlencode($search) : '' ?>" class="btn"><?= icon('file-type-csv') ?> CSV</a>
        <a href="stock_export.php?format=excel<?= $search ? '&search='.urlencode($search) : '' ?>" class="btn"><?= icon('file-spreadsheet') ?> Excel</a>
        <a href="stock_export.php?format=pdf<?= $search ? '&search='.urlencode($search) : '' ?>" target="_blank" class="btn"><?= icon('file-type-pdf') ?> PDF</a>
    </div>
</div>

<div class="stat-grid">
    <div class="stat-card info">
        <div class="stat-label">Total purchase value</div>
        <div class="stat-value mono" style="font-size:20px"><?= formatMoney($totalPurchaseValue) ?></div>
    </div>
    <div class="stat-card success">
        <div class="stat-label">Available stock value</div>
        <div class="stat-value mono" style="font-size:20px"><?= formatMoney($totalAvailableValue) ?></div>
    </div>
    <div class="stat-card accent">
        <div class="stat-label">Freeze (reserved) value</div>
        <div class="stat-value mono" style="font-size:20px"><?= formatMoney($totalFreezeValue) ?></div>
    </div>
    <div class="stat-card">
        <div class="stat-label">Sold (completed) value</div>
        <div class="stat-value mono" style="font-size:20px"><?= formatMoney($totalSoldValue) ?></div>
    </div>
</div>

<div class="card">
    <div class="card-title">Stock Status by Item</div>
    <?php if ($stock): ?>
    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th>Item</th><th>Category</th>
                    <th class="text-right">Purchased</th>
                    <th class="text-right">Available</th>
                    <th class="text-right">Freeze (Reserved)</th>
                    <th class="text-right">Sold</th>
                    <th class="text-right">Avg Purchase Price</th>
                    <th>Status</th><th></th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($stock as $s): ?>
            <tr>
                <td>
                    <strong><?= sanitize($s['item_name']) ?></strong>
                    <div class="text-sm text-faint mono"><?= sanitize($s['item_code']) ?></div>
                </td>
                <td><?= sanitize($s['category_name']) ?: '-' ?></td>
                <td class="num"><?= $s['purchased_qty'] ?></td>
                <td class="num"><strong><?= $s['available_qty'] ?></strong></td>
                <td class="num"><?= $s['freeze_qty'] ?></td>
                <td class="num"><?= $s['sold_qty'] ?></td>
                <td class="num"><?= formatMoney($s['avg_purchase_price']) ?></td>
                <td>
                    <?php if ($s['available_qty'] <= $s['min_stock_level']): ?>
                    <span class="badge badge-danger">Low Stock</span>
                    <?php elseif ($s['available_qty'] <= $s['min_stock_level'] * 2): ?>
                    <span class="badge badge-warning">Watch</span>
                    <?php else: ?>
                    <span class="badge badge-success">OK</span>
                    <?php endif; ?>
                </td>
                <td><a href="?item_id=<?= $s['id'] ?><?= $search ? '&search='.urlencode($search) : '' ?>" class="btn btn-icon btn-sm" title="View Movements"><?= icon('history') ?></a></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php else: ?>
    <div class="empty-state"><?= icon('stack-2') ?>No items found.</div>
    <?php endif; ?>
</div>

<?php if ($movementItem): ?>
<div class="card">
    <div class="card-title">
        Movement History: <?= sanitize($movementItem['item_name']) ?>
        <a href="stock_view.php" class="btn btn-sm"><?= icon('x') ?> Close</a>
    </div>
    <?php if ($movements): ?>
    <div class="table-wrap">
        <table>
            <thead>
                <tr><th>Date/Time</th><th>Type</th><th class="text-right">Qty Change</th><th>Reference</th><th>Remarks</th><th>By</th></tr>
            </thead>
            <tbody>
            <?php foreach ($movements as $m): ?>
            <tr>
                <td><?= formatDateTime($m['created_at']) ?></td>
                <td>
                    <?php
                    $typeColors = ['PURCHASE'=>'success','FREEZE'=>'warning','UNFREEZE'=>'info','SOLD'=>'info','ADJUSTMENT'=>'muted'];
                    ?>
                    <span class="badge badge-<?= $typeColors[$m['movement_type']] ?? 'muted' ?>"><?= $m['movement_type'] ?></span>
                </td>
                <td class="num <?= $m['qty']<0?'text-danger':'text-success' ?>"><?= $m['qty']>0?'+':'' ?><?= $m['qty'] ?></td>
                <td><?= sanitize($m['reference_type']) ?> #<?= $m['reference_id'] ?></td>
                <td><?= sanitize($m['remarks']) ?></td>
                <td><?= sanitize($m['user_name'] ?? '-') ?></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php else: ?>
    <div class="empty-state"><?= icon('history') ?>No movement history for this item.</div>
    <?php endif; ?>
</div>
<?php endif; ?>

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