<?php
// ------------------------------------------------------------
// 1. Load DB + helpers BEFORE any HTML output
// ------------------------------------------------------------
require_once '../config/database.php';   // $pdo
require_once '../includes/functions.php'; // uploadFile, uploadMultipleFiles, deleteFile, setFlash, h, ...
require_once '../includes/auth.php';      // requireLogin() etc.

// Must be logged in
requireLogin();

// Media base URL
define('MEDIA_BASE_URL', 'https://admin.vocabpanda.com/admin_panel/assets/uploads/');

// ------------------------------------------------------------
// 2. Handle POST – redirect on success
// ------------------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // Basic fields
    $product_code       = trim($_POST['product_code'] ?? '');
    $name               = trim($_POST['name'] ?? '');
    $category_id        = (int)($_POST['category_id'] ?? 0);
    $brand_id           = $_POST['brand_id'] !== '' ? (int)$_POST['brand_id'] : null;
    $buying_price       = (float)($_POST['buying_price'] ?? 0);
    $default_sell_price = (float)($_POST['default_sell_price'] ?? 0);
    $stock_qty          = (int)($_POST['stock_qty'] ?? 0);
    $is_in_stock        = $stock_qty > 0 ? 1 : (int)($_POST['is_in_stock'] ?? 1);
    $section_tag        = $_POST['section_tag'] ?? null;
    $description        = trim($_POST['description'] ?? '');
    $video_url          = trim($_POST['video_url'] ?? '');
    $errors = [];

    if ($product_code === '' || $name === '' || $category_id === 0) {
        $errors[] = 'Product code, name, and category are required.';
    }

    $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $name)));

    // Thumbnail
    $thumbnail = null;
    $thumbRaw  = null;
    if (!empty($_FILES['thumbnail']['name'])) {
        $thumbRaw = uploadFile('thumbnail', ['image/jpeg','image/png','image/gif','image/webp'], '../assets/uploads/');
        if ($thumbRaw === false) {
            $errors[] = 'Thumbnail upload failed.';
        } elseif ($thumbRaw !== null) {
            $thumbnail = MEDIA_BASE_URL . $thumbRaw;
        }
    }

    // Additional images
    $rawImageNames = uploadMultipleFiles('images', ['image/jpeg','image/png','image/gif','image/webp'], '../assets/uploads/');
    $imageFiles = array_map(function($fn) { return MEDIA_BASE_URL . $fn; }, $rawImageNames);

    if (empty($errors)) {
        try {
            $pdo->beginTransaction();

            $stmt = $pdo->prepare("INSERT INTO products (
                category_id, brand_id, product_code, name, slug, description,
                buying_price, default_sell_price, stock_qty,
                is_in_stock, thumbnail_url, video_url, section_tag
            ) VALUES (
                :category_id, :brand_id, :product_code, :name, :slug, :description,
                :buying_price, :default_sell_price, :stock_qty,
                :is_in_stock, :thumbnail_url, :video_url, :section_tag
            )");
            $stmt->execute([
                ':category_id'        => $category_id,
                ':brand_id'           => $brand_id,
                ':product_code'       => $product_code,
                ':name'               => $name,
                ':slug'               => $slug,
                ':description'        => $description,
                ':buying_price'       => $buying_price,
                ':default_sell_price' => $default_sell_price,
                ':stock_qty'          => $stock_qty,
                ':is_in_stock'        => $is_in_stock,
                ':thumbnail_url'      => $thumbnail,
                ':video_url'          => $video_url ?: null,
                ':section_tag'        => $section_tag,
            ]);
            $productId = $pdo->lastInsertId();

            if (!empty($imageFiles)) {
                $imgStmt = $pdo->prepare("INSERT IGNORE INTO product_images (product_id, image_url, sort_order) VALUES (:pid, :url, :sort)");
                $sort = 0;
                foreach ($imageFiles as $img) {
                    $imgStmt->execute([':pid' => $productId, ':url' => $img, ':sort' => $sort++]);
                }
            }

            $pdo->commit();

            setFlash('success', 'Product "' . $name . '" added successfully.');
            header('Location: products.php');
            exit;
        } catch (Exception $e) {
            $pdo->rollBack();
            $errors[] = 'Database error: ' . $e->getMessage();
            // clean up files on error
            if ($thumbRaw) deleteFile('../assets/uploads/' . $thumbRaw);
            foreach ($rawImageNames as $fn) deleteFile('../assets/uploads/' . $fn);
        }
    }
}
?>

<?php
// ------------------------------------------------------------
// 3. Now we include the full layout (header + sidebar) because we didn't redirect
// ------------------------------------------------------------
require_once '../includes/header.php';   // this outputs the top navbar, sidebar, etc.

// Fetch dropdown data (only needed for the form)
$categories = $pdo->query("SELECT id, name FROM categories ORDER BY name")->fetchAll();
$brands     = $pdo->query("SELECT id, name FROM brands ORDER BY name")->fetchAll();
?>

<h1 class="h2 mb-4">Add Product</h1>

<!-- Flash message (if any) -->
<?php $flash = getFlash(); if ($flash): ?>
<div class="alert alert-<?= $flash['type'] ?> alert-dismissible fade show" role="alert">
    <?= htmlspecialchars($flash['message']) ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<!-- Validation errors -->
<?php if (!empty($errors)): ?>
<div class="alert alert-danger">
    <ul class="mb-0">
        <?php foreach ($errors as $e) echo '<li>'.htmlspecialchars($e).'</li>'; ?>
    </ul>
</div>
<?php endif; ?>

<div class="card shadow-sm">
    <div class="card-body">
        <form method="POST" enctype="multipart/form-data">
            <div class="row">
                <!-- Basic Info -->
                <div class="col-md-6 mb-3">
                    <label class="form-label">Product Code *</label>
                    <input type="text" name="product_code" class="form-control"
                           value="<?= htmlspecialchars($_POST['product_code'] ?? '') ?>" required>
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">Product Name *</label>
                    <input type="text" name="name" class="form-control"
                           value="<?= htmlspecialchars($_POST['name'] ?? '') ?>" required>
                </div>
                <div class="col-md-4 mb-3">
                    <label class="form-label">Category *</label>
                    <select name="category_id" class="form-select" required>
                        <option value="">Select</option>
                        <?php foreach ($categories as $cat): ?>
                            <option value="<?= $cat['id'] ?>" <?= ($_POST['category_id'] ?? '') == $cat['id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($cat['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-4 mb-3">
                    <label class="form-label">Brand</label>
                    <select name="brand_id" class="form-select">
                        <option value="">-- None --</option>
                        <?php foreach ($brands as $b): ?>
                            <option value="<?= $b['id'] ?>" <?= ($_POST['brand_id'] ?? '') == $b['id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($b['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-4 mb-3">
                    <label class="form-label">Section Tag</label>
                    <select name="section_tag" class="form-select">
                        <option value="">-- None --</option>
                        <?php foreach (['featured','new','sale'] as $tag): ?>
                            <option value="<?= $tag ?>" <?= ($_POST['section_tag'] ?? '') == $tag ? 'selected' : '' ?>>
                                <?= ucfirst($tag) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <!-- Pricing & Stock -->
                <div class="col-md-6 mb-3">
                    <label class="form-label">Buying Price (Cost)</label>
                    <input type="number" step="0.01" name="buying_price" class="form-control"
                           value="<?= htmlspecialchars($_POST['buying_price'] ?? '0') ?>">
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">Default Sell Price (MRP) *</label>
                    <input type="number" step="0.01" name="default_sell_price" class="form-control"
                           value="<?= htmlspecialchars($_POST['default_sell_price'] ?? '') ?>" required>
                </div>

                <div class="col-md-6 mb-3">
                    <label class="form-label">Stock Qty</label>
                    <input type="number" name="stock_qty" class="form-control"
                           value="<?= htmlspecialchars($_POST['stock_qty'] ?? '0') ?>">
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">In Stock?</label>
                    <select name="is_in_stock" class="form-select">
                        <option value="1" <?= ($_POST['is_in_stock'] ?? 1) == 1 ? 'selected' : '' ?>>Yes</option>
                        <option value="0" <?= ($_POST['is_in_stock'] ?? 1) == 0 ? 'selected' : '' ?>>No</option>
                    </select>
                </div>

                <!-- Description -->
                <div class="col-12 mb-3">
                    <label class="form-label">Description</label>
                    <textarea name="description" class="form-control" rows="4"><?= htmlspecialchars($_POST['description'] ?? '') ?></textarea>
                </div>

                <!-- Video URL -->
                <div class="col-12 mb-3">
                    <label class="form-label">Video URL <small class="text-muted">(YouTube / direct MP4)</small></label>
                    <input type="url" name="video_url" class="form-control"
                           value="<?= htmlspecialchars($_POST['video_url'] ?? '') ?>"
                           placeholder="e.g. https://youtube.com/watch?v=... or https://...">
                </div>

                <!-- Images -->
                <div class="col-md-6 mb-3">
                    <label class="form-label">Thumbnail (main image)</label>
                    <input type="file" name="thumbnail" class="form-control" accept="image/*">
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">Additional Images (multi-select)</label>
                    <input type="file" name="images[]" class="form-control" accept="image/*" multiple>
                </div>
            </div>

            <button type="submit" class="btn btn-primary"><i class="bi bi-save"></i> Create Product</button>
            <a href="products.php" class="btn btn-secondary">Cancel</a>
        </form>
    </div>
</div>

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