<?php
require_once '../includes/auth.php';
requirePermission('products', 'view');
require_once '../db.php';
require_once '../includes/header.php';
require_once '../includes/sidebar.php';

$userRole = $_SESSION['user_role'] ?? '';
$search   = $_GET['search'] ?? '';

$filterCo = $cid;
$companies = null;
if (in_array($userRole, ['admin', 'master_staff'])) {
    $filterCo  = isset($_GET['co']) ? (int)$_GET['co'] : 0;
    $companies = $conn->query("SELECT id, company_name FROM company_master ORDER BY company_name");
}

$sql = "SELECT * FROM products WHERE status = 1";
$sql .= $filterCo > 0 ? " AND company_id = $filterCo" : "";
if ($search !== '') {
    $s = $conn->real_escape_string($search);
    $sql .= " AND (name LIKE '%$s%' OR brand LIKE '%$s%' OR hsn_code LIKE '%$s%')";
}
$sql .= " ORDER BY name";
$result = $conn->query($sql);
?>

<div class="page-header">
    <h2><i class="fas fa-box" style="color:var(--primary);margin-right:8px;"></i>Products</h2>
    <a href="create.php" class="btn btn-primary"><i class="fas fa-plus"></i> Add Product</a>
</div>

<div class="panel">
    <div class="panel-header">
        <span class="panel-title">Product List</span>
        <form method="get" class="search-bar" style="display:flex;gap:6px;align-items:center;flex-wrap:wrap;">
            <?php if ($companies): ?>
            <select name="co" onchange="this.form.submit()" style="font-size:13px;padding:5px 8px;border:1px solid var(--border);border-radius:6px;">
                <option value="0" <?= $filterCo == 0 ? 'selected' : '' ?>>All Companies</option>
                <?php while ($co = $companies->fetch_assoc()): ?>
                <option value="<?= $co['id'] ?>" <?= $filterCo == $co['id'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars($co['company_name']) ?>
                </option>
                <?php endwhile; ?>
            </select>
            <?php endif; ?>
            <input type="text" name="search" placeholder="Search name, brand, HSN..."
                   value="<?= htmlspecialchars($search) ?>">
            <button type="submit" class="btn btn-primary btn-sm"><i class="fas fa-search"></i></button>
            <?php if ($search || ($companies && $filterCo > 0)): ?>
            <a href="index.php" class="btn btn-secondary btn-sm">Clear</a>
            <?php endif; ?>
        </form>
    </div>
    <div style="overflow-x:auto;">
        <table>
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Brand</th>
                    <th>Category</th>
                    <th>Unit</th>
                    <th>HSN Code</th>
                    <th style="text-align:right;">Selling Price</th>
                    <th>Status</th>
                    <th style="text-align:center;">Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php if ($result->num_rows > 0): while ($row = $result->fetch_assoc()): ?>
            <tr>
                <td><strong><?= htmlspecialchars($row['name']) ?></strong></td>
                <td><?= htmlspecialchars($row['brand']) ?></td>
                <td><?= htmlspecialchars($row['category']) ?></td>
                <td><?= htmlspecialchars($row['unit']) ?></td>
                <td><span style="font-family:monospace;font-size:12px;"><?= htmlspecialchars($row['hsn_code']) ?></span></td>
                <td style="text-align:right;"><?= $row['selling_price'] > 0 ? '&#8377; ' . number_format((float)$row['selling_price'], 2) : '<span style="color:var(--text-muted)">—</span>' ?></td>
                <td><span class="badge <?= $row['status'] ? 'badge-success' : 'badge-gray' ?>"><?= $row['status'] ? 'Active' : 'Inactive' ?></span></td>
                <td>
                    <div class="action-links" style="justify-content:center;">
                        <a href="edit.php?id=<?= $row['id'] ?>" class="action-btn edit" title="Edit">
                            <i class="fas fa-edit"></i>
                        </a>
                        <a href="toggle_status.php?id=<?= $row['id'] ?>"
                           onclick="return confirm('Change status of this product?')"
                           class="action-btn <?= $row['status'] ? 'delete' : 'view' ?>"
                           title="<?= $row['status'] ? 'Disable' : 'Enable' ?>">
                            <i class="fas fa-<?= $row['status'] ? 'ban' : 'check-circle' ?>"></i>
                        </a>
                    </div>
                </td>
            </tr>
            <?php endwhile; else: ?>
            <tr><td colspan="8" style="text-align:center;padding:40px;color:var(--text-muted);">
                <i class="fas fa-inbox" style="font-size:28px;display:block;margin-bottom:8px;"></i>
                No products found.
            </td></tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

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