<?php
$pageTitle = 'View Products';
require_once '../includes/functions.php';
requireLogin();
$db = getDB();

// Handle Delete
$action = $_GET['action'] ?? '';
$id     = (int)($_GET['id'] ?? 0);

if ($action === 'delete' && $id) {
    try {
        $db->prepare("DELETE FROM products WHERE id=?")->execute([$id]);
        setFlash('success', 'Product deleted successfully.');
    } catch (PDOException $e) {
        setFlash('error', 'Cannot delete product — it may be used in invoices.');
    }
    header('Location: product_view.php');
    exit;
}

// Filters
$search      = trim($_GET['search'] ?? '');
$filterType  = trim($_GET['type'] ?? '');
$filterStatus= trim($_GET['status'] ?? '');
$page        = max(1, (int)($_GET['page'] ?? 1));

$where  = 'WHERE 1=1';
$params = [];

if ($search) {
    $where .= ' AND (name LIKE ? OR sku LIKE ?)';
    $params[] = "%$search%";
    $params[] = "%$search%";
}
if ($filterStatus) {
    $where .= ' AND status = ?';
    $params[] = $filterStatus;
}

$result = paginate("SELECT * FROM products $where ORDER BY created_at DESC", $params, $page, 15);

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

<!-- Page Header -->
<div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mb-5">
    <div>
        <h2 class="text-lg font-bold text-slate-800">Products</h2>
        <p class="text-sm text-slate-400"><?= $result['total'] ?> product<?= $result['total'] != 1 ? 's' : '' ?> found</p>
    </div>
    <a href="product_add.php" class="btn-primary">
        <i class="fas fa-plus"></i> Add New Product
    </a>
</div>

<!-- Search & Filter -->
<div class="card p-4 mb-5">
    <form method="GET" class="flex flex-col sm:flex-row gap-3 items-end">
        <div class="flex-1">
            <label class="block text-xs font-semibold text-slate-500 mb-1">Search</label>
            <div class="relative">
                <i class="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 text-sm"></i>
                <input type="text" name="search" value="<?= sanitize($search) ?>"
                    placeholder="Search by name or SKU..." class="form-input pl-9">
            </div>
        </div>
        <div class="w-full sm:w-36">
            <label class="block text-xs font-semibold text-slate-500 mb-1">Status</label>
            <select name="status" class="form-input">
                <option value="">All Status</option>
                <option value="active"   <?= $filterStatus === 'active'   ? 'selected' : '' ?>>Active</option>
                <option value="inactive" <?= $filterStatus === 'inactive' ? 'selected' : '' ?>>Inactive</option>
            </select>
        </div>
        <div class="flex gap-2">
            <button type="submit" class="btn-primary">
                <i class="fas fa-filter"></i> Filter
            </button>
            <?php if ($search || $filterStatus): ?>
            <a href="product_view.php" class="btn-outline"><i class="fas fa-times"></i> Clear</a>
            <?php endif; ?>
        </div>
    </form>
</div>

<!-- Summary Cards -->
<?php
$totals = $db->query("SELECT COUNT(*) as total, SUM(CASE WHEN status='active' THEN 1 ELSE 0 END) as active_count, SUM(stock_quantity) as total_stock FROM products")->fetch();
?>
<div class="grid grid-cols-2 sm:grid-cols-3 gap-4 mb-5">
    <div class="card p-4">
        <p class="text-xs text-slate-400 font-semibold uppercase tracking-wide mb-1">Total Products</p>
        <p class="text-2xl font-bold text-slate-800"><?= $totals['total'] ?></p>
    </div>
    <div class="card p-4">
        <p class="text-xs text-slate-400 font-semibold uppercase tracking-wide mb-1">Active</p>
        <p class="text-2xl font-bold text-green-600"><?= $totals['active_count'] ?></p>
    </div>
    <div class="card p-4 col-span-2 sm:col-span-1">
        <p class="text-xs text-slate-400 font-semibold uppercase tracking-wide mb-1">Total Stock</p>
        <p class="text-2xl font-bold text-brand-600"><?= number_format($totals['total_stock'] ?? 0) ?></p>
    </div>
</div>

<!-- Products Table -->
<div class="card overflow-hidden">
    <div class="overflow-x-auto">
        <table class="w-full text-sm">
            <thead class="bg-slate-50 border-b border-slate-100">
                <tr>
                    <th class="text-left px-4 py-3.5 text-slate-500 font-semibold text-xs uppercase tracking-wide">#</th>
                    <th class="text-left px-4 py-3.5 text-slate-500 font-semibold text-xs uppercase tracking-wide">Product Name</th>
                    <th class="text-left px-4 py-3.5 text-slate-500 font-semibold text-xs uppercase tracking-wide">SKU / HSN</th>
                    <th class="text-right px-4 py-3.5 text-slate-500 font-semibold text-xs uppercase tracking-wide">Price (₹)</th>
                    <th class="text-right px-4 py-3.5 text-slate-500 font-semibold text-xs uppercase tracking-wide">GST%</th>
                    <th class="text-right px-4 py-3.5 text-slate-500 font-semibold text-xs uppercase tracking-wide">Stock</th>
                    <th class="text-left px-4 py-3.5 text-slate-500 font-semibold text-xs uppercase tracking-wide">Status</th>
                    <th class="text-right px-4 py-3.5 text-slate-500 font-semibold text-xs uppercase tracking-wide">Actions</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-50">
                <?php if (empty($result['data'])): ?>
                <tr>
                    <td colspan="8" class="text-center py-16 text-slate-400">
                        <i class="fas fa-box-open text-4xl mb-3 block text-slate-200"></i>
                        <p class="font-semibold">No products found</p>
                        <a href="product_add.php" class="btn-primary mt-4 inline-flex">
                            <i class="fas fa-plus mr-1"></i> Add Your First Product
                        </a>
                    </td>
                </tr>
                <?php else: foreach ($result['data'] as $i => $p): ?>
                <tr class="table-row">
                    <td class="px-4 py-3.5 text-slate-400 text-xs"><?= ($page - 1) * 15 + $i + 1 ?></td>
                    <td class="px-4 py-3.5">
                        <div class="font-bold text-slate-800"><?= sanitize($p['name']) ?></div>
                        <?php if ($p['description']): ?>
                        <div class="text-xs text-slate-400 truncate max-w-xs mt-0.5"><?= sanitize($p['description']) ?></div>
                        <?php endif; ?>
                    </td>
                    <td class="px-4 py-3.5">
                        <?php if ($p['sku']): ?>
                        <span class="font-mono text-xs bg-slate-100 px-2 py-0.5 rounded text-slate-600 block w-fit mb-1">SKU: <?= sanitize($p['sku']) ?></span>
                        <?php endif; ?>
                    </td>
                    <td class="px-4 py-3.5 text-right font-bold text-slate-800">
                        <?= formatCurrency($p['price']) ?>
                    </td>
                    <td class="px-4 py-3.5 text-right">
                        <span class="text-xs font-semibold bg-blue-50 text-blue-600 px-2 py-0.5 rounded-full"><?= $p['gst_percent'] ?>%</span>
                    </td>
                    <td class="px-4 py-3.5 text-right">
                        <span class="font-bold text-lg <?= $p['stock_quantity'] < 10 ? 'text-red-600' : 'text-slate-700' ?>">
                            <?= number_format($p['stock_quantity']) ?>
                        </span>
                        <?php if ($p['stock_quantity'] < 10): ?>
                        <div class="text-xs text-red-400">Low stock</div>
                        <?php endif; ?>
                    </td>
                    <td class="px-4 py-3.5"><?= statusBadge($p['status']) ?></td>
                    <td class="px-4 py-3.5 text-right">
                        <div class="flex items-center justify-end gap-2">
                            <button onclick="editProduct(<?= htmlspecialchars(json_encode($p)) ?>)"
                                class="text-xs font-semibold text-brand-600 hover:text-brand-700 bg-brand-50 hover:bg-brand-100 px-3 py-1.5 rounded-lg transition">
                                <i class="fas fa-pen mr-1"></i>Edit
                            </button>
                            <form method="GET" action="product_view.php" class="inline"
                                onsubmit="return confirm('Delete \'<?= addslashes($p['name']) ?>\'? This cannot be undone.')">
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="id" value="<?= $p['id'] ?>">
                                <button type="submit"
                                    class="text-xs font-semibold text-red-500 hover:text-red-700 bg-red-50 hover:bg-red-100 px-3 py-1.5 rounded-lg transition">
                                    <i class="fas fa-trash mr-1"></i>Delete
                                </button>
                            </form>
                        </div>
                    </td>
                </tr>
                <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>

    <!-- Pagination -->
    <?php if ($result['totalPages'] > 1): ?>
    <div class="px-5 py-4 border-t border-slate-100 flex items-center justify-between">
        <span class="text-xs text-slate-400">Page <?= $page ?> of <?= $result['totalPages'] ?> (<?= $result['total'] ?> products)</span>
        <div class="flex gap-1.5">
            <?php for ($pg = 1; $pg <= $result['totalPages']; $pg++): ?>
            <a href="?page=<?= $pg ?>&search=<?= urlencode($search) ?>&status=<?= urlencode($filterStatus) ?>"
                class="w-8 h-8 flex items-center justify-center rounded-lg text-xs font-bold
                <?= $pg == $page ? 'bg-brand-600 text-white' : 'bg-slate-100 text-slate-600 hover:bg-slate-200' ?>">
                <?= $pg ?>
            </a>
            <?php endfor; ?>
        </div>
    </div>
    <?php endif; ?>
</div>

<!-- Edit Modal -->
<div id="editModal" class="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 hidden items-center justify-center p-4">
    <div class="bg-white rounded-2xl shadow-2xl w-full max-w-lg max-h-[85vh] overflow-y-auto">
        <div class="flex items-center justify-between p-6 border-b border-slate-100">
            <h3 class="font-bold text-slate-800 text-lg">Edit Product</h3>
            <button onclick="closeEdit()" class="text-slate-400 hover:text-slate-600 w-8 h-8 flex items-center justify-center rounded-lg hover:bg-slate-100">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <form method="POST" action="products.php" class="p-6 space-y-4">
            <input type="hidden" name="_action" value="edit">
            <input type="hidden" name="id" id="eId">
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div class="col-span-2">
                    <label class="block text-xs font-bold text-slate-600 mb-1.5 uppercase tracking-wide">Product Name *</label>
                    <input type="text" name="name" id="eName" class="form-input" required>
                </div>
                <div>
                    <label class="block text-xs font-bold text-slate-600 mb-1.5 uppercase tracking-wide">Price (₹) *</label>
                    <input type="number" step="0.01" name="price" id="ePrice" class="form-input" required>
                </div>
                <div>
                    <label class="block text-xs font-bold text-slate-600 mb-1.5 uppercase tracking-wide">GST %</label>
                    <select name="gst_percent" id="eGst" class="form-input">
                        <?php foreach ([0, 5, 12, 18, 28] as $g): ?>
                        <option value="<?= $g ?>"><?= $g ?>%</option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="block text-xs font-bold text-slate-600 mb-1.5 uppercase tracking-wide">Stock Qty</label>
                    <input type="number" name="stock_quantity" id="eQty" class="form-input">
                </div>
                <div>
                    <label class="block text-xs font-bold text-slate-600 mb-1.5 uppercase tracking-wide">SKU</label>
                    <input type="text" name="sku" id="eSku" class="form-input font-mono">
                </div>
                <div class="col-span-2">
                    <label class="block text-xs font-bold text-slate-600 mb-1.5 uppercase tracking-wide">Description</label>
                    <textarea name="description" id="eDesc" class="form-input" rows="2"></textarea>
                </div>
                <div>
                    <label class="block text-xs font-bold text-slate-600 mb-1.5 uppercase tracking-wide">Status</label>
                    <select name="status" id="eStatus" class="form-input">
                        <option value="active">Active</option>
                        <option value="inactive">Inactive</option>
                    </select>
                </div>
            </div>
            <div class="flex gap-3 pt-2">
                <button type="submit" class="btn-primary flex-1 justify-center">
                    <i class="fas fa-save mr-1"></i> Save Changes
                </button>
                <button type="button" onclick="closeEdit()" class="btn-outline">Cancel</button>
            </div>
        </form>
    </div>
</div>

<script>
function editProduct(p) {
    document.getElementById('eId').value    = p.id;
    document.getElementById('eName').value  = p.name;
    document.getElementById('ePrice').value = p.price;
    document.getElementById('eGst').value   = p.gst_percent;
    document.getElementById('eQty').value   = p.stock_quantity;
    document.getElementById('eSku').value   = p.sku || '';
    document.getElementById('eDesc').value  = p.description || '';
    document.getElementById('eStatus').value = p.status;
    const modal = document.getElementById('editModal');
    modal.classList.remove('hidden');
    modal.classList.add('flex');
}
function closeEdit() {
    const modal = document.getElementById('editModal');
    modal.classList.add('hidden');
    modal.classList.remove('flex');
}
</script>

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