<?php

namespace App\Http\Controllers;

use App\Models\MaterialProductCompositon;
use Illuminate\Http\Request;
use App\Models\ManufactureBOM;
use App\Models\ReversedBom;

class MaterialProductCompositonController 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)
    {       
        \DB::table('final_productions')->where('FinalProductionID', $request->product_id)->update([
            'product_code' => $request->Product_code
        ]);
        
        $getCodes = \DB::table('final_productions')->where('FinalProductionID', $request->product_id)->first();
        $getCodesComp = \DB::table('items')->where('id', explode(" - ", $request->product)[0])->first();
          
        
                // Get Manufacturing Price
        $checkManfactureBOM = \DB::table('manufacture_b_o_m_s')
              ->where('item_id', explode(" - ", $request->product)[0])->first();


        $data = new MaterialProductCompositon;
        $data -> product_id = $request->product_id;
        $data -> composition_id = explode(" - ", $request->product)[0];
        $data -> unit_measure = $request->unit_measure;
        $data -> cost = $checkManfactureBOM->estimated_cost * $request->unit_measure;
        $data -> product_name = explode(" - ", $request->product)[1];
        $data -> product_code = $getCodes->product_code;
        $data -> raw_material_code = $getCodesComp->item_code;
        $data->save();
            
          if ($checkManfactureBOM == null) {
              ManufactureBOM::Insert([
                  'item_id' => explode(" - ", $request->product)[0],
                  'estimated_cost' => 0
              ]);
          }
        
        return $request->product_id;


    }

    public function ReverseProductComposition()
    {   
        if (request('type') == "Restore BOM") {
            $check = ReversedBom::where('bom_id', request('comp_id'))->first();

            if (empty($check) || null) {
                return back()->with('statuspass', 'This Item Can\'t be restored');
            }else {
                $checkstatus = ReversedBom::where('bom_id', request('comp_id'))->first();
                if ($checkstatus->status == 1 &&  $checkstatus->type == "Returned Item") {
                      // Getting Branch Code
                    $branch_code = \DB::table('branches')->where('branch_name', request('branch'))->first();
                    $saleliite = \DB::table('kitchens')->where('kitchen_code', $branch_code->branch_code)->first();

                    $existing = \DB::table('item_stock_ledgers')->where('item_id', request('comp_id'))
                        ->where('station', $saleliite->kitchen_name)
                        ->whereDate('date', explode(" ", request('date'))[0])
                        ->update([
                            'item_sales' => \DB::raw('item_sales + ' . request('quantity')),
                            'item_closing_stock' => \DB::raw('(item_opening_stock + item_manufacturing + item_recieved + item_purchases) - (item_sales + item_issue + item_wastage + item_cons_manufacturing)')
                        ]);

                        $this->updateReversed();

                        return back()->with('status', 'BOM Restored Successfully');
                }elseif ($checkstatus->status == 1 &&  $checkstatus->type == "Wastage") {
                    $existing = \DB::table('item_stock_ledgers')->where('item_id', request('comp_id'))
                    ->where('station', $saleliite->kitchen_name)
                    ->whereDate('date', explode(" ", request('date'))[0])
                    ->update([
                        'item_sales' => \DB::raw('item_sales + ' . request('quantity')),
                        'item_wastage' => \DB::raw('item_wastage - ' . request('quantity')),
                        'item_closing_stock' => \DB::raw('(item_opening_stock + item_manufacturing + item_recieved + item_purchases) - (item_sales + item_issue + item_wastage + item_cons_manufacturing)')
                    ]);

                    $this->updateReversed();
                }
                else {
                    return back()->with('statuspass', 'This Item Can\'t be restored');
                }
            }
        }
        // wastages
        elseif (request('type') == "Wastage") {

                // Getting Branch Code
          $branch_code = \DB::table('branches')->where('branch_name', request('branch'))->first();
          $saleliite = \DB::table('kitchens')->where('kitchen_code', $branch_code->branch_code)->first();


            $this->checkRejected();
            $checkstatus = ReversedBom::where('bom_id', request('comp_id'))->first();
            if ($checkstatus->status == 1 &&  $checkstatus->type == "Wastage") {
                return back()->with('statuspass', 'Sorry, Item Can\'t be recoreded as wastage');
            }elseif ($checkstatus->status == 1 &&  $checkstatus->type == "Returned Item") {
                $existing = \DB::table('item_stock_ledgers')->where('item_id', request('comp_id'))
                ->where('station', $saleliite->kitchen_name)
                ->whereDate('date', explode(" ", request('date'))[0])
                ->update([
                    'item_wastage' => \DB::raw('item_wastage + ' . request('quantity')),
                    'item_closing_stock' => \DB::raw('(item_opening_stock + item_manufacturing + item_recieved + item_purchases) - (item_sales + item_issue + item_wastage + item_cons_manufacturing)')
                ]);

                $this->updateReversed();

            }else {
                
                $existing = \DB::table('item_stock_ledgers')->where('item_id', request('comp_id'))
                ->where('station', $saleliite->kitchen_name)
                ->whereDate('date', explode(" ", request('date'))[0])
                ->update([
                    'item_sales' => \DB::raw('item_sales - ' . request('quantity')),
                    'item_wastage' => \DB::raw('item_wastage + ' . request('quantity')),
                    'item_closing_stock' => \DB::raw('(item_opening_stock + item_manufacturing + item_recieved + item_purchases) - (item_sales + item_issue + item_wastage + item_cons_manufacturing)')
                ]);
            }

            $this->updateReversed();

         return back()->with('status', 'BOM Trashed Successfully');
        }

        else {
        $this->checkRejected();
        $checkstatus = ReversedBom::where('bom_id', request('comp_id'))->first();
        if ($checkstatus->status == 1 && $checkstatus->type == "Returned Item") {
            return back()->with('statuspass', 'Sorry, Bom Can\'t be reversed');
        }
        
         // Getting Branch Code
          $branch_code = \DB::table('branches')->where('branch_name', request('branch'))->first();
          $saleliite = \DB::table('kitchens')->where('kitchen_code', $branch_code->branch_code)->first();

         $existing = \DB::table('item_stock_ledgers')->where('item_id', request('comp_id'))
            ->where('station', $saleliite->kitchen_name)
            ->whereDate('date', explode(" ", request('date'))[0])
            ->update([
                'item_sales' => \DB::raw('item_sales - ' . request('quantity')),
                'item_closing_stock' => \DB::raw('(item_opening_stock + item_manufacturing + item_recieved + item_purchases) - (item_sales + item_issue + item_wastage + item_cons_manufacturing)')
            ]);

        $this->updateReversed();

         return back()->with('status', 'BOM Reversed Successfully');
        }
    }


    public function updateReversed()
    {
        ReversedBom::where('bom_id', request('comp_id'))->update([
            'status' => 1,
            'reversed_by' => auth()->id(),
            'type' => request('type'),
        ]);
    }


    public function checkRejected()
    {
        $check = ReversedBom::where('bom_id', request('comp_id'))
        ->first();

        if (empty($check) || Null) {
            ReversedBom::create([
                'bom_id' => request('comp_id'),
                'product_id' => request('product_id'),
                'type' => request('type'),
                'status' => 0,
            ]);
        }
    }



    public function composition($id)
    {
        return \DB::table('material_product_compositons')->where('product_id', $id)->get();
    }


     public function destroy(MaterialProductCompositon $materialProductCompositon)
    {
        $materialProductCompositon->delete();
        return back()->with('status', "Product Composition Removed Successfully");
    }
}
