<?php
// Ensure DB connection exists
require_once __DIR__ . "/../db.php";
require_once __DIR__ . "/../session.php";

// Require authentication
requireAuth();

$current_business = getCurrentBusiness();
if (!$current_business) {
    header('Location: ' . BASE_URL . '/public/login.php');
    exit;
}

$business_id = $current_business['business_id'];

// 1. Fetch items (Now includes the 'dynamic_data' column)
$items = all_rows("SELECT * FROM new_items WHERE business_id = ? ORDER BY id DESC", [$business_id]);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Items List</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    
    <style>
        body { background-color: #f4f6f9; }
        .table-card { border-radius: 10px; border: none; box-shadow: 0 4px 6px rgba(0,0,0,0.05); }
        .item-img { width: 50px; height: 50px; object-fit: cover; border-radius: 6px; border: 1px solid #ddd; }
        .unit-badge { font-size: 0.75rem; background: #eef2ff; color: #4f46e5; border: 1px solid #c7d2fe; padding: 2px 6px; border-radius: 4px; }
        .price-text { font-weight: 600; color: #2c3e50; }
        .text-sku { font-size: 0.8rem; color: #888; }
        
        /* New Style for Dynamic Specs */
        .spec-badge {
            font-size: 0.75rem;
            font-weight: normal;
            background-color: #f8f9fa;
            color: #555;
            border: 1px solid #dee2e6;
            margin-right: 4px;
            margin-top: 4px;
            display: inline-block;
        }

        body {
            background-image: url("<?php echo BASE_URL; ?>/public/grocery.png");
            background-size: cover;
            background-repeat: no-repeat;
            background-attachment: fixed;
            background-position: center;
        }
        .container{
            background: rgba(255, 255, 255, 0.88);
            border-radius: 16px;
            padding: 1rem;
            box-shadow: 0 10px 30px rgba(0, 0, 0, .15);
            backdrop-filter: blur(2px);
        }
    </style>
</head>

<body>

<div class="container-fluid py-4">
    
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h4 class="mb-0 text-primary fw-bold"><i class="bi bi-box-seam"></i> Item Management</h4>
        <a href="<?= BASE_URL ?>/public/?r=add_items" class="btn btn-primary">
            <i class="bi bi-plus-lg"></i> Add New Item
        </a>
    </div>

    <div class="card table-card">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0">
                    <thead class="bg-light">
                        <tr>
                            <th class="ps-4">#</th>
                            <th>Image</th>
                            <th style="min-width: 250px;">Item Details</th>
                            <th>Group / Brand</th>
                            <th>Unit Logic</th>
                            <th>Pricing (₹)</th>
                            <th>Stock</th>
                            <th class="text-end pe-4">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (count($items) > 0): ?>
                            <?php foreach ($items as $index => $item): ?>
                                <tr>
                                    <td class="ps-4 text-muted"><?= $index + 1 ?></td>
                                    
                                    <td>
                                        <?php if (!empty($item['img'])): ?>
                                            <img src="uploads/<?= $item['img'] ?>" class="item-img" alt="Item">
                                        <?php else: ?>
                                            <div class="item-img d-flex align-items-center justify-content-center bg-light text-muted">
                                                <i class="bi bi-image"></i>
                                            </div>
                                        <?php endif; ?>
                                    </td>

                                    <td>
                                        <div class="fw-bold text-dark"><?= htmlspecialchars($item['item_name']) ?></div>
                                        
                                        <?php if($item['short_name']): ?>
                                            <div class="text-sku">SKU: <?= htmlspecialchars($item['short_name']) ?></div>
                                        <?php endif; ?>

                                        <span class="badge bg-secondary text-white" style="font-size: 0.7rem;">HSN: <?= $item['hsn_code'] ?: 'N/A' ?></span>

                                        <?php 
                                            // Decode JSON string safely
                                            $specs = json_decode($item['dynamic_data'] ?? '{}', true);
                                            
                                            if (!empty($specs) && is_array($specs)): 
                                        ?>
                                            <div class="mt-1">
                                                <?php foreach ($specs as $key => $val): ?>
                                                    <span class="badge spec-badge text-dark">
                                                        <?= htmlspecialchars($key) ?>: <b><?= htmlspecialchars($val) ?></b>
                                                    </span>
                                                <?php endforeach; ?>
                                            </div>
                                        <?php endif; ?>
                                    </td>

                                    <td>
                                        <small class="d-block text-dark fw-bold"><?= htmlspecialchars($item['company']) ?></small>
                                        <small class="text-muted"><?= htmlspecialchars($item['item_group']) ?></small>
                                    </td>

                                    <td>
                                        <div class="mb-1">
                                            Base: <b><?= htmlspecialchars($item['primary_unit']) ?></b>
                                        </div>
                                        <?php if($item['alternate_unit'] && $item['alternate_unit'] != $item['primary_unit']): ?>
                                            <span class="unit-badge">
                                                1 <?= htmlspecialchars($item['alternate_unit']) ?> = <?= (float)$item['conversion_factor'] ?> <?= htmlspecialchars($item['primary_unit']) ?>
                                            </span>
                                        <?php endif; ?>
                                    </td>

                                    <td>
                                        <div style="font-size: 0.9rem;">
                                            Sale: <span class="text-success fw-bold"><?= number_format($item['sale_price'], 2) ?></span>
                                        </div>
                                        <div style="font-size: 0.8rem;" class="text-muted">
                                            Pur: <?= number_format($item['purchase_price'], 2) ?> | MRP: <?= number_format($item['mrp'], 2) ?>
                                        </div>
                                        <span class="badge bg-info text-dark mt-1"><?= $item['tax_slab'] ?>% Tax</span>
                                    </td>

                                    <td>
                                        <span class="fw-bold fs-5"><?= (float)$item['opening_qty_kg'] ?></span> 
                                        <small class="text-muted"><?= htmlspecialchars($item['primary_unit']) ?></small>
                                    </td>

                                    <td class="text-end pe-4">
                                        <a href="<?= BASE_URL ?>/public/?r=items/edit&id=<?= $item['id'] ?>" class="btn btn-sm btn-outline-primary me-1">
                                            <i class="bi bi-pencil"></i>
                                        </a>
                                        
                                        <a href="<?= BASE_URL ?>/public/?r=items/delete&id=<?= $item['id'] ?>" 
                                           class="btn btn-sm btn-outline-danger"
                                           onclick="return confirm('Are you sure you want to delete this item?');">
                                            <i class="bi bi-trash"></i>
                                        </a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="8" class="text-center py-5 text-muted">
                                    <i class="bi bi-box display-4 d-block mb-2"></i>
                                    No items found. Add your first item!
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

</div>

</body>
</html>