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

$action = $_GET['action'] ?? 'list';
$id     = (int)($_GET['id'] ?? 0);
$msg    = '';

// ── Handle POST ──────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name     = trim($_POST['name'] ?? '');
    $desc     = trim($_POST['description'] ?? '');
    $price    = (float)($_POST['price'] ?? 0);
    $gst      = (float)($_POST['gst_percent'] ?? 0);
    $qty      = (int)($_POST['stock_quantity'] ?? 0);
    $sku      = trim($_POST['sku'] ?? '') ?: null;
    $status   = $_POST['status'] ?? 'active';

    if (empty($name) || $price < 0) {
        setFlash('error', 'Product name and valid price are required.');
    } else {
        try {
            if ($_POST['_action'] === 'add') {
                $stmt = $db->prepare("INSERT INTO products (name, description, price, gst_percent, stock_quantity, sku, status) VALUES (?,?,?,?,?,?,?)");
                $stmt->execute([$name, $desc, $price, $gst, $qty, $sku, $status]);
                setFlash('success', 'Product added successfully!');
            } elseif ($_POST['_action'] === 'edit') {
                $pid = (int)($_POST['id'] ?? 0);
                $stmt = $db->prepare("UPDATE products SET name=?, description=?, price=?, gst_percent=?, stock_quantity=?, sku=?, status=? WHERE id=?");
                $stmt->execute([$name, $desc, $price, $gst, $qty, $sku, $status, $pid]);
                setFlash('success', 'Product updated successfully!');
            }
        } catch (PDOException $e) {
            // Common cause: duplicate SKU (UNIQUE constraint) or bad DB config
            setFlash('error', 'Failed to save product. Please check SKU/inputs.');
        }
    }
    header('Location: products.php');
    exit;
}

// ── Handle Delete ─────────────────────────────────────────────
if ($action === 'delete' && $id) {
    try {
        $db->prepare("DELETE FROM products WHERE id=?")->execute([$id]);
        setFlash('success', 'Product deleted.');
    } catch (PDOException $e) {
        setFlash('error', 'Failed to delete product.');
    }
    header('Location: products.php');
    exit;
}

// ── Edit: fetch product ───────────────────────────────────────
$editProduct = null;
if ($action === 'edit' && $id) {
    $stmt = $db->prepare("SELECT * FROM products WHERE id=?");
    $stmt->execute([$id]);
    $editProduct = $stmt->fetch();
    if (!$editProduct) { header('Location: products.php'); exit; }
}

// ── List with search/filter ───────────────────────────────────
$search = trim($_GET['search'] ?? '');
$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%";
}
$result = paginate("SELECT * FROM products $where ORDER BY created_at DESC", $params, $page);
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'] ?> products found</p>
    </div>
    <button onclick="openModal('productModal')" class="btn-primary">
        <i class="fas fa-plus"></i> Add Product
    </button>
</div>

<!-- Search -->
<form method="GET" class="mb-4 flex flex-col sm:flex-row gap-2">
    <div class="relative flex-1 max-w-sm">
        <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 products..." class="form-input pl-9">
    </div>
    <button type="submit" class="btn-outline">Search</button>
    <?php if ($search): ?><a href="products.php" class="btn-outline">Clear</a><?php endif; ?>
</form>

<!-- 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-5 py-3.5 text-slate-500 font-semibold text-xs uppercase tracking-wide">#</th>
                    <th class="text-left px-5 py-3.5 text-slate-500 font-semibold text-xs uppercase tracking-wide">Product</th>
                    <th class="text-left px-5 py-3.5 text-slate-500 font-semibold text-xs uppercase tracking-wide">SKU</th>
                    <th class="text-right px-5 py-3.5 text-slate-500 font-semibold text-xs uppercase tracking-wide">Price</th>
                    <th class="text-right px-5 py-3.5 text-slate-500 font-semibold text-xs uppercase tracking-wide">GST%</th>
                    <th class="text-right px-5 py-3.5 text-slate-500 font-semibold text-xs uppercase tracking-wide">Stock</th>
                    <th class="text-left px-5 py-3.5 text-slate-500 font-semibold text-xs uppercase tracking-wide">Status</th>
                    <th class="text-right px-5 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-12 text-slate-400">
                    <i class="fas fa-box-open text-3xl mb-2 block"></i>No products found.
                </td></tr>
                <?php else: foreach ($result['data'] as $i => $p): ?>
                <tr class="table-row">
                    <td class="px-5 py-3.5 text-slate-400 text-xs"><?= ($page-1)*10 + $i + 1 ?></td>
                    <td class="px-5 py-3.5">
                        <div class="font-semibold text-slate-800"><?= sanitize($p['name']) ?></div>
                        <div class="text-xs text-slate-400 truncate max-w-xs"><?= sanitize($p['description']) ?></div>
                    </td>
                    <td class="px-5 py-3.5"><span class="font-mono text-xs bg-slate-100 px-2 py-0.5 rounded"><?= sanitize($p['sku'] ?? '—') ?></span></td>
                    <td class="px-5 py-3.5 text-right font-bold text-slate-800"><?= formatCurrency($p['price']) ?></td>
                    <td class="px-5 py-3.5 text-right text-slate-600"><?= $p['gst_percent'] ?>%</td>
                    <td class="px-5 py-3.5 text-right">
                        <span class="font-semibold <?= $p['stock_quantity'] < 10 ? 'text-red-600' : 'text-slate-700' ?>">
                            <?= $p['stock_quantity'] ?>
                        </span>
                    </td>
                    <td class="px-5 py-3.5"><?= statusBadge($p['status']) ?></td>
                    <td class="px-5 py-3.5 text-right">
                        <button onclick="editProduct(<?= htmlspecialchars(json_encode($p)) ?>)" class="text-brand-600 hover:text-brand-700 font-semibold text-xs mr-3">
                            <i class="fas fa-pen mr-1"></i>Edit
                        </button>
                        <form method="POST" action="products.php?action=delete&id=<?= $p['id'] ?>" class="inline" onsubmit="return confirm('Delete this product?')">
                            <button type="submit" class="text-red-500 hover:text-red-700 font-semibold text-xs">
                                <i class="fas fa-trash mr-1"></i>Delete
                            </button>
                        </form>
                    </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'] ?></span>
        <div class="flex gap-2">
            <?php for ($p = 1; $p <= $result['totalPages']; $p++): ?>
            <a href="?page=<?= $p ?>&search=<?= urlencode($search) ?>" class="w-8 h-8 flex items-center justify-center rounded-lg text-xs font-semibold <?= $p == $page ? 'bg-brand-600 text-white' : 'bg-slate-100 text-slate-600 hover:bg-slate-200' ?>">
                <?= $p ?>
            </a>
            <?php endfor; ?>
        </div>
    </div>
    <?php endif; ?>
</div>

<!-- Add/Edit Modal -->
<div id="productModal" 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" id="modalTitle">Add Product</h3>
            <button onclick="closeModal('productModal')" class="text-slate-400 hover:text-slate-600"><i class="fas fa-times"></i></button>
        </div>
        <form method="POST" action="products.php">
            <input type="hidden" name="_action" id="formAction" value="add">
            <input type="hidden" name="id" id="productId">
            <div class="p-6 space-y-4">
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div class="col-span-2">
                        <label class="block text-xs font-semibold text-slate-600 mb-1.5">Product Name *</label>
                        <input type="text" name="name" id="pName" class="form-input" required placeholder="e.g. Wireless Mouse">
                    </div>
                    <div>
                        <label class="block text-xs font-semibold text-slate-600 mb-1.5">Price (₹) *</label>
                        <input type="number" step="0.01" name="price" id="pPrice" class="form-input" required placeholder="0.00">
                    </div>
                    <div>
                        <label class="block text-xs font-semibold text-slate-600 mb-1.5">GST %</label>
                        <input type="number" step="0.01" name="gst_percent" id="pGst" class="form-input" placeholder="18">
                    </div>
                    <div>
                        <label class="block text-xs font-semibold text-slate-600 mb-1.5">Stock Quantity</label>
                        <input type="number" name="stock_quantity" id="pQty" class="form-input" placeholder="0">
                    </div>
                    <div>
                        <label class="block text-xs font-semibold text-slate-600 mb-1.5">SKU</label>
                        <input type="text" name="sku" id="pSku" class="form-input" placeholder="e.g. PRD001">
                    </div>
                    <div class="col-span-2">
                        <label class="block text-xs font-semibold text-slate-600 mb-1.5">Description</label>
                        <textarea name="description" id="pDesc" class="form-input" rows="2" placeholder="Short product description..."></textarea>
                    </div>
                    <div>
                        <label class="block text-xs font-semibold text-slate-600 mb-1.5">Status</label>
                        <select name="status" id="pStatus" class="form-input">
                            <option value="active">Active</option>
                            <option value="inactive">Inactive</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="px-6 pb-6 flex gap-3 justify-end">
                <button type="button" onclick="closeModal('productModal')" class="btn-outline">Cancel</button>
                <button type="submit" class="btn-primary">Save Product</button>
            </div>
        </form>
    </div>
</div>

<script>
function openModal(id) { document.getElementById(id).classList.remove('hidden'); document.getElementById(id).classList.add('flex'); }
function closeModal(id) { document.getElementById(id).classList.add('hidden'); document.getElementById(id).classList.remove('flex'); }

function editProduct(p) {
    document.getElementById('modalTitle').textContent = 'Edit Product';
    document.getElementById('formAction').value = 'edit';
    document.getElementById('productId').value = p.id;
    document.getElementById('pName').value = p.name;
    document.getElementById('pPrice').value = p.price;
    document.getElementById('pGst').value = p.gst_percent;
    document.getElementById('pQty').value = p.stock_quantity;
    document.getElementById('pSku').value = p.sku || '';
    document.getElementById('pDesc').value = p.description || '';
    document.getElementById('pStatus').value = p.status;
    openModal('productModal');
}

<?php if (isset($_GET['action']) && $_GET['action'] === 'add'): ?>
openModal('productModal');
<?php endif; ?>
</script>

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