<?php

require_once __DIR__ . '/../app/auth.php';
require_once __DIR__ . '/../app/layout.php';
require_once __DIR__ . '/../app/helpers.php';
require_once __DIR__ . '/../app/db.php';

$user = sparrow_require_backyard_login();

function sparrow_shop_import_clean_text(string $value): string
{
    $value = str_replace(["\\r\\n", "\\n", "\\r"], "\n", $value);
    $value = html_entity_decode($value, ENT_QUOTES | ENT_HTML5, 'UTF-8');

    $value = preg_replace('/<\s*br\s*\/?>/i', "\n", $value);
    $value = preg_replace('/<\/p>/i', "\n\n", $value);
    $value = preg_replace('/<\/li>/i', "\n", $value);
    $value = preg_replace('/<li[^>]*>/i', '• ', $value);

    $value = strip_tags($value);
    $value = preg_replace("/[ \t]+/", ' ', $value);
    $value = preg_replace("/\n{3,}/", "\n\n", $value);

    return trim($value);
}

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

    return $slug !== '' ? $slug : 'shop-product-' . time();
}

function sparrow_shop_import_value(array $row, string $key): string
{
    return trim((string) ($row[$key] ?? ''));
}

function sparrow_shop_import_price(array $row): float
{
    $sale_price = sparrow_shop_import_value($row, 'Sale price');
    $regular_price = sparrow_shop_import_value($row, 'Regular price');

    $price = $sale_price !== '' ? $sale_price : $regular_price;
    $price = preg_replace('/[^0-9.]/', '', $price);

    return $price !== '' ? (float) $price : 0.00;
}

function sparrow_shop_import_quantity(array $row): int
{
    $stock = sparrow_shop_import_value($row, 'Stock');
    $in_stock = sparrow_shop_import_value($row, 'In stock?');

    if ($stock !== '' && is_numeric($stock)) {
        return max(0, (int) $stock);
    }

    return $in_stock === '1' ? 1 : 0;
}

function sparrow_shop_import_category(array $row): string
{
    $categories_raw = sparrow_shop_import_value($row, 'Categories');

    if ($categories_raw === '') {
        return '';
    }

    $parts = array_map('trim', explode(',', $categories_raw));

    $ignored = [
        'Ready to Sell',
        'Uncategorized',
    ];

    foreach ($parts as $part) {
        if ($part !== '' && !in_array($part, $ignored, true)) {
            return $part;
        }
    }

    return $parts[0] ?? '';
}

function sparrow_shop_import_meta_title(array $row): string
{
    $name = sparrow_shop_import_value($row, 'Name');

    return $name !== '' ? $name . ' | Sparrow & Seed Creations' : '';
}

function sparrow_shop_import_meta_description(array $row, string $short_description): string
{
    $seo_description = sparrow_shop_import_value($row, 'Meta: seo description');

    if ($seo_description !== '') {
        return sparrow_shop_import_clean_text($seo_description);
    }

    return $short_description;
}

function sparrow_shop_import_find_existing(PDO $pdo, string $source_product_id, string $product_name): ?array
{
    if ($source_product_id !== '') {
        $stmt = $pdo->prepare("
            SELECT *
            FROM shop_products
            WHERE source_product_id = :source_product_id
            LIMIT 1
        ");

        $stmt->execute([
            ':source_product_id' => $source_product_id,
        ]);

        $product = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($product) {
            return $product;
        }
    }

    if ($product_name !== '') {
        $stmt = $pdo->prepare("
            SELECT *
            FROM shop_products
            WHERE product_name = :product_name
            LIMIT 1
        ");

        $stmt->execute([
            ':product_name' => $product_name,
        ]);

        $product = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($product) {
            return $product;
        }
    }

    return null;
}

function sparrow_shop_import_read_csv(string $path): array
{
    $handle = fopen($path, 'r');

    if (!$handle) {
        throw new RuntimeException('Could not open CSV file.');
    }

    $headers = fgetcsv($handle);

    if (!$headers) {
        fclose($handle);
        throw new RuntimeException('CSV file is empty.');
    }

    if (isset($headers[0])) {
        $headers[0] = preg_replace('/^\xEF\xBB\xBF/', '', $headers[0]);
    }

    $rows = [];

    while (($data = fgetcsv($handle)) !== false) {
        $row = [];

        foreach ($headers as $index => $header) {
            $row[$header] = $data[$index] ?? '';
        }

        if (trim((string) ($row['Name'] ?? '')) === '') {
            continue;
        }

        $rows[] = $row;
    }

    fclose($handle);

    return $rows;
}

function sparrow_shop_import_build_product_data(array $row): array
{
    $name = sparrow_shop_import_value($row, 'Name');
    $short_description = sparrow_shop_import_clean_text(sparrow_shop_import_value($row, 'Short description'));
    $description = sparrow_shop_import_clean_text(sparrow_shop_import_value($row, 'Description'));
    $category = sparrow_shop_import_category($row);
    $tags = sparrow_shop_import_value($row, 'Tags');
    $source_product_id = sparrow_shop_import_value($row, 'ID');
    $images = sparrow_shop_import_value($row, 'Images');
    $slug = sparrow_shop_import_slug($name);

    return [
        'product_name' => $name,
        'slug' => $slug,
        'category' => $category,
        'description' => $description,
        'short_description' => $short_description,
        'price' => sparrow_shop_import_price($row),
        'quantity_available' => sparrow_shop_import_quantity($row),
        'image_path' => '',
        'source_image_urls' => $images,
        'is_active' => sparrow_shop_import_value($row, 'Published') === '1' ? 1 : 0,
        'is_featured' => sparrow_shop_import_value($row, 'Is featured?') === '1' ? 1 : 0,
        'sort_order' => (int) (sparrow_shop_import_value($row, 'Position') ?: 0),
        'source_product_id' => $source_product_id,
        'meta_title' => sparrow_shop_import_meta_title($row),
        'meta_description' => sparrow_shop_import_meta_description($row, $short_description),
        'meta_keywords' => $tags,
    ];
}

function sparrow_shop_import_insert_product(PDO $pdo, array $product): void
{
    $stmt = $pdo->prepare("
        INSERT INTO shop_products (
            product_name,
            slug,
            category,
            description,
            short_description,
            price,
            quantity_available,
            image_path,
            source_image_urls,
            is_active,
            is_featured,
            sort_order,
            source_product_id,
            meta_title,
            meta_description,
            meta_keywords,
            created_at
        ) VALUES (
            :product_name,
            :slug,
            :category,
            :description,
            :short_description,
            :price,
            :quantity_available,
            :image_path,
            :source_image_urls,
            :is_active,
            :is_featured,
            :sort_order,
            :source_product_id,
            :meta_title,
            :meta_description,
            :meta_keywords,
            NOW()
        )
    ");

    $stmt->execute([
        ':product_name' => $product['product_name'],
        ':slug' => $product['slug'],
        ':category' => $product['category'],
        ':description' => $product['description'],
        ':short_description' => $product['short_description'],
        ':price' => $product['price'],
        ':quantity_available' => $product['quantity_available'],
        ':image_path' => $product['image_path'] ?: null,
        ':source_image_urls' => $product['source_image_urls'] ?: null,
        ':is_active' => $product['is_active'],
        ':is_featured' => $product['is_featured'],
        ':sort_order' => $product['sort_order'],
        ':source_product_id' => $product['source_product_id'],
        ':meta_title' => $product['meta_title'],
        ':meta_description' => $product['meta_description'],
        ':meta_keywords' => $product['meta_keywords'],
    ]);
}

function sparrow_shop_import_update_product(PDO $pdo, int $id, array $product): void
{
    $stmt = $pdo->prepare("
        UPDATE shop_products
        SET
            product_name = :product_name,
            slug = :slug,
            category = :category,
            description = :description,
            short_description = :short_description,
            price = :price,
            quantity_available = :quantity_available,
            source_image_urls = :source_image_urls,
            is_active = :is_active,
            is_featured = :is_featured,
            sort_order = :sort_order,
            source_product_id = :source_product_id,
            meta_title = :meta_title,
            meta_description = :meta_description,
            meta_keywords = :meta_keywords,
            updated_at = NOW()
        WHERE id = :id
        LIMIT 1
    ");

    $stmt->execute([
        ':product_name' => $product['product_name'],
        ':slug' => $product['slug'],
        ':category' => $product['category'],
        ':description' => $product['description'],
        ':short_description' => $product['short_description'],
        ':price' => $product['price'],
        ':quantity_available' => $product['quantity_available'],
        ':source_image_urls' => $product['source_image_urls'] ?: null,
        ':is_active' => $product['is_active'],
        ':is_featured' => $product['is_featured'],
        ':sort_order' => $product['sort_order'],
        ':source_product_id' => $product['source_product_id'],
        ':meta_title' => $product['meta_title'],
        ':meta_description' => $product['meta_description'],
        ':meta_keywords' => $product['meta_keywords'],
        ':id' => $id,
    ]);
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: ' . sparrow_url('/backyard/import.php'));
    exit;
}

try {
    $pdo = sparrow_db();
    $action = $_POST['action'] ?? 'preview';

    if ($action === 'confirm_import') {
        $encoded_rows = $_POST['rows_json'] ?? '';
        $rows_json = base64_decode($encoded_rows, true);

        if (!$rows_json) {
            throw new RuntimeException('Import preview data was missing.');
        }

        $rows = json_decode($rows_json, true);

        if (!is_array($rows)) {
            throw new RuntimeException('Import preview data was invalid.');
        }

        $update_existing = !empty($_POST['update_existing']);

        $created = 0;
        $updated = 0;
        $skipped = 0;

        foreach ($rows as $row) {
            $product = sparrow_shop_import_build_product_data($row);

            if ($product['product_name'] === '') {
                $skipped++;
                continue;
            }

            $existing = sparrow_shop_import_find_existing(
                $pdo,
                $product['source_product_id'],
                $product['product_name']
            );

            if ($existing && $update_existing) {
                sparrow_shop_import_update_product($pdo, (int) $existing['id'], $product);
                $updated++;
                continue;
            }

            if ($existing && !$update_existing) {
                $skipped++;
                continue;
            }

            sparrow_shop_import_insert_product($pdo, $product);
            $created++;
        }

        header(
            'Location: ' . sparrow_url(
                '/backyard/import.php?shop_products_imported=1'
                . '&created=' . $created
                . '&updated=' . $updated
                . '&skipped=' . $skipped
            )
        );
        exit;
    }

    if (empty($_FILES['shop_products_csv']) || ($_FILES['shop_products_csv']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
        throw new RuntimeException('Please choose a WooCommerce products CSV file.');
    }

    $tmp_name = $_FILES['shop_products_csv']['tmp_name'] ?? '';

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

    $rows = sparrow_shop_import_read_csv($tmp_name);

    if (!$rows) {
        throw new RuntimeException('No products were found in this CSV.');
    }

    $preview_rows = [];
    $update_existing = !empty($_POST['update_existing']);

    foreach ($rows as $row) {
        $product = sparrow_shop_import_build_product_data($row);

        $existing = sparrow_shop_import_find_existing(
            $pdo,
            $product['source_product_id'],
            $product['product_name']
        );

        $preview_rows[] = [
            'raw' => $row,
            'product' => $product,
            'existing' => $existing,
        ];
    }

    $rows_json = base64_encode(json_encode($rows));

    sparrow_backyard_header('Preview WooCommerce Shop Products');

    ?>

    <section class="card">
        <h1>Preview WooCommerce Shop Products</h1>

        <p class="muted">
            Review these products before importing. Nothing has been saved yet.
        </p>

        <form method="post" action="<?php echo sparrow_escape(sparrow_url('/backyard/import-shop-products.php')); ?>">
            <input type="hidden" name="action" value="confirm_import">
            <input type="hidden" name="rows_json" value="<?php echo sparrow_escape($rows_json); ?>">

            <label>
                <input
                    type="checkbox"
                    name="update_existing"
                    value="1"
                    <?php echo $update_existing ? 'checked' : ''; ?>
                    style="width:auto;"
                >
                Update existing products when WooCommerce ID or product name matches
            </label>

            <div class="form-actions">
                <button type="submit" class="button">
                    Import These Products
                </button>

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

    <section class="card">
        <h2>Products Found: <?php echo count($preview_rows); ?></h2>

        <div style="overflow-x:auto;">
            <table class="table">
                <thead>
                    <tr>
                        <th>Status</th>
                        <th>Product</th>
                        <th>Category</th>
                        <th>Price</th>
                        <th>Qty</th>
                        <th>Featured</th>
                        <th>SEO Description</th>
                    </tr>
                </thead>

                <tbody>
                    <?php foreach ($preview_rows as $preview): ?>
                        <?php $product = $preview['product']; ?>
                        <tr>
                            <td>
                                <?php echo $preview['existing'] ? 'Will update' : 'Will create'; ?>
                            </td>

                            <td>
                                <strong><?php echo sparrow_escape($product['product_name']); ?></strong>

                                <?php if (!empty($product['short_description'])): ?>
                                    <div class="muted">
                                        <?php echo sparrow_escape(substr($product['short_description'], 0, 120)); ?>
                                        <?php echo strlen($product['short_description']) > 120 ? '...' : ''; ?>
                                    </div>
                                <?php endif; ?>
                            </td>

                            <td><?php echo sparrow_escape($product['category']); ?></td>

                            <td>$<?php echo sparrow_escape(number_format((float) $product['price'], 2)); ?></td>

                            <td><?php echo (int) $product['quantity_available']; ?></td>

                            <td><?php echo !empty($product['is_featured']) ? 'Yes' : 'No'; ?></td>

                            <td>
                                <?php echo sparrow_escape(substr($product['meta_description'], 0, 120)); ?>
                                <?php echo strlen($product['meta_description']) > 120 ? '...' : ''; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </section>

    <?php

    sparrow_backyard_footer();
    exit;
} catch (Throwable $e) {
    header(
        'Location: ' . sparrow_url(
            '/backyard/import.php?shop_products_error=' . urlencode($e->getMessage())
        )
    );
    exit;
}