<?php
include 'db.php';
include 'auth_check.php';

// Fetch all stock data with available qty using purchase_stock.id
$sql = "
 SELECT 
        p.id,
        p.item_name,
        p.particular_name,
        p.specification,
        p.model_number,
        p.invoice_number,
        p.incoming_date,
        p.courier_name,
        p.qty AS purchased_qty,
        COALESCE(f.fault_qty,0) AS fault_qty,
        COALESCE(o.outward_qty,0) AS outward_qty,
        (p.qty - COALESCE(f.fault_qty,0) - COALESCE(o.outward_qty,0)) AS available_qty
    FROM purchase_stock p
    LEFT JOIN (
        SELECT purchase_stock_id, SUM(qty) AS fault_qty
        FROM fault_stock
        GROUP BY purchase_stock_id
    ) f ON f.purchase_stock_id = p.id
    LEFT JOIN (
        SELECT purchase_stock_id, SUM(qty) AS outward_qty
        FROM outward_stock
        GROUP BY purchase_stock_id
    ) o ON o.purchase_stock_id = p.id
    WHERE 1=1
";
$result = $conn->query($sql);

// Build hierarchical tree: Item -> Particular -> Specification -> Model with available qty
$tree = [];
while($row = $result->fetch_assoc()){
    $item = $row['item_name'];
    $particular = $row['particular_name'];
    $spec = $row['specification'];
    $model = $row['model_number'];

    $purchased = intval($row['purchased_qty']);
    $outward = intval($row['outward_qty']);
    $fault = intval($row['fault_qty']);
    $available = $purchased - ($outward + $fault);

    $tree[$item][$particular][$spec][] = [
        'model' => $model,
        'available' => $available
    ];
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Stock Categories</title>
    <link rel="icon" type="image/png" href="assets/logo/logo_icon.png">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .tree ul {
            list-style: none;
            padding-left: 1rem;
            border-left: 2px solid #333;
            margin-left: 0.5rem;
        }
        .tree li {
            margin: 0.5rem 0;
            cursor: pointer;
            position: relative;
            user-select: none;
        }
        .tree li::before {
            content: '';
            position: absolute;
            top: 0.7rem;
            left: -1rem;
            width: 0.8rem;
            height: 0;
            border-top: 2px solid #333;
        }
        .tree li > ul { display: none; }
        .tree li.expanded > ul { display: block; }
        .tree li span { padding: 0.1rem 0.3rem; }
        .tree li span:hover { background-color: #e0e0e0; }
        body { display: flex; flex-direction: column; min-height: 100vh; }
        .flex-grow-1 { flex: 1; }
        footer { background: #f8f9fa; padding: 10px 0; }
        .available-zero { color: red; font-weight: bold; }
        .available-positive { color: green; font-weight: bold; }
    </style>
</head>
<body class="bg-light">

<?php
if (session_status() == PHP_SESSION_NONE) session_start();
include 'navbar.php';
?>

<div class="flex-grow-1">
    <div class="container mt-2">
        <h2 class="mb-4 text-center text-success">Stock Categories</h2>
    <div class="stock-tree">
        <?php foreach($tree as $item => $particulars): ?>
            <div class="tree-item">
                <div class="tree-header" onclick="toggleTree(this)">
                    <strong><?php echo htmlspecialchars($item); ?></strong>
                </div>
                <div class="tree-children">
                    <?php foreach($particulars as $part => $specs): ?>
                        <div class="tree-item">
                            <div class="tree-header" onclick="toggleTree(this)">
                                <?php echo htmlspecialchars($part); ?>
                            </div>
                            <div class="tree-children">
                                <?php foreach($specs as $spec => $models): ?>
                                    <div class="tree-item">
                                        <div class="tree-header" onclick="toggleTree(this)">
                                            <?php echo htmlspecialchars($spec); ?>
                                        </div>
                                        <div class="tree-children">
                                            <?php foreach($models as $m): 
                                                $available = $m['available'];
                                                $css = $available > 0 ? 'text-success' : 'text-danger';
                                            ?>
                                                <div class="tree-leaf">
                                                    <?php echo htmlspecialchars($m['model']); ?>
                                                    <span class="<?php echo $css; ?>">(Available: <?php echo $available; ?>)</span>
                                                </div>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
</div>

<style>
.stock-tree .tree-item {
    margin-left: 1rem;
    border-left: 2px solid #ddd;
    padding-left: 0.5rem;
    margin-bottom: 0.3rem;
}
.stock-tree .tree-header {
    cursor: pointer;
    padding: 0.2rem 0.5rem;
    background: #f1f1f1;
    border-radius: 4px;
    margin-bottom: 0.2rem;
}
.stock-tree .tree-header:hover {
    background: #e0e0e0;
}
.stock-tree .tree-children {
    display: none;
    margin-left: 1rem;
}
.stock-tree .tree-leaf {
    padding: 0.1rem 0.5rem;
}
.text-success { color: green; font-weight: bold; }
.text-danger { color: red; font-weight: bold; }
</style>

<script>
function toggleTree(header){
    const children = header.nextElementSibling;
    if(children){
        children.style.display = children.style.display === 'block' ? 'none' : 'block';
    }
}
</script>

    </div>
</div>

<?php
if (session_status() == PHP_SESSION_NONE) session_start();
include 'footer.php';
?>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    document.querySelectorAll('.tree li span').forEach(span => {
        span.addEventListener('click', function(e){
            e.stopPropagation();
            let li = this.parentElement;
            li.classList.toggle('expanded');
        });
    });
</script>

</body>
</html>
