<?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\DB;

class SupplierPricingController extends Controller
{

    public function index(Request $request)
    {
        try {
            $query = DB::table('supplier_pricings');

            if ($request->filled('ProductCode')) {
                $query->where('ProductCode', 'like', '%' . $request->ProductCode . '%');
            }

            if ($request->filled('ProductName')) {
                $query->where('ProductName', 'like', '%' . $request->ProductName . '%');
            }

            if ($request->filled('CategoryName')) {
                $query->where('CategoryName', 'like', '%' . $request->CategoryName . '%');
            }

            if ($request->has('is_sent')) {
                $query->where('is_sent', (bool)$request->is_sent);
            }

            $perPage = $request->get('per_page') ?? 15;
            // dd($perPage);
            $products = $query->paginate($perPage);

            // Add increment_by to each record
            $productsWithIncrement = collect($products->items())->map(function ($product) {
                $product->increment_by = 0.05;
                return $product;
            });

            return response()->json([
                'status' => true,
                'message' => 'Supplier pricing list',
                'data' => $productsWithIncrement,
                'pagination' => [
                    'current_page' => $products->currentPage(),
                    'per_page' => $products->perPage(),
                    'total' => $products->total(),
                    'last_page' => $products->lastPage(),
                    'next_page_url' => $products->nextPageUrl(),
                    'prev_page_url' => $products->previousPageUrl(),
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => false,
                'message' => 'Error fetching records',
                'error' => $e->getMessage(),
            ], 500);
        }
    }



    public function updatePrices(Request $request)
    {
        try {
            $data = $request->all();

            // Validate each item
            foreach ($data as $item) {
                if (!isset($item['ProductCode']) || !isset($item['SalePrice'])) {
                    return response()->json([
                        'status' => false,
                        'message' => 'Each item must have ProductCode and SalePrice',
                    ], 422);
                }
            }

            // Perform updates
            foreach ($data as $item) {
                DB::table('supplier_pricings')
                    ->where('ProductCode', $item['ProductCode'])
                    ->update([
                        'SalePrice' => $item['SalePrice'],
                        'is_sent' => '1',
                        'updated_at' => now(),
                    ]);
            }

            return response()->json([
                'status' => true,
                'message' => 'Sale prices updated successfully',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => false,
                'message' => 'Failed to update prices',
                'error' => $e->getMessage(),
            ], 500);
        }
    }




    public function getCategories()
    {
        try {
            $categories = DB::table('supplier_pricings')
                ->select('CategoryName')
                ->distinct()
                ->orderBy('CategoryName')
                ->pluck('CategoryName');

            return response()->json([
                'status' => true,
                'message' => 'Unique category list',
                'data' => $categories
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => false,
                'message' => 'Failed to fetch categories',
                'error' => $e->getMessage(),
            ], 500);
        }
    }


    // public function index(Request $request)
    // {
    //     try {
    //         $query = SupplierPricing::query();

    //         if ($request->filled('ProductCode')) {
    //             $query->where('ProductCode', 'like', '%' . $request->ProductCode . '%');
    //         }

    //         if ($request->filled('ProductName')) {
    //             $query->where('ProductName', 'like', '%' . $request->ProductName . '%');
    //         }

    //         if ($request->filled('CategoryName')) {
    //             $query->where('CategoryName', 'like', '%' . $request->CategoryName . '%');
    //         }

    //         if ($request->has('is_sent')) {
    //             $query->where('is_sent', (bool)$request->is_sent);
    //         }

    //         $perPage = $request->get('per_page', 1);
    //         $products = $query->paginate($perPage);

    //         // Add "increment_by" to each product
    //         $productsWithIncrement = collect($products->items())->map(function ($product) {
    //             $product->increment_by = 0.05;
    //             return $product;
    //         });

    //         return response()->json([
    //             'status' => true,
    //             'message' => 'Supplier pricing list',
    //             'data' => $productsWithIncrement, // this flattens the inner "data"
    //             'pagination' => [
    //                 'current_page' => $products->currentPage(),
    //                 'per_page' => $products->perPage(),
    //                 'total' => $products->total(),
    //                 'last_page' => $products->lastPage(),
    //                 'next_page_url' => $products->nextPageUrl(),
    //                 'prev_page_url' => $products->previousPageUrl(),
    //             ]
    //         ]);
    //     } catch (\Exception $e) {
    //         return response()->json([
    //             'status' => false,
    //             'message' => 'Error fetching records',
    //             'error' => $e->getMessage(),
    //         ], 500);
    //     }
    // }



    // public function index(Request $request)
    // {
    //     try {

    //         $query = SupplierPricing::query();

    //         // Optional filters
    //         if ($request->filled('ProductCode')) {
    //             $query->where('ProductCode', 'like', '%' . $request->ProductCode . '%');
    //         }

    //         if ($request->filled('ProductName')) {
    //             $query->where('ProductName', 'like', '%' . $request->ProductName . '%');
    //         }

    //         if ($request->filled('CategoryName')) {
    //             $query->where('CategoryName', 'like', '%' . $request->CategoryName . '%');
    //         }

    //         if ($request->has('is_sent')) {
    //             $query->where('is_sent', (bool)$request->is_sent);
    //         }

    //         // Paginate results (default 15, or as passed)
    //         $perPage = $request->get('per_page', 15);
    //         $supplierPricings = $query->paginate($perPage);

    //         return response()->json([
    //             'status' => true,
    //             'message' => 'Supplier pricing list',
    //             'data' => $supplierPricings,
    //         ]);
    //     } catch (\Exception $e) {
    //         return response()->json([
    //             'status' => false,
    //             'message' => 'Error fetching records',
    //             'error' => $e->getMessage(),
    //         ], 500);
    //     }
    // }


    public function saveSupplierPricings(Request $request)
    {
        try {
            $data = $request->all(); // Get the raw array

            if (!is_array($data)) {
                return response()->json([
                    'status' => false,
                    'message' => 'Invalid data format. Expected an array of price objects.',
                ], 422);
            }

            // Validate each item
            foreach ($data as $index => $item) {
                if (!isset($item['ProductCode']) || !isset($item['SalePrice'])) {
                    return response()->json([
                        'status' => false,
                        'message' => "Missing ProductCode or SalePrice at index $index.",
                    ], 422);
                }

                if (!is_numeric($item['SalePrice']) || $item['SalePrice'] < 0) {
                    return response()->json([
                        'status' => false,
                        'message' => "Invalid SalePrice at index $index.",
                    ], 422);
                }
            }

            // Update prices
            foreach ($data as $item) {
                Product::where('ProductCode', $item['ProductCode'])
                    ->update(['SalePrice' => $item['SalePrice']]);
            }

            return response()->json([
                'status' => true,
                'message' => 'Sale prices updated successfully.',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => false,
                'message' => 'Failed to update sale prices.',
                'error' => $e->getMessage(),
            ], 500);
        }
    }
}
