<?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_categories = array_values(array_filter(array_map(
    'trim',
    preg_split('/\r\n|\r|\n/', $shop_settings['shop_product_categories']) ?: []
)));

$product_id = (int) ($_GET['id'] ?? $_POST['product_id'] ?? 0);
$product = $product_id > 0 ? sparrow_get_shop_product($product_id) : null;

if (!$product) {
    sparrow_backyard_header('Product Not Found');
    ?>
    <section class="card">
        <h1>Product Not Found</h1>
        <p class="muted">This product could not be found.</p>

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

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

if (($_GET['notice'] ?? '') === 'created') {
    $notice = 'Product added.';
}

function sparrow_product_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 {
        $action = $_POST['action'] ?? 'save_product';

        if ($action === 'delete_product') {
            sparrow_delete_shop_product($product_id);

            header('Location: ' . sparrow_url('/backyard/products.php?notice=deleted'));
            exit;
        }

        $image_path = sparrow_product_upload_image('product_image');

        if ($image_path === null) {
            $image_path = $product['image_path'] ?? '';
        }

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

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

        sparrow_update_shop_product($product_id, [
            'product_name' => $product_name,
            'slug' => $_POST['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'] ?? ($product['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'] ?? '',
        ]);

        $notice = 'Product updated.';
        $product = sparrow_get_shop_product($product_id);
    } catch (Throwable $e) {
        $error = $e->getMessage();
    }
}

$image_src = '';

if (!empty($product['image_path'])) {
    $image_src = sparrow_url($product['image_path']);
} elseif (!empty($product['source_image_urls'])) {
    $image_urls = explode(',', (string) $product['source_image_urls']);
    $image_src = trim($image_urls[0] ?? '');
}

$page_css = <<<'CSS'
.product-edit-grid {
    display: grid;
    grid-template-columns: 240px 1fr;
    gap: 18px;
    align-items: start;
}

.product-edit-image,
.product-edit-placeholder {
    width: 220px;
    max-width: 100%;
    border-radius: 16px;
    border: 1px solid var(--sparrow-border, #ead2df);
    background: #fdf0f7;
}

.product-edit-image {
    height: 220px;
    object-fit: cover;
    display: block;
}

.product-edit-placeholder {
    height: 220px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #8a7080;
    text-align: center;
    padding: 16px;
}

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

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

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

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

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

@media (max-width: 900px) {
    .product-edit-grid {
        grid-template-columns: 1fr;
    }
}
CSS;

sparrow_backyard_header('Edit Product');

?>

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

.product-edit-image,
.product-edit-placeholder {
    width: 220px;
    max-width: 100%;
    border-radius: 16px;
    border: 1px solid var(--sparrow-border, #ead2df);
    background: #fdf0f7;
}

.product-edit-image {
    height: 220px;
    object-fit: cover;
    display: block;
}

.product-edit-placeholder {
    height: 220px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #8a7080;
    text-align: center;
    padding: 16px;
}

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

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

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

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

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

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

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

<?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>Edit Product</h1>
            <p class="muted">
                <?php echo sparrow_escape($product['product_name']); ?>
            </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>

            <a
                class="button button-secondary"
                href="<?php echo sparrow_escape(sparrow_url('/product.php?id=' . (int) $product['id'])); ?>"
                target="_blank"
            >
                View Public Page
            </a>
        </div>
    </div>
</section>

<form method="post" enctype="multipart/form-data">
    <input type="hidden" name="product_id" value="<?php echo (int) $product['id']; ?>">
	
    <div class="product-edit-grid">
        <section class="card">
            <h2>Image & Status</h2>
<p>
            <?php if ($image_src !== ''): ?>
                <img
                    class="product-edit-image"
                    src="<?php echo sparrow_escape($image_src); ?>"
                    alt="<?php echo sparrow_escape($product['product_name']); ?>"
                >
            <?php else: ?>
                <div class="product-edit-placeholder">
                    No image
                </div>
            <?php endif; ?>

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

            <p class="product-image-note">
                Local uploads will replace the public display image. WooCommerce image URLs stay saved below for reference.
            </p>

            <div class="product-edit-checks">
                <label>
                    <input
                        type="checkbox"
                        name="is_active"
                        value="1"
                        <?php echo !empty($product['is_active']) ? 'checked' : ''; ?>
                    >
                    Show in public shop
                </label>

                <label>
                    <input
                        type="checkbox"
                        name="is_featured"
                        value="1"
                        <?php echo !empty($product['is_featured']) ? '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"
                    value="<?php echo sparrow_escape($product['product_name']); ?>"
                    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="<?php echo sparrow_escape(number_format((float) $product['price'], 2, '.', '')); ?>"
                    >
                </div>

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

                <div>
                    <label for="sort_order">Sort Order</label>
                    <input
                        id="sort_order"
                        name="sort_order"
                        type="number"
                        value="<?php echo (int) $product['sort_order']; ?>"
                    >
                </div>
            </div>

            <div class="form-grid">
                <div>
                    <label for="category">Category</label>
                    <?php $saved_category = trim((string) ($product['category'] ?? '')); ?>
                    <select id="category" name="category">
                        <option value="">Choose a category</option>
                        <?php if ($saved_category !== '' && !in_array($saved_category, $shop_categories, true)): ?>
                            <option value="<?php echo sparrow_escape($saved_category); ?>" selected><?php echo sparrow_escape($saved_category); ?> (saved)</option>
                        <?php endif; ?>
                        <?php foreach ($shop_categories as $category): ?>
                            <option value="<?php echo sparrow_escape($category); ?>" <?php echo $saved_category === $category ? 'selected' : ''; ?>><?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"
                        value="<?php echo sparrow_escape($product['source_product_id'] ?? ''); ?>"
                    >
                </div>
            </div>

            <div class="form-section">
                <label for="short_description">Short Description</label>
                <textarea
                    id="short_description"
                    name="short_description"
                    rows="3"
                ><?php echo sparrow_escape($product['short_description'] ?? ''); ?></textarea>
            </div>

            <div class="form-section">
                <label for="description">Full Description</label>
                <textarea
                    id="description"
                    name="description"
                    rows="8"
                ><?php echo sparrow_escape($product['description'] ?? ''); ?></textarea>
            </div>

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

            <div class="form-section">
                <label for="slug">Slug</label>
                <input
                    id="slug"
                    name="slug"
                    type="text"
                    value="<?php echo sparrow_escape($product['slug'] ?? ''); ?>"
                >
            </div>

            <div class="form-section">
                <label for="meta_title">Meta Title</label>
                <input
                    id="meta_title"
                    name="meta_title"
                    type="text"
                    value="<?php echo sparrow_escape($product['meta_title'] ?? ''); ?>"
                >
            </div>

            <div class="form-section">
                <label for="meta_description">Meta Description</label>
                <textarea
                    id="meta_description"
                    name="meta_description"
                    rows="3"
                ><?php echo sparrow_escape($product['meta_description'] ?? ''); ?></textarea>
            </div>

            <div class="form-section">
                <label for="meta_keywords">Tags / Keywords</label>
                <textarea
                    id="meta_keywords"
                    name="meta_keywords"
                    rows="3"
                ><?php echo sparrow_escape($product['meta_keywords'] ?? ''); ?></textarea>
            </div>

            <div class="product-edit-actions">
    <button
        type="submit"
        class="button"
        name="action"
        value="save_product"
    >
        Save Product
    </button>

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

    <button
        type="submit"
        class="button button-danger"
        name="action"
        value="delete_product"
        onclick="return confirm('Are you sure you want to delete this product?');"
    >
        Delete Product
    </button>
</div>
        </section>
    </div>
</form>

<?php sparrow_backyard_footer(); ?>
