<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\SupplierPricing;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class SupplierProductController extends Controller
{
    // supplier add new product


    public function add_new_product(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'CategoryName' => 'required',
            'ProductName' => 'required',
            'SalePrice' => 'required|numeric',
            'ShortName' => 'nullable',
            'ProductDescription' => 'nullable',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status' => false,
                'message' => 'Validation Error',
                'errors' => $validator->errors(),
            ], 422);
        }

        try {
            // Get max ProductCode from supplier_pricings and increment by 1
            // $maxProductCode = SupplierPricing::max('ProductCode');
            // dd($maxProductCode);
            // $newProductCode = $maxProductCode ? $maxProductCode + 1 : 1000; // default starting code if none exists

            // Get the current max ProductCode from both tables
            $maxSupplierCode = SupplierPricing::selectRaw('MAX(CAST(ProductCode AS UNSIGNED)) as max_code')->value('max_code');
            // dd($maxSupplierCode);

            $maxProductCode = Product::selectRaw('MAX(CAST(ProductCode AS UNSIGNED)) as max_code')->value('max_code');
            // dd($maxProductCode);

            $maxCode = max([$maxSupplierCode ?? 0, $maxProductCode ?? 0]);
            // dd($maxCode);

            $newProductCode = $maxCode + 1;
            // dd($newProductCode);
            // Ensure uniqueness
            while (
                SupplierPricing::where('ProductCode', $newProductCode)->exists() ||
                Product::where('ProductCode', $newProductCode)->exists()
            ) {
                $newProductCode++;
            }


            // dd($newProductCode);
            // Check if product already exists
            $existingPricing = SupplierPricing::where('ProductCode', $newProductCode)->first();
            // dd($existingPricing);
            if ($existingPricing) {
                return response()->json(['status' => false, 'message' => 'Supplier Product already exists'], 200);
            }

            // Create the supplier pricing record
            SupplierPricing::create([
                'ProductCode' => $newProductCode,
                'CategoryName' => $request->CategoryName,
                'ProductName' => $request->ProductName,
                'SalePrice' => $request->SalePrice,
                'ShortName' => $request->ShortName ?? '',
                'ProductDescription' => $request->ProductDescription ?? '',
                'is_sent' => 1,
                'is_new' => 1,
            ]);

            // dd($newProductCode);

            // Check if product already exists in the products table
            $existingProduct = Product::where('ProductCode', $newProductCode)->first();
            if ($existingProduct) {
                return response()->json(['status' => false, 'message' => 'Product already exists'], 200);
            }

            // Add 40% margin to the SalePrice
            $finalPrice = round($request->SalePrice * 1.4, 2); // rounded to 2 decimals

            // Create the product with 40% added SalePrice
            Product::create([
                'ProductCode' => $newProductCode,
                'CategoryName' => $request->CategoryName,
                'ProductName' => $request->ProductName,
                'SalePrice' => $finalPrice,
                'ShortName' => $request->ShortName ?? '',
                'ProductDescription' => $request->ProductDescription ?? '',
            ]);

            return response()->json(['status' => true, 'message' => 'Product created successfully'], 200);
        } catch (\Exception $e) {
            return response()->json([
                'status' => false,
                'message' => 'Something went wrong',
                'error' => $e->getMessage()
            ], 500);
        }
    }




    // public function add_new_product(Request $request)
    // {

    //     // dd(auth()->user());

    //     $validator = Validator::make($request->all(), [
    //         'ProductCode' => 'required',
    //         'CategoryName' => 'required',
    //         'ProductName' => 'required',
    //         'SalePrice' => 'required|numeric',
    //         // 'SupplierName' => 'required',
    //         // 'ShortName' => 'required',
    //         // 'ProductDescription' => 'required',
    //     ]);

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


    //     // Check if supplier pricing already exists
    //     $existingPricing = SupplierPricing::where('ProductCode', $request->ProductCode)
    //         // ->where('SupplierName', auth()->user()->name) // Assuming the supplier name
    //         ->first();

    //     if ($existingPricing) {
    //         return response()->json(['status' => false, 'message' => 'Product already exists'], 200);
    //     }


    //     // Create the supplier pricing record

    //     SupplierPricing::create([
    //         'ProductCode' => $request->ProductCode,
    //         'CategoryName' => $request->CategoryName,
    //         'ProductName' => $request->ProductName,
    //         'SalePrice' => $request->SalePrice,
    //         // 'SupplierName' => auth()->user()->name, // Assuming the supplier name is the authenticated user's name
    //         'ShortName' => $request->ShortName ?? '',
    //         'ProductDescription' => $request->ProductDescription ?? '',
    //         'is_sent' => 1, // Default value for is_sent
    //         'is_new' => 1, // Assuming new products are marked as is_new
    //     ]);



    //     // Check if product already exists
    //     $existingProduct = Product::where('ProductCode', $request->ProductCode)->first();
    //     if ($existingProduct) {
    //         return response()->json(['status' => false, 'message' => 'Product already exists'], 200);
    //     }

    //     // If product does not exist, create it
    //     $productData = [
    //         'ProductCode' => $request->ProductCode,
    //         'CategoryName' => $request->CategoryName,
    //         'ProductName' => $request->ProductName,
    //         'SalePrice' => $request->SalePrice,
    //         // 'SupplierName' => auth()->user()->name, // Assuming the supplier name is the authenticated user's name
    //         'ShortName' => $request->ShortName ?? '',
    //         'ProductDescription' => $request->ProductDescription ?? '',
    //     ];



    //     // Create the product
    //     Product::create($productData);

    //     return response()->json(['status' => true, 'message' => 'Product created successfully'], 200);
    // }



}
