<?php

namespace App\Http\Controllers\Feeds;

use App\Http\Controllers\Controller;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\StreamedResponse;

class FacebookCatalogFeedController extends Controller
{
    /**
     * Facebook Commerce Manager - Scheduled Feed (CSV)
     * URL example:
     *   https://your-domain.com/feeds/facebook/products.csv?token=YOUR_TOKEN
     */
    public function productsCsv(Request $request): StreamedResponse
    {
        $expectedToken = (string) config('services.facebook_catalog.token');
        $givenToken = (string) $request->query('token', '');

        // Simple token gate (so random people can't scrape your catalog easily)
        if (!empty($expectedToken) && !hash_equals($expectedToken, $givenToken)) {
            abort(403, 'Invalid feed token');
        }

        // CSV headers that Facebook accepts (Google-style catalog fields also work here)
        $headers = [
            'id',
            'title',
            'description',
            'availability',
            'condition',
            'price',
            'sale_price',
            'link',
            'image_link',
            'additional_image_link',
            'brand',
            'inventory',
            'category',
        ];

        $currency = (string) config('services.facebook_catalog.currency', 'BDT');

        return response()->stream(function () use ($headers, $currency) {
            // NOTE: BOM helps CSV readers handle Bangla/Unicode safely
            echo "\xEF\xBB\xBF";

            $out = fopen('php://output', 'w');
            fputcsv($out, $headers);

            Product::query()
                ->with(['galleries:id,product_id,image', 'category:id,name', 'subcategory:id,name'])
                ->select([
                    'id', 'name', 'title', 'slug', 'description',
                    'price', 'discount_price', 'stock', 'brand_name',
                    'thumbnail', 'status', 'category_id', 'subcategory_id',
                ])
                ->orderBy('id')
                ->chunk(300, function ($products) use ($out, $currency) {
                    foreach ($products as $p) {
                        $availability = $p->status === 'in-stock' ? 'in stock' : 'out of stock';

                        $price = number_format((float) $p->price, 2, '.', '') . " {$currency}";
                        $salePrice = null;
                        if (!empty($p->discount_price) && (float) $p->discount_price > 0) {
                            $salePrice = number_format((float) $p->discount_price, 2, '.', '') . " {$currency}";
                        }

                        $productLink = route('details', $p->slug, true);

                        // Main image
                        $imageLink = $p->thumbnail_url; // accessor from Product model

                        // Additional images (comma separated)
                        $additionalImages = [];
                        foreach ($p->galleries as $g) {
                            $additionalImages[] = asset('storage/' . ltrim($g->image, '/'));
                        }
                        $additionalImages = implode(',', array_values(array_unique(array_filter($additionalImages))));

                        $categoryName = $p->category?->name ?? '';
                        $subCategoryName = $p->subcategory?->name ?? '';
                        $categoryPath = trim($categoryName . ($subCategoryName ? " > {$subCategoryName}" : ''));

                        // Facebook likes clean text. No HTML.
                        $desc = trim(strip_tags((string) $p->description));

                        $row = [
                            $p->id,                                 // id
                            (string) ($p->title ?: $p->name),        // title
                            $desc,                                   // description
                            $availability,                            // availability
                            'new',                                   // condition
                            $price,                                  // price
                            $salePrice,                              // sale_price
                            $productLink,                            // link
                            $imageLink,                              // image_link
                            $additionalImages,                       // additional_image_link
                            (string) ($p->brand_name ?: ''),         // brand
                            (int) ($p->stock ?? 0),                  // inventory
                            $categoryPath,                           // category
                        ];

                        fputcsv($out, $row);
                    }
                });

            fclose($out);
        }, 200, [
            'Content-Type' => 'text/csv; charset=UTF-8',
            'Cache-Control' => 'no-store, no-cache, must-revalidate, max-age=0',
            'Pragma' => 'no-cache',
            'Content-Disposition' => 'inline; filename="facebook-products.csv"',
        ]);
    }
}
