<?php

namespace App\Http\Controllers\Product;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\ProductPrice;
use App\Models\VoucherType;
use Carbon\Carbon;
use Illuminate\Validation\Rule;

class ProductBatchController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {
        $productId = $request->productId;
        return view('product-batches.create',compact('productId'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $batch            = $request->batch;
        $productId        = $request->product_id;
        
        $validator = \Validator::make($request->all(), [
            'batch'          => 'required',
            'mrp'            => 'required',
        ]);
        $checkBatch = ProductPrice::where(['product_id'=>$productId,'batch'=>trim($batch)])->first();
        if(isset($checkBatch))
        {
            return response()->json([
                'success' => false,
                'message' => 'Batch Name is Already Exist This Product',
                'data'    => []
            ]);
        }
       

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }
            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }
        $month            = $request->exp_month;
        $year             = $request->exp_year;
        $mrp              = $request->mrp;
        $sale_price       = $request->sale_price;
        $purchase_price   = $request->purchase_price;
       
        $exp_date         = '';
        if($month && $year)
        {
            $dates = Carbon::create($year, $month, 1);
            $exp_date = $dates->endOfMonth()->format('Y-m-d');
        }

       $data=['batch'           =>  strtoupper(trim($batch)),
              'mrp'             =>  $mrp,
              'sale_price'      =>  $sale_price,
              'purchase_price'  =>  $purchase_price,
              'product_id'      =>  $productId,
              'exp_date'        =>  $exp_date
    ];

        $price = ProductPrice::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success'   => true,
                'message'   => 'Batch has been created successfully',
                'batchId'   => $price->id,
                'productId' => $productId,
            ]);
        }
        return redirect()->back()
            ->with('success','Batch has been created successfully');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Request $request)
    {
        $id = $request->batch_id;
        $price = ProductPrice::find($id);

        return view('product-batches.edit', compact('price','id'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'batch'          => 'required',
            'mrp'            => 'required',

        ]);
        $batch            = $request->batch;
        $priceId          = $request->price_id;
        $productPrice = ProductPrice::find($priceId);
        $productId = $productPrice->product_id;

        $checkBatch = ProductPrice::where(['product_id'=>$productId,'batch'=>trim($batch)])->whereNot('id',$priceId)->first();
        if(isset($checkBatch))
        {
            return response()->json([
                'success' => false,
                'message' => 'Batch Name is Already Exist This Product',
                'data'    => []
            ]);
        }

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }
            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $month            = $request->exp_month;
        $year             = $request->exp_year;
        
        $mrp              = $request->mrp;
        $sale_price       = $request->sale_price;
        $purchase_price   = $request->purchase_price;
       
        $exp_date         = '';
        if($month && $year)
        {
            $dates = Carbon::create($year, $month, 1);
            $exp_date = $dates->endOfMonth()->format('Y-m-d');
        }
        

        $data=['batch'          =>  strtoupper(trim($batch)),
              'mrp'             =>  $mrp,
              'sale_price'      =>  $sale_price,
              'purchase_price'  =>  $purchase_price,
              'exp_date'        =>  $exp_date
    ];

        $price = $productPrice->update($data);

        if ($request->ajax()) {
            return response()->json([
                'success'   => true,
                'message'   => 'Batch has been update successfully',
                'batchId'   => $priceId,
                'productId' => $productPrice->product_id,
            ]);
        }
        return redirect()->back()
            ->with('success','Batch has been update successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

   
    public function getBatchWisePriceInformation(Request $request)
    {
        $productId  = $request->input('productId');
        $moduleCode = $request->input('moduleCode')??'PURCHASE';

        $purchaseVoucher = VoucherType::select(['default_price_type'])->where(['code'=>$moduleCode])->first();

        if($purchaseVoucher->default_price_type=='MRP')
        {
            $productPrice ='product_prices.mrp as mrp';
        }
        elseif($purchaseVoucher->default_price_type=='Purchase Price')
        {
            $productPrice ='product_prices.purchase_price as mrp';
        }
        elseif($purchaseVoucher->default_price_type=='WholeSale Price')
        {
            $productPrice ='product_prices.wholesale_price as mrp';
        }
        elseif($purchaseVoucher->default_price_type=='Discounted/Sale Price(DP)')
        {
            $productPrice ='product_prices.sale_price as mrp';
        }
        elseif($purchaseVoucher->default_price_type=='Min. Sale Price')
        {
            $productPrice ='product_prices.min_sale_price as mrp';
        }
        elseif($purchaseVoucher->default_price_type=='Manufacturing Cost')
        {
            $productPrice ='product_prices.mfg_cost as mrp';
        }

        $batch = ProductPrice::select(['id','batch','exp_date',$productPrice])
                    ->where(['product_id'=>$productId,'status'=>'1'])
                    ->orderBy('id','desc')->get();
        $data=[];
        foreach($batch as $key => $row)
        {
            $currentStock = getCurrentStock($productId,$row->id);
            $data[]=['id'           => $row->id,
                     'batch'        => $row->batch,
                     'exp_date'     => $row->exp_date,
                     'mrp'          => $row->mrp,
                    'current_stock' =>$currentStock??0];
        }
        if ($data) {
            return response()->json(['batchInfo' => $data]);
        } else {
            return response()->json(['error' => 'Batch information not found'], 404);
        }
    }

}
