<?php

namespace App\Http\Controllers\Inventory;

use App\Group;
use App\Product;
use App\Purchase;
use App\Department;
use App\ProductUnit;
use App\Requisition;
use App\TempData;
use App\Supplier;
use App\RequisitionProduct;
use App\Quotation;
use App\QuotationProduct;
use App\PurchaseProduct;
use App\NewRequisition;
use App\NewRequisitionProduct;
use App\GoodsinProduct;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route;
use App\Models\Commercial\PiDetails;

class InventoryRequisitionController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }
    public function index(){
        // $requisitions = Requisition::where('unit_id', 15)->get();
        // foreach ($requisitions as $key => $requisition) {
        //     foreach ($requisition->requisition_products as $Productkey => $requisition_product) {

        //         $requisition_product_date = explode(' ',$requisition_product->created_at)[0];
        //         return $requisition_product_date;
        //         $last_goodsin = GoodsinProduct::where('goodsin_id','!=', 0)->where('unit_id', $requisition->unit_id)->where('product_id',$requisition_product->product_id)->whereHas('goodsin', function ($query) use ($requisition_product_date){
        //             $query->where('bill_date', '<=', $requisition_product_date);
        //         })->orderBy('id','desc')->first();
        //         $requisition_product->update(['last_goodsin_id'=> $last_goodsin ? $last_goodsin->id : '']);
        //     }
        // }
        $codes = Product::pluck('item_code','id');
        $items = Product::pluck('name','id');
        $departments = Department::pluck('name','id');
        $groups = Group::pluck('name','id');
        $units = ProductUnit::pluck('name','id');
        $factories = Auth::user()->units;
        return view('inventory.requisition.add-inventory-requisition',compact('codes','items','departments','groups','units','factories'));
    }

    public function getlc(Request $request)
        {  $cost_center = $request->cost_center;
             $lc = null;
             if ($cost_center=='lc'  ){
                $lc = PiDetails::whereNotNull('export_contact_no')->get();
                
             }
            return response()->json([
                'lc' => $lc
            ]);
        }

    public function lists(){
        return view('inventory.requisition.item-list');
    }

    public function addIndividualRequisition($id){
        $requisition = Requisition::find($id);
        return view('inventory.requisition.add-individual-requisition',compact('requisition'));
    }

    

    public function storeIndividualRequisition(Request $request){

        $past = RequisitionProduct::where('requisition_id',$request->requisition_id)->where('product_id',$request->product_id)->first();

        if(isset($past->id)){
            session()->flash('error','Already this item is added');
            return back();
        }
        $save['qty']=$request->qty;
        $save['note']=$request->note;
        $save['product_id']=$request->product_id;
        $save['requisition_id'] = $request->requisition_id;
        RequisitionProduct::create($save);
        return redirect('Inventory/view-single-purchase-requisition/'.$request->requisition_id);
    }

    public function addIndividualNewRequisitionProduct($id){
        $new_requisition = NewRequisition::find($id);
        $requisition = Requisition::find($new_requisition->requisition_id);
        return view('inventory.requisition.add-individual-new-requisition-product',compact('new_requisition'));
    }

    public function storeIndividualNewRequisitionProduct(Request $request){
        $new_requisition = NewRequisition::find($request->new_requisition_id);
        $past = RequisitionProduct::where('requisition_id',$request->requisition_id)->where('product_id',$request->product_id)->first();

        if(isset($past->id)){
            session()->flash('error','Already this item is added');
            return back();
        }

        if($request->qty > 0 && $request->qty >= $request->approved_qty){
            $checked_qty = $request->approved_qty;
            if($request->approved_qty == 0 || $request->approved_qty ==  null){
                $checked_qty = $request->qty;
            }
            $save['qty']=$request->qty;
            $save['checked_qty']=$checked_qty;
            $save['note']=$request->note;
            $save['product_id']=$request->product_id;
            $save['requisition_id'] = $request->requisition_id;
            $save['status'] = 1;
            $req = RequisitionProduct::create($save);

            if($req){
                $new_req = NewRequisitionProduct::create([
                    'qty'=>$checked_qty,
                    'checked_qty'=>$checked_qty,
                    'note'=>$request->note,
                    'product_id'=>$request->product_id,
                    'new_requisition_id'=>$new_requisition->id,
                    'user_id'=>Auth::id(),
                ]);
            }

            return redirect('Inventory/quotation-make/'.$request->new_requisition_id);
        }
    }

    public function deleteIndividualRequisition($id){
        $requisition_product = RequisitionProduct::find($id);
        $purchased = false;
        $new_requisitions = NewRequisition::where('requisition_id',$requisition_product->requisition_id)->get();
        // $delete = $requisition_product->delete();
            if(isset($new_requisitions[0]->id)){
                foreach ($new_requisitions as $key => $value) {
                    $new_requisition_products = NewRequisitionProduct::where('new_requisition_id',$value->id)->where('product_id',$requisition_product->product_id)->get();
                    foreach ($new_requisition_products as $productKey => $product) {
                        $purchase = PurchaseProduct::where('requisition_product_id', $product->id)->first();
                        if(isset($purchase->id)){
                            $purchased = true;
                            return response()->json(['success'=>false]);
                        }else{
                            QuotationProduct::where('requisition_product_id', $product->id)->delete();
                        }
                        
                    }
                }
                if(!$purchased){
                    foreach ($new_requisitions as $key => $value) {
                        NewRequisitionProduct::where('new_requisition_id',$value->id)->where('product_id',$requisition_product->product_id)->delete();
                    }
                }
            }
            if(!$purchased){
                $delete = $requisition_product->delete();
            }


            return response()->json(['success'=>true]);
    }

    public function editIndividualRequisition($id){
        $requisition_product = RequisitionProduct::find($id);
        $items = Product::pluck('name','id');
        return view('inventory.requisition.edit-individual-requisition',compact('requisition_product','items'));
    }

    /* product find according to product id start */
    public function findProduct(Request $request){
        $id = $request->id;
        $products = Product::findOrFail($id);
        $data['unit'] = $products->unit->name;
        $data['price'] = $products->price;
        echo json_encode($data);

    }
    /* product find according to product id end */


       public function storeTempRequisitionInfo(Request $request){

        $request['user_id']= Auth::user()->id;
        $request['unit_id']= Auth::user()->active_unit;
        $request['type'] = 1;
        $request['last_consume'] = null; //last two months consumtions
        $product = Product::find($request->product_id);
        $request['last_purchase_date'] = $product->last_purchase_date;// last product purchase date
        $request['last_purchase_price'] = $product->last_purchase_price; // last product purchase price
        $request['p_type'] = $request->p_type;
        $cost_center = $request->cost_c;
        if($cost_center=='lc'){
            $cost_center = $request->lc;
        }
        $request['cost_c'] = $cost_center;
        // dd($request->all());


        $exist = TempData::where('type',1)->where('unit_id',$request['unit_id'])->where('product_id',$request->product_id)->get();
        if($exist->count()>0){
            TempData::where('type',1)->where('unit_id',$request['unit_id'])->where('product_id',$request->product_id)->where('user_id',Auth::user()->id)->update(['qty'=>$request->qty,'p_type'=>$request->p_type,'cost_c'=>$request->cost_c]);
        }else{
             TempData::create($request->all());
        }
        echo json_encode(['success'=>1]);

    }

public function productLists(){
        $user = Auth::id();
        $unit = Auth::user()->active_unit;

        $products = TempData::query()->where('unit_id',$unit)->where('user_id',$user)->where('type',1)->get();
        $sl =0 ;

        foreach ($products as $product){
            $dataId = $product->id;
            $dataURL = route('inventory.requisition.item.remove');
            $curr_stock = QuotationProduct::where('product_id', $dataId)->sum('qty');
            $last_purchase_order_no = $product->last_purchase_order_no !=null ? $product->last_purchase_order_no : "";
            $last_purchase_qty = $product->last_purchase_qty !=null ? $product->last_purchase_qty : "";
            $last_purchase_date = $product->last_purchase_date !=null ? $product->last_purchase_date : "";
            $last_purchase_price = $product->last_purchase_price !=null ? $product->last_purchase_price : "";
            echo  '<tr>
                        <td>'.++$sl.'</td>
                        <td>'.($product->product->group  ? $product->product->group->name : "N/A").'</td>
                        <td>'.($product->product ? $product->product->item_code : "N/A").'</td>
                        <td>'.($product->product ? $product->product->name : "N/A").'</td>
                        <td>'.($product->product->brand ? $product->product->brand->name : "N/A").'</td>
                        <td>'.($product->product->unit ? $product->product->unit->name : "N/A").'</td>
                        <td>'.($product->cost_c=='overall' ? "Overall" : "LC NO: " .$product->cost_c).'</td>
                        <td>'.($product->p_type).'</td>
                        <td>'.$curr_stock.'</td>
                        <td> N / A</td>
                        <td>'.$product->qty.'</td>
                        <td>'.$last_purchase_order_no.'</td>
                        <td>'.$last_purchase_date.'</td>
                        <td>'.$last_purchase_qty.'</td>
                        <td>'.$last_purchase_price.'</td>
                        <td>'.$product->note.'</td>
                        <td> <button type="button" class="erase fa fa-trash-alt btn btn-danger" data-id="'.$dataId.'" data-url="'.$dataURL.'"></button> </td>
                </tr>';
        }
        // <td>'.($product->product->department ? $product->product->department->name : " N/A ").'</td>
    }

    public function removeItemFromList(Request $request){
        TempData::findOrFail($request->id)->delete();
    }


    /* purchase requisition store start */
        public function storePurchaseRequisition(Request $request){
        //return $request->all();
        $price = $qty = 0;
        $products = TempData::where('type',1)->where('unit_id',Auth::user()->active_unit)->get();
        if(count($products) > 0){
            foreach ($products as $product){
                $price+=$product->price;
                $qty+=$product->qty;
            }

            $request['requisition_id'] = getRequisitionId($request->unit_id);
            $request['qty'] = $qty;
            $request['price'] = $price;
            $request['invoice_no'] = substr(md5(time()),0,6)."1";
            $request['user_id'] = Auth::user()->id;
            $request['cost_c'] = $product->cost_c;
            $request['payment_mode'] = $product->p_type;

            $invoice_id = Requisition::create($request->all());
            $price = $qty = 0;

            foreach ($products as $product){
                $last_goodsin = GoodsinProduct::where('goodsin_id','!=', 0)->where(get_where())->where('product_id',$product->product_id)->orderBy('id','desc')->first();
                $save['price']=$product->price;
                $save['qty']=$product->qty;
                $save['note']=$product->note;
                $save['cost_c']=$product->cost_c;
                $save['payment_mode']=$product->p_type;
                $save['product_id']=$product->product_id;
                $save['requisition_id'] = $invoice_id->id;
                $save['last_goodsin_id'] = $last_goodsin ? $last_goodsin->id : '';
                RequisitionProduct::create($save);
                TempData::findOrFail($product->id)->delete();
            }
            echo json_encode(['success'=>1]);
        }else{
            echo json_encode(['failed'=>1]);
        }

    }

    /* purchase requisition store end */

    /* Purchase requisitions list show start */
    public function requisitions(){

        $requisitions = Requisition::where(get_where())->orderBy('unit_id')->latest()->get();
        return view('inventory.requisition.requisitions-inventory',compact('requisitions'));
    }
    /* Purchase requisitions list show End */

    public function deleteRequisition($id){

        $requisition = Requisition::find($id);
        $delete = $requisition->delete();
        if($delete){
            $new_requisitions = NewRequisition::where('requisition_id',$id)->get();
            if(isset($new_requisitions[0]->id)){
                NewRequisition::where('requisition_id',$id)->delete();
                foreach ($new_requisitions as $key => $value) {
                    NewRequisitionProduct::where('new_requisition_id', $value->id)->delete();
                }
            }
            $deleteProducts = RequisitionProduct::where('requisition_id',$id)->delete();
            if($deleteProducts){
                return response()->json(['success'=>true]);
            }
        }
        return response()->json(['success'=>false]);
    }

    /* Individual Requisition Visit for checking */

    public function singleRequisition($id){


        $requisition = Requisition::findOrFail($id);
        $suppliers = Supplier::all();
        $items = Product::all();
        return view('inventory.requisition.invoice-requisition',compact('requisition','suppliers','items'));
    }

    public function changeItem($data){
        $requisition_product_id = explode('&', $data)[0];
        $item_id = explode('&', $data)[1];

        $requisition_product = RequisitionProduct::find($requisition_product_id);
        if($requisition_product->product_id == $item_id){
            return back()->with('error', 'you have been provided same item');
        }
        $requisition_id = $requisition_product->requisition_id;
        $product_id = $requisition_product->product_id;

        $requisition_product->update(['product_id'=>$item_id]);

        

        $new_requisition = NewRequisition::where('requisition_id', $requisition_id)->get();
        if(isset($new_requisition[0]->id)){
            foreach ($new_requisition as $key => $value) {
                NewRequisitionProduct::where('new_requisition_id', $value->id)->where('product_id',$product_id)->update(['product_id'=>$item_id]);
                QuotationProduct::where('requisition_id', $value->id)->where('product_id',$product_id)->update(['product_id'=>$item_id]);
                PurchaseProduct::where('requisition_id', $value->id)->where('product_id',$product_id)->update(['product_id'=>$item_id]);
                GoodsinProduct::where('requisition_id', $value->id)->where('product_id',$product_id)->update(['product_id'=>$item_id]);
            }
        }
        

        return back()->with('success', 'Successfully changed the item');
    }

    public function singleRequisitionPrint($id){
        $requisition = Requisition::findOrFail($id);
        return view('inventory.requisition.invoice-requisition-print',compact('requisition'));
    }

    /* view approved items as list start */
    public function viewApprovedItems($id){
        $requisition = NewRequisition::findOrFail($id);
        return view('inventory.requisition.view-approved-requisition-items',compact('requisition'));
    }
    /* view approved items as list end */



    public function checkingApproval(Request $request,$id){
        if (isset($request->requisition_product_id)){

            $new_requisition = NewRequisition::create([
                    'requisition_id' => $id,
                    'cs_no' => getCSNumber(auth_unit()),
                    'invoice_no' => substr(md5(time()),0,6)."1",
                    'note' => $request->checking_note,
                    'check_user_id' => Auth::user()->id,
                    'user_id' => Auth::id(),
                    'unit_id' => auth_unit()?? null,
                    'sent_for' => $request->sent_for,
                    'purchased_status' => 0,
            ]);

            foreach ($request->requisition_product_id as $key => $requisition_product_table_id) {
                //update requisition product table
                DB::table('requisition_products')
                    ->where('id', $requisition_product_table_id)
                    ->update(['status' => 1,'qty'=>$request->req_qty[$requisition_product_table_id]]);

                //RequisitionProduct::query()->findOrFail($requisition_product_table_id)->fill($input)->save();
                $requisition_product = RequisitionProduct::find($requisition_product_table_id);

                NewRequisitionProduct::create([
                  'new_requisition_id' => $new_requisition->id,
                  'product_id' => $requisition_product->product_id,
                  'qty' => $request['qty'][$key] != null ? $request['qty'][$key] : $requisition_product->qty,
                  'user_id' => Auth::id(),
                  'sent_for' => $request->sent_for,
                ]);


            }


        }else{
            session()->flash('error','Please check at least one product ');
            return redirect()->back();
        }

        return redirect()->route('inventory.purchase-requisition.view');
    }


    /* after check item list start */
    public function AftercheckingItemLists(){

        $approved_requisitions = NewRequisition::query()->where(get_where())->latest()->paginate(10);

        return view('inventory.requisition.after-check-inventory-requisition',compact('approved_requisitions'));
    }


    /* after check item list End */




}
