<?php

    namespace App\Http\Controllers;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Mail;
    use Illuminate\Support\Facades\File;
    use App\Mail\SendScreenshotMail;
    use App\Models\Jewelry;
    use Illuminate\Support\Facades\Validator;
    use App\Models\CustomProduct;    
    use App\Models\User; 
    use Illuminate\Support\Facades\DB;
    use Illuminate\Support\Facades\Log;
    
  
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

    class JewelryController extends Controller

    {   

    public function index()

    {
        $jewelry = Jewelry::all();
        return view('rdi_jewelry', compact('jewelry'));
    }

    public function getById(Request $request)

    {

        $id = $request->jewelry_id;

        $item = Jewelry::findOrFail($id);



        $shapeStockMap = Jewelry::whereNotNull('stock_id')

        ->select('shape', 'stock_id')

        ->get()

        ->groupBy('shape');

        $headStyles = Jewelry::select('head_style', 'stock_id')

        ->distinct()

        ->whereNotNull('head_style')

        ->whereNotNull('stock_id')

        ->get()

        ->groupBy('head_style');



        $shankStyles = Jewelry::select('shank_style', 'stock_id')

        ->distinct()

        ->whereNotNull('shank_style')

        ->whereNotNull('stock_id')

        ->get()

        ->groupBy('shank_style');



        $shankMetals = Jewelry::select('shank_metal', 'stock_id')

        ->distinct()

        ->whereNotNull('shank_metal')

        ->whereNotNull('stock_id')

        ->get()

        ->groupBy('shank_metal');



        $metalHeads = Jewelry::select('metal_head', 'stock_id')

        ->distinct()

        ->whereNotNull('metal_head')

        ->whereNotNull('stock_id')

        ->get()

        ->groupBy('metal_head');



         $ring_Sizes = Jewelry::whereNotNull('stock_id')

            ->pluck('size')

            ->unique()

            ->values()

            ->toArray(); // ✅ gives a clean array like ['3', '3.5', '4', '4.5', ...]

        $carat_Sizes = Jewelry::whereNotNull('stock_id')

            ->pluck('carat')

            ->unique()

            ->values()

            ->toArray();


        return view('rdi_jewelry', compact('item', 'headStyles', 'shankStyles', 'shankMetals', 'metalHeads','shapeStockMap', 'ring_Sizes','carat_Sizes'));



        // return response()->json([

        //     'jewelry_res' => $jewelry,

        //     'html' => $html

        // ]);

    }

    public function show($id)

    {

        $item = Jewelry::findOrFail($id);

    

        $shapeStockMap = Jewelry::whereNotNull('stock_id')

        ->select('shape', 'stock_id')

        ->get()

        ->groupBy('shape');

        $headStyles = Jewelry::select('head_style', 'stock_id')

        ->distinct()

        ->whereNotNull('head_style')

        ->whereNotNull('stock_id')

        ->get()

        ->groupBy('head_style');



        $shankStyles = Jewelry::select('shank_style', 'stock_id')

        ->distinct()

        ->whereNotNull('shank_style')

        ->whereNotNull('stock_id')

        ->get()

        ->groupBy('shank_style');



        $shankMetals = Jewelry::select('shank_metal', 'stock_id')

        ->distinct()

        ->whereNotNull('shank_metal')

        ->whereNotNull('stock_id')

        ->get()

        ->groupBy('shank_metal');



        $metalHeads = Jewelry::select('metal_head', 'stock_id')

        ->distinct()

        ->whereNotNull('metal_head')

        ->whereNotNull('stock_id')

        ->get()

        ->groupBy('metal_head');



        // $ring_Sizes = Jewelry::whereNotNull('stock_id')

        //     ->select('size', 'stock_id')

        //     ->get()

        //     ->groupBy('size')

        //     ->toArray(); 



        $ring_Sizes = Jewelry::whereNotNull('stock_id')

            ->pluck('size')

            ->unique()

            ->values()

            ->toArray();







        return view('rdi_jewelry', compact('item', 'headStyles', 'shankStyles', 'shankMetals', 'metalHeads','shapeStockMap', 'ring_Sizes'));

    }

    public function showByType(Request $request)
    {
        $type = $request->type; // 👈 yaha se aayega

        $item = Jewelry::where('type', $type)->first();

        $shapeStockMap = Jewelry::where('type', $type)
            ->whereNotNull('stock_id')
            ->select('shape', 'stock_id')
            ->get()
            ->groupBy('shape');

        $headStyles = Jewelry::where('type', $type)
            ->whereNotNull('head_style')
            ->whereNotNull('stock_id')
            ->select('head_style', 'stock_id')
            ->distinct()
            ->get()
            ->groupBy('head_style');

        $shankStyles = Jewelry::where('type', $type)
            ->whereNotNull('shank_style')
            ->whereNotNull('stock_id')
            ->select('shank_style', 'stock_id')
            ->distinct()
            ->get()
            ->groupBy('shank_style');

        $shankMetals = Jewelry::where('type', $type)
            ->whereNotNull('shank_metal')
            ->whereNotNull('stock_id')
            ->select('shank_metal', 'stock_id')
            ->distinct()
            ->get()
            ->groupBy('shank_metal');

        $metalHeads = Jewelry::where('type', $type)
            ->whereNotNull('metal_head')
            ->whereNotNull('stock_id')
            ->select('metal_head', 'stock_id')
            ->distinct()
            ->get()
            ->groupBy('metal_head');

        $ring_Sizes = Jewelry::where('type', $type)
            ->whereNotNull('stock_id')
            ->pluck('size')
            ->unique()
            ->values();

            
        $results = Jewelry::where('type', $type)->whereNotNull('stock_id')->get();

        // 2. HTML Render karein (Partial view se)
        // Hum pura data view mein pass kar rahe hain
        $html = view('partials.jewelry_results', [
            'results' => $results,
            'item' => $item,
            'headStyles' => $headStyles,
            'shankStyles' => $shankStyles
        ])->render();


        return response()->json([
            'status' => true,
            'item' => $item,
            'html' => $html,
            'shapeStockMap' => $shapeStockMap,
            'headStyles' => $headStyles,
            'shankStyles' => $shankStyles,
            'shankMetals' => $shankMetals,
            'metalHeads' => $metalHeads,
            'ring_Sizes' => $ring_Sizes,
        ]);
    }

    public function jewelry_filter(Request $request)

    {

        

        $query = Jewelry::query();

       

        $stockId = $request->stock_id;

        $cleanedStockId = preg_replace('/\d+/', '', $stockId);

 

        if ($request->shape) {

          

            $query->where('shape', $request->shape);

        }

        if ($request->stock_id) {

          

            $query->where('stock_id', 'LIKE', '%' . $cleanedStockId . '%');

        }

        if ($request->head_style) {

            $query->where('head_style', $request->head_style);

        }

        // if ($request->ring_size) {

        //     $query->where('size', $request->ring_size);

        // }

        if ($request->metal_head) {

            $query->where('metal_head', $request->metal_head);

        }

        if ($request->shank_style) {

            $query->where('shank_style', $request->shank_style);

        }

        if ($request->shank_metals) {

            $query->where('shank_metal', $request->shank_metals);

        }

        if ($request->jewelry_type) {

            $query->where('type', $request->jewelry_type);

        }



        $results = $query->get();

        

        //    dd(

        //         $query->toSql(),        // Raw SQL with placeholders

        //         $query->getBindings()   // The actual values that will be bound

        //     );

 



        $jewelry_res = [];    

        foreach ($results as $item) {

        

            $jewelry_res['jewelry_id'] = $item->id;

            $jewelry_res['jewelry_title'] = $item->shank_style . ' ' . $item->head_style;

            $jewelry_res['price_display'] = number_format($item->price, 2);

        }



            $html = view('partials.jewelry_results', compact('results'))->render();



            return response()->json(['html' => $html,'results_data' => $results,'jewelry_res' => $jewelry_res]);

    }

    public function email_send(Request $request)
    {
        // ✅ AJAX friendly validation
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'screenshot' => 'required'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status' => false,
                'message' => $validator->errors()->first()
            ], 422); // ❗ no redirect
        }

        try {
            $imageData = $request->screenshot;

            // ✅ Base64 clean
            $image = preg_replace('#^data:image/\w+;base64,#i', '', $imageData);
            $image = str_replace(' ', '+', $image);

            if (empty($image)) {
                return response()->json([
                    'status' => false,
                    'message' => 'Screenshot not found'
                ], 400);
            }

            // ✅ Folder
            $folderPath = public_path('screenshots/');
            if (!File::exists($folderPath)) {
                File::makeDirectory($folderPath, 0755, true);
            }

            // ✅ Save
            $imageName = 'screenshot_' . time() . '.png';
            File::put($folderPath . $imageName, base64_decode($image));

            // ✅ Send Email
            Mail::to($request->email)->send(new SendScreenshotMail($imageName));

            return response()->json([
                'status' => true,
                'message' => 'Email Sent Successfully'
            ]);

        } catch (\Exception $e) {

            return response()->json([
                'status' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }
 



public function createCustomProduct(Request $request)
{
    try {
        /*
        |--------------------------------------------------------------------------
        | 1. Validation
        |--------------------------------------------------------------------------
        */

        $validated = $request->validate([
            'shop_name'    => ['required', 'string'],

            'master_id'    => ['nullable'],
            'stock_id'     => ['nullable'],

            'jewelry_type' => ['required', 'string'],
            'shape'        => ['nullable', 'string'],
            'head_style'   => ['nullable', 'string'],
            'shank_style'  => ['nullable', 'string'],
            'metal_head'   => ['nullable', 'string'],
            'shank_metals' => ['nullable', 'string'],
            'ring_size'    => ['nullable'],
            'carat_size'   => ['nullable'],

            'html_link'    => ['nullable', 'string'],
            'image_url'    => ['nullable', 'string'],
            'price'        => ['nullable'],

            'selected_area_image' => ['nullable', 'string'],
        ]);

        /*
        |--------------------------------------------------------------------------
        | 2. Find Shopify shop
        |--------------------------------------------------------------------------
        */

        $shopName = $validated['shop_name'];

        $user = User::where('name', $shopName)->first();

        if (!$user) {
            return response()->json([
                'status'  => false,
                'message' => 'Shop not found for: ' . $shopName,
            ], 404);
        }

        /*
        |--------------------------------------------------------------------------
        | 3. Decode and save selected screenshot
        |--------------------------------------------------------------------------
        */

        $imagePath = null;
        $imageUrl = null;
        $imageBase64Raw = null;
        $extension = 'png';

        $selectedAreaImage = trim(
            $validated['selected_area_image'] ?? ''
        );

        if ($selectedAreaImage !== '') {

            if (
                preg_match(
                    '/^data:image\/([a-zA-Z0-9.+-]+);base64,/',
                    $selectedAreaImage,
                    $typeMatch
                )
            ) {
                $extension = strtolower($typeMatch[1]);

                if ($extension === 'jpeg') {
                    $extension = 'jpg';
                }

                $base64Data = substr(
                    $selectedAreaImage,
                    strpos($selectedAreaImage, ',') + 1
                );
            } else {
                $extension = 'png';
                $base64Data = $selectedAreaImage;
            }

            $allowedExtensions = [
                'png',
                'jpg',
                'webp',
            ];

            if (!in_array($extension, $allowedExtensions, true)) {
                $extension = 'png';
            }

            $base64Data = str_replace(
                ' ',
                '+',
                $base64Data
            );

            $decodedImage = base64_decode(
                $base64Data,
                true
            );

            if ($decodedImage !== false) {

                /*
                |--------------------------------------------------------------------------
                | Save inside public/assets/customproducts
                |--------------------------------------------------------------------------
                */

                $directory = public_path(
                    'assets/customproducts'
                );

                if (!is_dir($directory)) {
                    $directoryCreated = mkdir(
                        $directory,
                        0775,
                        true
                    );

                    if (
                        !$directoryCreated &&
                        !is_dir($directory)
                    ) {
                        throw new \RuntimeException(
                            'Unable to create directory: ' .
                            $directory
                        );
                    }
                }

                if (!is_writable($directory)) {
                    throw new \RuntimeException(
                        'Directory is not writable: ' .
                        $directory
                    );
                }

                $fileName =
                    Str::uuid()->toString() .
                    '.' .
                    $extension;

                $fullPath =
                    $directory .
                    DIRECTORY_SEPARATOR .
                    $fileName;

                $savedBytes = file_put_contents(
                    $fullPath,
                    $decodedImage
                );

                if ($savedBytes === false) {
                    throw new \RuntimeException(
                        'Unable to save image in public/assets/customproducts.'
                    );
                }

                $imagePath =
                    'assets/customproducts/' .
                    $fileName;

                $imageUrl = asset(
                    'assets/customproducts/' .
                    $fileName
                );

                $imageBase64Raw =
                    $base64Data;

            } else {
                Log::warning(
                    'createCustomProduct: selected_area_image base64 decode failed'
                );
            }
        }

        /*
        |--------------------------------------------------------------------------
        | 4. Normalize product-specific values
        |--------------------------------------------------------------------------
        */

        $jewelryType = strtolower(
            trim((string) ($validated['jewelry_type'] ?? ''))
        );

        $isRing = $jewelryType === 'ring';

        /*
         * Ring size is allowed only for Ring products.
         */
        $ringSize = $isRing
            ? trim((string) ($validated['ring_size'] ?? ''))
            : '';

        $ringSize = $ringSize !== ''
            ? $ringSize
            : null;

        /*
        |--------------------------------------------------------------------------
        | 5. Save product data locally
        |--------------------------------------------------------------------------
        */

        $customProduct = CustomProduct::create([
            'user_id' =>
                $user->id,

            'master_id' =>
                $validated['master_id'] ?? null,

            'stock_id' =>
                $validated['stock_id'] ?? null,

            'jewelry_type' =>
                $validated['jewelry_type'] ?? null,

            'shape' =>
                $validated['shape'] ?? null,

            'head_style' =>
                $validated['head_style'] ?? null,

            'shank_style' =>
                $validated['shank_style'] ?? null,

            'metal_head' =>
                $validated['metal_head'] ?? null,

            'shank_metals' =>
                $validated['shank_metals'] ?? null,

            /*
             * Save ring size only when Jewelry Type is Ring.
             */
            'ring_size' =>
                $ringSize,

            'carat_size' =>
                $validated['carat_size'] ?? null,

            'html_link' =>
                $validated['html_link'] ?? null,

            'image_url' =>
                $imageUrl
                ?: ($validated['image_url'] ?? null),

            'image_path' =>
                $imagePath,

            'price' =>
                $validated['price'] ?? '0.00',
        ]);

        /*
        |--------------------------------------------------------------------------
        | 5. Product title
        |--------------------------------------------------------------------------
        */

        $title = trim(
            ($validated['shank_style'] ?? '') .
            ' ' .
            ($validated['head_style'] ?? '')
        );

        if ($title === '') {
            $title = 'Custom 360 Product';
        }

        /*
        |--------------------------------------------------------------------------
        | 6. Shopify description
        |--------------------------------------------------------------------------
        | Add an LI only when that field has a value.
        | Ring Size is added only when Jewelry Type is Ring.
        |--------------------------------------------------------------------------
        */

        $descriptionFields = [
            'Jewelry Type' =>
                trim((string) ($validated['jewelry_type'] ?? '')),

            'Shape' =>
                trim((string) ($validated['shape'] ?? '')),

            'Head Style' =>
                trim((string) ($validated['head_style'] ?? '')),

            'Shank Style' =>
                trim((string) ($validated['shank_style'] ?? '')),

            'Head Metal' =>
                trim((string) ($validated['metal_head'] ?? '')),

            'Band Metal' =>
                trim((string) ($validated['shank_metals'] ?? '')),

            'Carat Size' =>
                trim((string) ($validated['carat_size'] ?? '')),

            'Stock ID' =>
                trim((string) ($validated['stock_id'] ?? '')),
        ];

        /*
         * Ring Size must appear only for Ring products.
         */
        if ($isRing && !empty($ringSize)) {
            $descriptionFields =
                array_slice($descriptionFields, 0, 6, true)
                + ['Ring Size' => $ringSize]
                + array_slice($descriptionFields, 6, null, true);
        }

        $descriptionListItems = '';

        foreach ($descriptionFields as $label => $value) {

            if ($value === '') {
                continue;
            }

            $descriptionListItems .=
                '<li><strong>' .
                e($label) .
                ':</strong> ' .
                e($value) .
                '</li>';
        }

        $bodyHtml =
            '<p>Custom-built jewelry product.</p>';

        if ($descriptionListItems !== '') {
            $bodyHtml .=
                '<ul>' .
                $descriptionListItems .
                '</ul>';
        }

        /*
        |--------------------------------------------------------------------------
        | 7. Shopify product payload
        |--------------------------------------------------------------------------
        */

        $product = [
            'title' =>
                $title,

            'body_html' =>
                $bodyHtml,

            'vendor' =>
                'Custom360 Builder',

            'product_type' =>
                'Custom Jewelry',

            'tags' =>
                implode(',', [
                    'custom360',
                    $validated['jewelry_type'] ?? '',
                    $validated['shape'] ?? '',
                    $validated['shank_style'] ?? '',
                ]),

            /*
             * Variants and options are attached below conditionally.
             */
        ];

        /*
        |--------------------------------------------------------------------------
        | Build Shopify variant/options conditionally
        |--------------------------------------------------------------------------
        */

        $variant = [
            'price' =>
                $validated['price'] ?? '0.00',

            'sku' =>
                !empty($validated['stock_id'])
                    ? $validated['stock_id']
                    : 'C360-' . $customProduct->id,
        ];

        $shopifyOptions = [];
        $optionPosition = 1;

        /*
         * Ring Size exists in Shopify only for Ring products.
         */
        if ($isRing && !empty($ringSize)) {

            $variant['option' . $optionPosition] =
                $ringSize;

            $shopifyOptions[] = [
                'name' => 'Ring Size',
            ];

            $optionPosition++;
        }

        $caratSize = trim(
            (string) ($validated['carat_size'] ?? '')
        );

        if ($caratSize !== '') {

            $variant['option' . $optionPosition] =
                $caratSize;

            $shopifyOptions[] = [
                'name' => 'Carat Size',
            ];
        }

        /*
         * Shopify requires a variant title option when no custom options exist.
         */
        if (empty($shopifyOptions)) {

            $variant['option1'] =
                'Default Title';

        } else {

            $product['options'] =
                $shopifyOptions;
        }

        $product['variants'] = [
            $variant,
        ];

        /*
        |--------------------------------------------------------------------------
        | 8. Add Shopify image
        |--------------------------------------------------------------------------
        */

        $productImages = [];

        /*
        |--------------------------------------------------------------------------
        | Selected screenshot as Base64 attachment
        |--------------------------------------------------------------------------
        */

        if ($imageBase64Raw !== null) {
            $productImages[] = [
                'attachment' =>
                    $imageBase64Raw,

                'filename' =>
                    'selected-area-' .
                    $customProduct->id .
                    '.' .
                    $extension,

                'alt' =>
                    $title,
            ];
        }

        /*
        |--------------------------------------------------------------------------
        | External image fallback
        |--------------------------------------------------------------------------
        */

        $fallbackImageUrl = trim(
            $validated['image_url'] ?? ''
        );

        if (
            $imageBase64Raw === null &&
            $fallbackImageUrl !== '' &&
            filter_var(
                $fallbackImageUrl,
                FILTER_VALIDATE_URL
            )
        ) {
            $productImages[] = [
                'src' =>
                    $fallbackImageUrl,

                'alt' =>
                    $title,
            ];
        }

        if (!empty($productImages)) {
            $product['images'] =
                $productImages;
        }

        $data = [
            'product' => $product,
        ];

        Log::info(
            'Shopify custom Ring payload',
            [
                'custom_product_id' =>
                    $customProduct->id,

                'has_selected_area_image' =>
                    $imageBase64Raw !== null,

                'image_path' =>
                    $imagePath,

                'image_url' =>
                    $imageUrl,
            ]
        );

        /*
        |--------------------------------------------------------------------------
        | 9. Shopify API request
        |--------------------------------------------------------------------------
        */

        $response = $user->api()->rest(
            'POST',
            '/admin/api/2024-01/products.json',
            $data
        );

        /*
        |--------------------------------------------------------------------------
        | FIX: Convert complete Shopify response to array
        |--------------------------------------------------------------------------
        */

        if (is_array($response)) {
            $responseArray = $response;
        } else {
            $responseArray = json_decode(
                json_encode($response),
                true
            );
        }

        /*
        |--------------------------------------------------------------------------
        | Sometimes body may be returned as JSON string
        |--------------------------------------------------------------------------
        */

        if (
            isset($responseArray['body']) &&
            is_string($responseArray['body'])
        ) {
            $decodedBody = json_decode(
                $responseArray['body'],
                true
            );

            if (json_last_error() === JSON_ERROR_NONE) {
                $responseArray['body'] =
                    $decodedBody;
            }
        }

        /*
        |--------------------------------------------------------------------------
        | FIX: Product is available inside body.product
        |--------------------------------------------------------------------------
        */

        $shopifyProduct =
            $responseArray['body']['product']
            ?? $responseArray['product']
            ?? null;

        $statusCode = (int) (
            $responseArray['status']
            ?? 0
        );

        Log::info(
            'Shopify create product response',
            [
                'status_code' =>
                    $statusCode,

                'product_id' =>
                    $shopifyProduct['id']
                    ?? null,

                'response' =>
                    $responseArray,
            ]
        );

        /*
        |--------------------------------------------------------------------------
        | Shopify success status: 200 or 201
        |--------------------------------------------------------------------------
        */

        if (
            empty($shopifyProduct) ||
            !in_array(
                $statusCode,
                [200, 201],
                true
            )
        ) {
            Log::error(
                'Shopify product creation failed',
                [
                    'status' =>
                        $statusCode,

                    'response' =>
                        $responseArray,
                ]
            );

            return response()->json([
                'status' =>
                    false,

                'message' =>
                    'Shopify API error: ' .
                    json_encode(
                        $responseArray
                    ),
            ], 422);
        }

        /*
        |--------------------------------------------------------------------------
        | 10. Update local Shopify references
        |--------------------------------------------------------------------------
        */

        $customProduct->update([
            'shopify_product_id' =>
                $shopifyProduct['id'] ?? null,

            'shopify_handle' =>
                $shopifyProduct['handle'] ?? null,
        ]);

        /*
        |--------------------------------------------------------------------------
        | Get final Shopify image
        |--------------------------------------------------------------------------
        */

        $shopifyImageUrl =
            $shopifyProduct['image']['src']
            ?? $shopifyProduct['images'][0]['src']
            ?? null;

        /*
        |--------------------------------------------------------------------------
        | Get first Shopify variant ID
        |--------------------------------------------------------------------------
        */

        $variantId =
            $shopifyProduct['variants'][0]['id']
            ?? null;

        /*
        |--------------------------------------------------------------------------
        | Create Shopify checkout URL
        |--------------------------------------------------------------------------
        |
        | Example:
        | https://store-name.myshopify.com/cart/VARIANT_ID:1?checkout
        |
        */

        $checkoutUrl = null;

        if (!empty($variantId)) {

            $cleanShopName = trim($shopName);

            $cleanShopName = preg_replace(
                '#^https?://#i',
                '',
                $cleanShopName
            );

            $cleanShopName = rtrim(
                $cleanShopName,
                '/'
            );

            $checkoutUrl =
                'https://' .
                $cleanShopName .
                '/cart/' .
                $variantId .
                ':1?checkout';
        }

        Log::info(
            'Custom product checkout URL created',
            [
                'custom_product_id' =>
                    $customProduct->id,

                'shopify_product_id' =>
                    $shopifyProduct['id'] ?? null,

                'variant_id' =>
                    $variantId,

                'checkout_url' =>
                    $checkoutUrl,
            ]
        );

        return response()->json([
            'status' =>
                true,

            'message' =>
                'Ring product created successfully',

            'custom_product_id' =>
                $customProduct->id,

            'image_path' =>
                $imagePath,

            'image_url' =>
                $imageUrl,

            'shopify_image_url' =>
                $shopifyImageUrl,

            'shopify_product_id' =>
                $shopifyProduct['id'] ?? null,

            'variant_id' =>
                $variantId,

            'checkout_url' =>
                $checkoutUrl,

            'shopify' =>
                $shopifyProduct,
        ]);

    } catch (
        \Illuminate\Validation\ValidationException $e
    ) {
        return response()->json([
            'status' =>
                false,

            'message' =>
                'Validation failed',

            'errors' =>
                $e->errors(),
        ], 422);

    } catch (\Throwable $e) {
        Log::error(
            'createCustomProduct failed',
            [
                'message' =>
                    $e->getMessage(),

                'file' =>
                    $e->getFile(),

                'line' =>
                    $e->getLine(),

                'trace' =>
                    $e->getTraceAsString(),
            ]
        );

        return response()->json([
            'status' =>
                false,

            'message' =>
                'Server error: ' .
                $e->getMessage(),
        ], 500);
    }
}
       
}

