<?php

namespace App\Http\Controllers\Inventory;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Requests\InventoryRequests\GrnRequest;
use App\Inventory\PurchaseOrder;
use App\Inventory\Item;
use App\Inventory\Payable;
use App\Inventory\ReceivingNote;
use App\Inventory\ProjectStock;
use App\Inventory\Stock;
use App\Inventory\BillOfQuantity;
use App\Inventory\BOQItems;
use App\User;
use App\Branch;
use Crypt;
use PDF;
use Illuminate\Contracts\Encryption\DecryptException;


class ReceivingNoteController extends Controller
{
    //

    public function view()
    {
      $purchase_order = new PurchaseOrder;
      $grn            = new ReceivingNote;
      $branch_obj = new Branch;
      $item = new Item;
      $branch    =  $branch_obj->getBranchList();
      $user = new User;
      $type2 = ['Product'];
      //$vendor_type = new VendorType;


      $user_list = $user->getUserListByType(['Supplier']);

      $purchase_order_list = $purchase_order->getAllPurchaseOrders();
      $purchase_order_list = $purchase_order_list->where('status' , "Approved");

      $grn_list            = $grn->getAllGrn();
      $all_grn = $grn_list;
      $grn_list = $grn_list->where('status', "Approved");
      $product_list = $item->getItemListByType($type2);

          return view('inventory_module.receiving_note.search_po_grn' ,
            [
              'po_numbers'     => $purchase_order_list,
              'grn_list'       => $grn_list,
              'branch' => $branch,
              'user_list' =>$user_list,
              'all_grn' =>$all_grn,
              'product_list' =>$product_list
            ]);
        }

        public function getPOList($id)
        {

          $id = decrypt($id);
          $purchase_order = new PurchaseOrder;
          $purchase_order_list = $purchase_order->getAllPurchaseOrdersProject($id);
          $purchase_order_list = $purchase_order_list->where('status' , "Approved");
          $userarr = [];
          $view = '<option value="'.Crypt::encrypt(0).'">Select Vendor</option>';
          foreach ($purchase_order_list as $rows)
          {
            //dd($rows->user_id);
            if(in_array($rows->user_id, $userarr))
            {

            }
            else {
              $view .= '<option  value="'.Crypt::encrypt($rows->user_id).'">'.$rows->user->name.'</option>';
              $userarr[] = $rows->user_id;
            }

          }
          return $view;

            }

            public function getPOListvendor($id)
            {

              $id = decrypt($id);
              $purchase_order = new PurchaseOrder;
              $purchase_order_list = $purchase_order->getAllPurchaseOrdersVendor($id);
              $purchase_order_list = $purchase_order_list->where('status' , "Approved");
              $view = '<option value="0">Select Item </option>';
              foreach ($purchase_order_list as $rows)
              {
                $po_no = PurchaseOrder::where('p_number', $rows->p_number)->get();
                $t_number = 0;
                foreach($po_no as $pn)
                {
                  $grn_total = ReceivingNote::where('purchase_order_id', $pn->id)->first();
                  if(!$grn_total)
                  {
                    $t_number = 1;
                  }
                  else{
                  $grn_t = $grn_total->total_quantity;
                  $grn_rec = ReceivingNote::where('purchase_order_id', $pn->id)->sum('accepted_quantity');
                  if($grn_t != $grn_rec)
                  {
                    $t_number = 1;
                  }
                }
              }
                  //$view .= '<option  value="'.$rows->p_number.'">'.$rows->p_number.'</option>';
                if($t_number == 1)
                {
                  $view .= '<option  value="'.$rows->p_number.'">'.$rows->p_number.'</option>';
                }

              }
              return $view;

                }

                public function getPOListproduct($id)
                {

                  $id = decrypt($id);
                  $boqitems = Boqitems::where('item_id', $id)->get();
                  //$purchase_order = new PurchaseOrder;
                  // $purchase_order_list = $purchase_order->getAllPurchaseOrdersVendor($id);
                  // $purchase_order_list = $purchase_order_list->where('status' , "Approved");
                  $view = '<option value="0">Select PO </option>';
                  if($boqitems)
                  {
                  foreach ($boqitems as $rows)
                  {
                    $purchase_order = PurchaseOrder::where('b_o_q_item_id', $rows->id)->first();
                    if($purchase_order)
                    {
                      $grn_total = ReceivingNote::where('purchase_order_id', $purchase_order->id)->first();
                      if(!$grn_total)
                      {
                        $view .= '<option  value="'.$purchase_order->p_number.'">'.$purchase_order->p_number.'</option>';

                      }
                      else
                      {
                      $grn_t = $grn_total->total_quantity;

                      $grn_rec = ReceivingNote::where('purchase_order_id', $purchase_order->id)->sum('accepted_quantity');

                      if($grn_t != $grn_rec)
                      {
                      $view .= '<option  value="'.$purchase_order->p_number.'">'.$purchase_order->p_number.'</option>';
                      }
}
                    }


                  }
                  }

                  return $view;

                    }


    public function generateGrn(GrnRequest $request)
    {
      $form_collect  = $request->input();
      $po_number = $form_collect['po_number'];
      $user = new User;
        try
        {
              $po = new PurchaseOrder;
              $po_detail = $po->getPObyNoAll($po_number);
              if(isset($po_detail[0]->id))
              {
                $employee_list = $user->getUserListByType(['Employee']);
                parent::setLogMessage('GRN with PO"'.$po_detail[0]->$po_number.'" has been generate');
                //parent::successMessage('GRN Generated.',parent::getLogMessage());
                return view('inventory_module.receiving_note.show_notes',
                [
                  'po_detail' => $po_detail,
                  'employee_list' => $employee_list,
                ]
            );
              }
          else{
            parent::errorMessage('PO with this number not found.');
              return redirect()->back();
            }
        }
        catch(DecryptException $e)
        {

        }
    }

    public function grnDetail($id)
    {
      try
      {
            $id        = decrypt($id);
            $grn       = new ReceivingNote;
            $po_detail = $po->getPObyNoAll($id);



            return redirect()->back();
      }
      catch(DecryptException $e)
      {
      }
    }

  public function showInvoiceModal($id)
  {
      if(\Request::ajax())
      {
          $data = '';

          try
          {
              $id               = decrypt($id);
              $count            = 0;

              $grn =  new ReceivingNote;

              $curr_grn = $grn->getGrnById($id);

              if(isset($curr_grn->id))
              {

                $data = view('inventory_module.receiving_note.modals.invoice_modal',[
                  'curr_grn' => $curr_grn,


                ]);
              }





          }
          catch (DecryptException $e)
          {

          }

          return $data;
      }

      return redirect()->back();
  }

    public function commitGrn(GrnRequest $request)
    {
      $form_collect  = $request->input();

      $a_u = \Auth::User();
      $au_id = $a_u->id;
      $po_number = $form_collect['po_number'];
      $form_grn = [];
        try
        {
              $po = new PurchaseOrder;
              $i=0;
              foreach($po_number as $row)
              {
              $po_detail = $po->getPObyId($row);
              if(isset($po_detail->id))
              {
                $date = date("Y-m-d");
                $accept_qty = $form_collect['accept_qty'][$i];

                if(isset($form_collect['received_by'][$i]))
                {
                    $user = decrypt($form_collect['received_by'][$i]);
                }
                else
                {
                  $user = \Auth::user()->id;
                }

                $rejected_qty = $po_detail->boqitem->quantity-$accept_qty;
                $total_quantity = $po_detail->boqitem->quantity;
                $form_grn['po_id'] = $po_detail->id;
                $form_grn['accepted_quantity'] = $accept_qty;
                $form_grn['user_id']          = $user;
                $form_grn['rejected_quantity'] = $rejected_qty;
                $form_grn['grn_type'] = $po_detail->boqitem->item->type;
                $form_grn['total_quantity'] = $total_quantity;
                $form_grn['au_id'] = $au_id;
                $form_grn['date'] = $date;

              if($accept_qty > 0)
              {

                $grn = new ReceivingNote;
                $curr_grn = $grn->storeGRN($form_grn);
              }

              }
              $i++;
            }

            parent::setLogMessage('GRN with PO"'.$po_detail->p_nmber.'" has been Approved');
            parent::successMessage('GRN Approved.',parent::getLogMessage());
            return redirect()->route('grn.view');
        }
        catch(DecryptException $e)
        {
        }
    }

    public function downloadPDFgrn($id)
    {

      try
      {

      $id = decrypt($id);
      $recNote = new ReceivingNote;
      $curr_note = $recNote->getGrnById($id);

      if(isset($curr_note->id))
      {
      $pdf = PDF::loadView('inventory_module.reports.grnPDF',[
             'grn'                   => $curr_note,
      ]);

      return $pdf->setPaper('legal','potrait')->stream('GIN.pdf');
      }
      parent::errorMessage('Something went wrong.');
      return redirect()->back();
      }
      catch(DecryptException $e)
      {

      }

      return redirect()->back();



    }

    public function viewdetailsGRN($id)
    {

      try
      {

      $id = decrypt($id);
      $recNote = new ReceivingNote;
      $curr_note = $recNote->getGrnById($id);

      if(isset($curr_note->id))
      {
      return view('inventory_module.receiving_note.note_detail',[
             'grn'                   => $curr_note,
      ]);

      //return $pdf->setPaper('legal','potrait')->stream('GIN.pdf');
      }
      parent::errorMessage('Something went wrong.');
      return redirect()->back();
      }
      catch(DecryptException $e)
      {

      }

      return redirect()->back();



    }

    public function grnAccept($id)
    {
      $id = decrypt($id);
      $grn = ReceivingNote::where('id',$id)->first();

      $po = new PurchaseOrder;

      $curr_po = $po->getPObyId($grn->purchase_order_id);

      $accepted_quantity = $grn->getGrnAcceptedQuantity($grn->purchase_order_id);

      if(isset($curr_po->id))
      {
        $item_quantity = $curr_po->boqitem->quantity;

        $item_id = $curr_po->boqitem->item_id;
        $boq = new BillOfQuantity;

        $stock = new Stock;
        $stock_data['receiving_note_id'] = $grn->id;
        $stock_data['date']              = now();
        $stock_data['in_quantity']       = $grn->accepted_quantity;
        $stock_data['item_id']           = $curr_po->boqitem->item_id;
        $stock_data['branch_id']           = $boq->getBOQById($curr_po->bill_of_quantity_id)->branch_id;

        $current_stock = $stock->inStock($stock_data);
        if(isset($current_stock) && isset($item_id))
        {

          $item = new Item;

          $item_data['id'] = $item_id;

          $item_data['quantity'] = $grn->accepted_quantity;

          $curr_item = $item->updateItemQuantityById($item_data);

      }
      $grn->status = "Approved";
      $grn->save();
      //parent::setLogMessage('GRN with PO"'.$po_detail->p_nmber.'" has been Approved');
      parent::successMessage('GRN Approved.',parent::getLogMessage());
      return redirect()->route('grn.view');
      }
      else
      {
        parent::errorMessage('Something went wrong.');
        return redirect()->back();
      }
    }


    public function grnReject($id)
    {
      $id = decrypt($id);
      $grn = ReceivingNote::where('id',$id)->first();

      if(isset($grn->id))
      {
      $grn->delete();
      //parent::setLogMessage('GRN with PO"'.$po_detail->p_nmber.'" has been Approved');
      parent::successMessage('GRN Rejected.',parent::getLogMessage());
      return redirect()->route('grn.view');
      }
      else
      {
        parent::errorMessage('Something went wrong.');
        return redirect()->back();
      }
    }
}
