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

$msg = '';

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;
    $hsn      = trim($_POST['hsn_code'] ?? '') ?: null;
    $type     = trim($_POST['product_type'] ?? 'goods');
    $status   = $_POST['status'] ?? 'active';

    if (empty($name) || $price < 0) {
        setFlash('error', 'Product name and valid price are required.');
    } else {
        try {
            $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 '{$name}' added successfully!");
            header('Location: product_view.php');
            exit;
        } catch (PDOException $e) {
            setFlash('error', 'Failed to save product. Please check SKU/inputs (SKU must be unique).');
        }
    }
}

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

<!-- Page Header -->
<div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mb-6">
    <div>
        <h2 class="text-lg font-bold text-slate-800">Add New Product</h2>
        <p class="text-sm text-slate-400">Fill in product details below</p>
    </div>
    <div class="flex gap-2">
        <a href="product_view.php" class="btn-outline">
            <i class="fas fa-eye mr-1"></i> View Products
        </a>
        <a href="products.php" class="btn-outline">
            <i class="fas fa-list mr-1"></i> All Products
        </a>
    </div>
</div>

<div class="max-w-2xl">
    <div class="card p-6 sm:p-8">
        <form method="POST" action="product_add.php">
            <div class="space-y-5">

                <!-- Product Name -->
                <div>
                    <label class="block text-xs font-bold text-slate-600 mb-1.5 uppercase tracking-wide">Product Name <span class="text-red-500">*</span></label>
                    <input type="text" name="name" class="form-input text-base" required
                        placeholder="e.g. 3 Seater Sofa" value="<?= sanitize($_POST['name'] ?? '') ?>">
                </div>

                <!-- Row: Price & GST -->
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-xs font-bold text-slate-600 mb-1.5 uppercase tracking-wide">Price (₹) <span class="text-red-500">*</span></label>
                        <div class="relative">
                            <span class="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 font-bold">₹</span>
                            <input type="number" step="0.01" name="price" class="form-input pl-8" required
                                placeholder="0.00" value="<?= sanitize($_POST['price'] ?? '') ?>">
                        </div>
                    </div>
                    <div>
                        <label class="block text-xs font-bold text-slate-600 mb-1.5 uppercase tracking-wide">GST %</label>
                        <select name="gst_percent" class="form-input">
                            <?php foreach ([0, 5, 12, 18, 28] as $g): ?>
                            <option value="<?= $g ?>" <?= (($_POST['gst_percent'] ?? 18) == $g) ? 'selected' : '' ?>><?= $g ?>%</option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <!-- Row: HSN Code & Type -->
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-xs font-bold text-slate-600 mb-1.5 uppercase tracking-wide">HSN Code</label>
                        <input type="text" name="hsn_code" class="form-input font-mono"
                            placeholder="e.g. 9401" value="<?= sanitize($_POST['hsn_code'] ?? '') ?>">
                        <p class="text-xs text-slate-400 mt-1">Harmonised System of Nomenclature</p>
                    </div>
                    <div>
                        <label class="block text-xs font-bold text-slate-600 mb-1.5 uppercase tracking-wide">Product Type</label>
                        <select name="product_type" class="form-input">
                            <option value="goods" <?= (($_POST['product_type'] ?? '') === 'goods') ? 'selected' : '' ?>>Goods</option>
                            <option value="service" <?= (($_POST['product_type'] ?? '') === 'service') ? 'selected' : '' ?>>Service</option>
                        </select>
                    </div>
                </div>

                <!-- Row: Stock & SKU -->
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-xs font-bold text-slate-600 mb-1.5 uppercase tracking-wide">Stock Quantity</label>
                        <input type="number" name="stock_quantity" class="form-input"
                            placeholder="0" min="0" value="<?= sanitize($_POST['stock_quantity'] ?? '0') ?>">
                    </div>
                    <div>
                        <label class="block text-xs font-bold text-slate-600 mb-1.5 uppercase tracking-wide">SKU (Unique Code)</label>
                        <input type="text" name="sku" class="form-input font-mono"
                            placeholder="e.g. SOF001" value="<?= sanitize($_POST['sku'] ?? '') ?>">
                    </div>
                </div>

                <!-- Description -->
                <div>
                    <label class="block text-xs font-bold text-slate-600 mb-1.5 uppercase tracking-wide">Description</label>
                    <textarea name="description" class="form-input" rows="3"
                        placeholder="Short product description..."><?= sanitize($_POST['description'] ?? '') ?></textarea>
                </div>

                <!-- Status -->
                <div>
                    <label class="block text-xs font-bold text-slate-600 mb-1.5 uppercase tracking-wide">Status</label>
                    <div class="flex gap-4">
                        <label class="flex items-center gap-2 cursor-pointer">
                            <input type="radio" name="status" value="active" <?= (($_POST['status'] ?? 'active') === 'active') ? 'checked' : '' ?> class="accent-brand-600">
                            <span class="text-sm font-semibold text-green-600">Active</span>
                        </label>
                        <label class="flex items-center gap-2 cursor-pointer">
                            <input type="radio" name="status" value="inactive" <?= (($_POST['status'] ?? '') === 'inactive') ? 'checked' : '' ?> class="accent-brand-600">
                            <span class="text-sm font-semibold text-slate-400">Inactive</span>
                        </label>
                    </div>
                </div>

            </div>

            <!-- Action Buttons -->
            <div class="flex gap-3 mt-8 pt-6 border-t border-slate-100">
                <button type="submit" class="btn-primary flex-1 justify-center text-base py-3">
                    <i class="fas fa-plus mr-2"></i> Add Product
                </button>
                <a href="product_view.php" class="btn-outline flex-1 justify-center text-base py-3">
                    Cancel
                </a>
            </div>
        </form>
    </div>
</div>

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