<?php

namespace App\Http\Controllers\Evo;

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

class EvoSupplierPricingController extends Controller
{
    public function index()
    {
        try {
            // $supplier_pricings = SupplierPricing::where('is_sent', '0')->latest()->get();

            // $supplier_pricings = SupplierPricing::where('is_sent', '0')
            //     ->latest()
            //     ->take(10)
            //     ->hidden('id', 'created_at')
            //     ->get();

            $supplier_pricings = SupplierPricing::where('is_sent', '1')
                ->latest()
                ->get()
                ->each(function ($item) {
                    // Hide unwanted fields
                    $item->makeHidden(['id', 'created_at']);

                    // Override `updated_at` with formatted datetime
                    $item->updated_at = $item->updated_at->format('Y-m-d H:i:s');
                });

            return response()->json([
                'status' => true,
                'data' => $supplier_pricings,
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'status' => false,
                'message' => 'Failed to retrieve supplier pricings.',
                'error' => $e->getMessage(),
            ], 500);
        }
    }


    public function updatePricesStatus(Request $request)
    {
        try {

            $supplier_pricings =  DB::table('supplier_pricings')
                ->where('is_sent', 1)
                ->update([
                    'is_sent' => 0,
                    'updated_at' => now(),
                ]);

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