<?php

require_once __DIR__ . '/../app/auth.php';
require_once __DIR__ . '/../app/layout.php';
require_once __DIR__ . '/../app/helpers.php';
require_once __DIR__ . '/../app/shop-products.php';
require_once __DIR__ . '/../app/db.php';
require_once __DIR__ . '/../app/settings.php';

$user = sparrow_require_backyard_login();
$pdo = sparrow_db();
$shop_settings = sparrow_get_settings($pdo, [
    'business_name',
    'shop_product_categories',
    'shop_default_stock',
    'shop_default_active',
    'shop_default_featured',
]);
$shop_categories = array_values(array_filter(array_map(
    'trim',
    preg_split('/\r\n|\r|\n/', $shop_settings['shop_product_categories']) ?: []
)));

$notice = '';
$error = '';

function sparrow_product_new_slug(string $name): string
{
    $slug = strtolower(trim($name));
    $slug = preg_replace('/[^a-z0-9]+/', '-', $slug);
    $slug = trim($slug, '-');

    return $slug;
}

function sparrow_product_new_upload_image(string $field_name): ?string
{
    if (empty($_FILES[$field_name]) || ($_FILES[$field_name]['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_NO_FILE) {
        return null;
    }

    if (($_FILES[$field_name]['error'] ?? UPLOAD_ERR_OK) !== UPLOAD_ERR_OK) {
        throw new RuntimeException('Product image could not be uploaded.');
    }

    $tmp_name = $_FILES[$field_name]['tmp_name'] ?? '';
    $original_name = $_FILES[$field_name]['name'] ?? '';

    if (!is_uploaded_file($tmp_name)) {
        throw new RuntimeException('Invalid product image upload.');
    }

    $ext = strtolower(pathinfo($original_name, PATHINFO_EXTENSION));
    $allowed = ['jpg', 'jpeg', 'png', 'webp', 'gif'];

    if (!in_array($ext, $allowed, true)) {
        throw new RuntimeException('Product image must be JPG, PNG, WEBP, or GIF.');
    }

    $storage_dir = dirname(__DIR__) . '/storage/shop-products';

    if (!is_dir($storage_dir)) {
        mkdir($storage_dir, 0775, true);
    }

    $filename = 'product-' . date('Ymd-His') . '-' . bin2hex(random_bytes(4)) . '.' . $ext;
    $full_path = $storage_dir . '/' . $filename;

    if (!move_uploaded_file($tmp_name, $full_path)) {
        throw new RuntimeException('Product image could not be saved.');
    }

    return '/storage/shop-products/' . $filename;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $product_name = trim($_POST['product_name'] ?? '');

        if ($product_name === '') {
            throw new RuntimeException('Product name is required.');
        }

        $image_path = sparrow_product_new_upload_image('product_image');

        $slug = trim($_POST['slug'] ?? '');

        if ($slug === '') {
            $slug = sparrow_product_new_slug($product_name);
        }

        $meta_title = trim($_POST['meta_title'] ?? '');

        if ($meta_title === '') {
            $business_name = trim($shop_settings['business_name']);
            $meta_title = $business_name !== ''
                ? $product_name . ' | ' . $business_name
                : $product_name;
        }

        $product_id = sparrow_create_shop_product([
            'product_name' => $product_name,
            'slug' => $slug,
            'category' => $_POST['category'] ?? '',
            'description' => $_POST['description'] ?? '',
            'short_description' => $_POST['short_description'] ?? '',
            'price' => $_POST['price'] ?? 0,
            'quantity_available' => $_POST['quantity_available'] ?? 1,
            'image_path' => $image_path ?? '',
            'source_image_urls' => $_POST['source_image_urls'] ?? '',
            'is_active' => $_POST['is_active'] ?? 0,
            'is_featured' => $_POST['is_featured'] ?? 0,
            'sort_order' => $_POST['sort_order'] ?? 0,
            'source_product_id' => $_POST['source_product_id'] ?? '',
            'meta_title' => $meta_title,
            'meta_description' => $_POST['meta_description'] ?? '',
            'meta_keywords' => $_POST['meta_keywords'] ?? '',
        ]);

        header('Location: ' . sparrow_url('/backyard/product.php?id=' . (int) $product_id . '&notice=created'));
        exit;
    } catch (Throwable $e) {
        $error = $e->getMessage();
    }
}

sparrow_backyard_header('Add Product');

?>

<style>
.product-new-grid {
    display: grid;
    grid-template-columns: 280px 1fr;
    gap: 18px;
    align-items: start;
}

.product-new-placeholder {
    width: 240px;
    height: 240px;
    max-width: 100%;
    border-radius: 16px;
    border: 1px dashed var(--sparrow-border, #ead2df);
    background: #fdf0f7;
    color: #8a7080;
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    padding: 16px;
}

.product-new-checks {
    display: flex;
    flex-wrap: wrap;
    gap: 14px;
    margin-top: 12px;
}

.product-new-checks label {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    font-weight: bold;
}

.product-new-actions {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin-top: 16px;
}

.product-new-section-title {
    margin-top: 22px;
}

.product-image-note {
    margin-top: 10px;
    color: var(--sparrow-muted, #8a7080);
    font-size: 12px;
}

@media (max-width: 900px) {
    .product-new-grid {
        grid-template-columns: 1fr;
    }
}
</style>

<?php if ($error): ?>
    <div class="notice-error">
        <?php echo sparrow_escape($error); ?>
    </div>
<?php endif; ?>

<section class="card">
    <div class="page-heading-row">
        <div>
            <h1>Add Product</h1>
            <p class="muted">
                Add a premade item to the public shop.
            </p>
        </div>

        <div class="heading-actions">
            <a
                class="button button-secondary"
                href="<?php echo sparrow_escape(sparrow_url('/backyard/products.php')); ?>"
            >
                Back to Products
            </a>
        </div>
    </div>
</section>

<form method="post" enctype="multipart/form-data">
    <div class="product-new-grid">
        <section class="card">
            <h2>Image & Status</h2>

            <div class="product-new-placeholder">
                Product image preview will appear after saving.
            </div>

            <div class="form-section">
                <label for="product_image">Product Image</label>
                <input id="product_image" name="product_image" type="file" accept="image/*">
            </div>

            <p class="product-image-note">
                Upload a product photo here. You can replace it later on the edit page.
            </p>

            <div class="product-new-checks">
                <label>
                    <input type="checkbox" name="is_active" value="1" <?php echo $shop_settings['shop_default_active'] === 'yes' ? 'checked' : ''; ?>>
                    Show in public shop
                </label>

                <label>
                    <input type="checkbox" name="is_featured" value="1" <?php echo $shop_settings['shop_default_featured'] === 'yes' ? 'checked' : ''; ?>>
                    Featured
                </label>
            </div>
        </section>

        <section class="card">
            <h2>Product Details</h2>

            <div class="form-section">
                <label for="product_name">Product Name</label>
                <input
                    id="product_name"
                    name="product_name"
                    type="text"
                    required
                >
            </div>

            <div class="form-grid">
                <div>
                    <label for="price">Price</label>
                    <input
                        id="price"
                        name="price"
                        type="number"
                        step="0.01"
                        min="0"
                        value="0.00"
                    >
                </div>

                <div>
                    <label for="quantity_available">Stock</label>
                    <input
                        id="quantity_available"
                        name="quantity_available"
                        type="number"
                        min="0"
                        value="<?php echo (int) $shop_settings['shop_default_stock']; ?>"
                    >
                </div>

                <div>
                    <label for="sort_order">Sort Order</label>
                    <input
                        id="sort_order"
                        name="sort_order"
                        type="number"
                        value="0"
                    >
                </div>
            </div>

            <div class="form-grid">
                <div>
                    <label for="category">Category</label>
                    <select id="category" name="category">
                        <option value="">Choose a category</option>
                        <?php foreach ($shop_categories as $category): ?>
                            <option value="<?php echo sparrow_escape($category); ?>"><?php echo sparrow_escape($category); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div>
                    <label for="source_product_id">WooCommerce ID</label>
                    <input
                        id="source_product_id"
                        name="source_product_id"
                        type="text"
                        placeholder="Optional"
                    >
                </div>
            </div>

            <div class="form-section">
                <label for="short_description">Short Description</label>
                <textarea
                    id="short_description"
                    name="short_description"
                    rows="3"
                ></textarea>
            </div>

            <div class="form-section">
                <label for="description">Full Description</label>
                <textarea
                    id="description"
                    name="description"
                    rows="8"
                ></textarea>
            </div>

            <h2 class="product-new-section-title">SEO / Search Info</h2>

            <div class="form-section">
                <label for="slug">Slug</label>
                <input
                    id="slug"
                    name="slug"
                    type="text"
                    placeholder="Leave blank to auto-create from product name"
                >
            </div>

            <div class="form-section">
                <label for="meta_title">Meta Title</label>
                <input
                    id="meta_title"
                    name="meta_title"
                    type="text"
                    placeholder="Leave blank to use product name"
                >
            </div>

            <div class="form-section">
                <label for="meta_description">Meta Description</label>
                <textarea
                    id="meta_description"
                    name="meta_description"
                    rows="3"
                ></textarea>
            </div>

            <div class="form-section">
                <label for="meta_keywords">Tags / Keywords</label>
                <textarea
                    id="meta_keywords"
                    name="meta_keywords"
                    rows="3"
                ></textarea>
            </div>

            <div class="form-section">
                <label for="source_image_urls">WooCommerce Image URLs</label>
                <textarea
                    id="source_image_urls"
                    name="source_image_urls"
                    rows="3"
                ></textarea>
            </div>

            <div class="product-new-actions">
                <button type="submit" class="button">
                    Save Product
                </button>

                <a
                    class="button button-secondary"
                    href="<?php echo sparrow_escape(sparrow_url('/backyard/products.php')); ?>"
                >
                    Cancel
                </a>
            </div>
        </section>
    </div>
</form>

<?php sparrow_backyard_footer(); ?>
