<?php

namespace App\Http\Controllers\Inventory;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Inventory\Item;
use App\Imports\UsersImport;
use Crypt;
use App\Branch;
use App\Inventory\BillOfQuantity;
use App\Inventory\BOQItems;
use App\Inventory\InventoryUnit;
use App\Inventory\PurchaseOrder;
use App\User;
use App\Designation;
use App\Http\Requests\InventoryRequests\BOQRequest;
use Illuminate\Contracts\Encryption\DecryptException;
use PDF;
use Excel;




class BillOfQuantityController extends Controller
{
    public function addBOQForm()
    {

    	 $branch_obj  = new Branch;
       $unit_obj    = new InventoryUnit;
       $boq         = new BillOfQuantity;
       $user = new User;
       $designation = new Designation;
       //$vendor_type = new VendorType;
       $designation_list = $designation->getDesignationList();
       $items = Item::all();

       $auser_list = $user->getUserListByType(['Employee']);
    	 $branch      = $branch_obj->getBranchList();
       $unit_list   = $unit_obj->getAllInventoryUnit();
       $floor_list  = $boq->getBOQListByColumn('floor');

      return view('inventory_module.boq.add_boqform',
      	[
      		'branch'            => $branch,
          'unit_list'         => $unit_list,
          'floor_list'        => $floor_list,
          'auser_list'        => $auser_list,
          'designation_list'  => $designation_list,
          'items'             => $items
      	]
        );
    }

    public function createboqrequsition()
    {

    	 $branch_obj  = new Branch;
       $unit_obj    = new InventoryUnit;
       $boq         = new BillOfQuantity;
    	 $branch      = $branch_obj->getBranchList();
       $unit_list   = $unit_obj->getAllInventoryUnit();
       $floor_list  = $boq->getBOQListByColumn('floor');
       $user = new User;
       //$vendor_type = new VendorType;
       $designation = new Designation;
       //$vendor_type = new VendorType;
       $items = Item::all();
       $designation_list = $designation->getDesignationList();

 $auser_list = $user->getUserListByType(['Employee']);

      return view('inventory_module.manual_boq.manual_add_boqform',
      	[
      		'branch'    =>  $branch,
          'unit_list' =>  $unit_list,
          'floor_list' => $floor_list,
          'auser_list'=>$auser_list,
          'designation_list' =>$designation_list,
          'items' => $items
      	]
        );

    }

    public function viewBOQRequests()
    {

       $boq = new BillOfQuantity;

       $boq_list = $boq->getAllBOQ();

      return view('inventory_module.boq.requsition_request',
        [
          'boq_list' => $boq_list,
        ]

        );

    }

    public function viewBOQRequests_pr()
    {

       $boq = new BillOfQuantity;

       $boq_list = $boq->getAllBOQ2();
       $boq_list = $boq_list->where('status' ,"!=" , "Pending");

       $curr_date =date("Y-m-d");
       $time = strtotime($curr_date.'-2 days');
       $date = date("Y-m-d", $time);

       $alerts = BillOfQuantity::join('purchase_orders', 'purchase_orders.bill_of_quantity_id', '=', 'bill_of_quantities.id')
         ->where('bill_of_quantities.status' , "Approved")
         ->where('purchase_orders.status' , "Pending")
         ->where('purchase_orders.created_at' ,"<", $date)
         ->groupBy('purchase_orders.bill_of_quantity_id')


         ->selectRaw('purchase_orders.bill_of_quantity_id')
         ->get();


      return view('inventory_module.boq.view_boqrequest',
        [
          'boq_list' => $boq_list,
          'alerts' =>$alerts
        ]

        );

    }




    public function createRequestpo()
    {

       $boq = new BillOfQuantity;

       $boq_list = $boq->getAllBOQ2();
       $boq_list = $boq_list->where('status' ,"!=" , "Pending");

       $curr_date =date("Y-m-d");
       $time = strtotime($curr_date.'-2 days');
       $date = date("Y-m-d", $time);

       $alerts = BillOfQuantity::join('purchase_orders', 'purchase_orders.bill_of_quantity_id', '=', 'bill_of_quantities.id')
         ->where('bill_of_quantities.status' , "Approved")
         ->where('purchase_orders.status' , "Pending")
         ->where('purchase_orders.created_at' ,"<", $date)
         ->groupBy('purchase_orders.bill_of_quantity_id')


         ->selectRaw('purchase_orders.bill_of_quantity_id')
         ->get();


      return view('inventory_module.purchase_order.createporequest',
        [
          'boq_list' => $boq_list,
          'alerts' =>$alerts
        ]

        );

    }

    public function rejectBOQ($id)
    {
      try
      {

            $id = decrypt($id);

            $boq = new BillOfQuantity;

            if($boq->rejectBOQ($id))
            {
                parent::successMessage('BOQ has been rejected.');
            }


         $boq_list = $boq->getAllBOQ();

         return view('inventory_module.boq.requsition_request',
        [
          'boq_list' => $boq_list,
        ]

        );


      }
      catch(DecryptException $e)
      {

      }



    }
    public function storeBOQ(BOQRequest $request)
    {
      try
      {


        $user_all = \Auth::User();
        $user_id = $user_all->id;

        $boq = new BillOfQuantity;

        $form_collect = $request->input();
        for($i=0; $i< @count($form_collect['item_quantity']); $i++)
        {
          if(decrypt($form_collect['item'][$i]) !=0 && decrypt($form_collect['item_unit'][$i]) !=0 && $form_collect['item_quantity'][$i] < 1)
          {
            parent::errorMessage('Items quantity cannot be in negative or zero.');
             return redirect()->back();
           }
        }
        if(@count($form_collect['item']) == 0)
        {
             parent::errorMessage('Select a BOQ item to add valid BOQ.');
              return redirect()->back();
        }
        $form_collect['project'] = decrypt($form_collect['project']);
        $form_collect['user_id'] = decrypt($form_collect['au_user']);
        $form_collect['remarks'] = $form_collect['remarks'];
        $form_collect['pr_check'] = "0";

        // if(@count($form_collect['item']) == @count($form_collect['item_quantity']))
        // {
        //     foreach($form_collect['item'] as $rows)
        //    {
        //     $form_collect['id_list'][] = decrypt($rows);
        //    }
        //
        //    foreach($form_collect['item_unit'] as $rows)
        //    {
        //      $form_collect['unit_list'][] = decrypt($rows);
        //    }
        // }
        // else{
        //   parent::errorMessage('Items Quantity are missing.');
        //    return redirect()->back();
        // }

        $curr_boq = $boq->storeBOQ($form_collect);

       if(isset($curr_boq->id))
       {
        for($i=0; $i< @count($form_collect['item']); $i++)
        {
            if(decrypt($form_collect['item'][$i]) !=0 && decrypt($form_collect['item_unit'][$i]) !=0 && $form_collect['item_quantity'][$i] !=0 && $form_collect['item_quantity'][$i] !="")
            {
          $boq_item_data[$i] =
          [
            'bill_of_quantity_id'             => $curr_boq->id,
            'item_id'                         => decrypt($form_collect['item'][$i]),
            'inventory_unit_id'               => decrypt($form_collect['item_unit'][$i]),
            'quantity'                        => $form_collect['item_quantity'][$i],
            'item_description'                => $form_collect['item_description'][$i],
            'created_at'                      => $form_collect['item_date'],
          ];
          }
        }

        if(@count($boq_item_data))
        {
            $boq_item = new BOQItems;
            $boq_item->massInsertBOQItem($boq_item_data);
        }

          parent::setLogMessage('BOQ "'.$curr_boq->sr_no.' Remarks: '.$curr_boq->remarks.'" has been created');

            parent::successMessage('BOQ has been created.',parent::getLogMessage());

             return redirect('viewBOQDetails/'.Crypt::encrypt($curr_boq->id));

       }

      }
      catch(DecryptException $e)
      {

      }

      return redirect()->back();
    }



    public function storecreatepurchase(BOQRequest $request)
    {
      try
      {

        $user_all = \Auth::User();
        $user_id = $user_all->id;

        $boq = new BillOfQuantity;

        $form_collect = $request->input();
        for($i=0; $i< @count($form_collect['item_quantity']); $i++)
        {
          if(decrypt($form_collect['item'][$i]) !=0 && decrypt($form_collect['item_unit'][$i]) !=0 && $form_collect['item_quantity'][$i] < 1)
          {
            parent::errorMessage('Items quantity cannot be in negative or zero.');
             return redirect()->back();
           }
        }
        if(@count($form_collect['item']) == 0)
        {
             parent::errorMessage('Select a BOQ item to add valid BOQ.');
              return redirect()->back();
        }
        $form_collect['project'] = decrypt($form_collect['project']);
        $form_collect['user_id'] = decrypt($form_collect['au_user']);
        $form_collect['remarks'] = $form_collect['remarks'];

        // if(@count($form_collect['item']) == @count($form_collect['item_quantity']))
        // {
        //     foreach($form_collect['item'] as $rows)
        //    {
        //   $form_collect['id_list'][] = decrypt($rows);
        //
        //    }
        //
        //    foreach($form_collect['item_unit'] as $rows)
        //    {
        //   $form_collect['unit_list'][] = decrypt($rows);
        //
        //    }
        // }

        $form_collect['status'] = "Waiting";
        $form_collect['pr_check'] = "1";

        $curr_boq = $boq->storeBOQ($form_collect);

       if(isset($curr_boq->id))
       {
         for($i=0; $i< @count($form_collect['item']); $i++)
         {
             if(decrypt($form_collect['item'][$i]) !=0 && decrypt($form_collect['item_unit'][$i]) !=0 && $form_collect['item_quantity'][$i] !=0 && $form_collect['item_quantity'][$i] !="")
             {
           $boq_item_data[$i] =
           [
             'bill_of_quantity_id'             => $curr_boq->id,
             'item_id'                         => decrypt($form_collect['item'][$i]),
             'inventory_unit_id'               => decrypt($form_collect['item_unit'][$i]),
             'quantity'                        => $form_collect['item_quantity'][$i],
             'item_description'                => $form_collect['item_description'][$i],
             'created_at'                      => $form_collect['item_date'],
           ];
           }
         }
        if(@count($boq_item_data))
        {
            $boq_item = new BOQItems;
            $boq_item->massInsertBOQItem($boq_item_data);
        }
          parent::setLogMessage('PR "'.$curr_boq->sr_no.' Remarks: '.$curr_boq->remarks.'" has been created');

            parent::successMessage('PR has been created.',parent::getLogMessage());

             return redirect('boqrequestdetail/'.Crypt::encrypt($curr_boq->id));
       }

      }
      catch(DecryptException $e)
      {

      }

      return redirect()->back();
    }

    public function boqRequestAccept($boq_id)
    {
      try
      {
      $boq_id   = decrypt($boq_id);


      $boq_detail = new BillOfQuantity;
      $curr_boq_detail = $boq_detail->getBOQById($boq_id);
      if(isset($curr_boq_detail->id))
      {

      $curr_boq_detail->status = "Waiting";
      $curr_boq_detail->update();

      parent::successMessage('BOQ has been accepted and marked as Waiting');

       return redirect('boqrequest-pr');


      }
     else
    {
      parent::errorMessage('Something Went Wrong');
    }


      }
        catch (DecryptException $e)
        {


        }
          return redirect()->back();
  }

    public function viewBOQRequestDetails($boq_id)
    {
      try
      {
      $boq_id   = decrypt($boq_id);
      $boq_item = new BOQItems;
      $boq_items_list = $boq_item->getBOQItemById($boq_id);
      $boq_detail = new BillOfQuantity;
      $boq_detail = $boq_detail->getBOQById($boq_id);
      $user = new User;
      $user2 = new User;
      $purchase_order = new PurchaseOrder;
      $type1[] = "Supplier";
      $type2[] = "Contractor";
      $supplier = $user->getUserListByType($type1);
      $contractor = $user2->getUserListByType($type2);
      $brand_list  = $purchase_order->getPurchaseListByColumn('brand');
      $auser_list = $user->getUserListByType(['Employee']);


        return view('inventory_module.boq.boq_request_detail',
        [
           'boq_items_lists'       => $boq_items_list,
           'boq_detail'            => $boq_detail,
           'suppliers'             => $supplier,
           'contractors'           => $contractor,
           'brand_list'            => $brand_list,
           'auser_list' =>$auser_list
         ]
        );
      }
        catch (DecryptException $e)
        {


        }
  }

  public function viewPORequestDetails($boq_id)
  {

    try
    {
    $boq_id   = decrypt($boq_id);
    $boq_item = new BOQItems;
    $boq_items_list = $boq_item->getBOQItemById($boq_id);
    $boq_detail = new BillOfQuantity;
    $boq_detail = $boq_detail->getBOQById($boq_id);
    $user = new User;
    $user2 = new User;
    $purchase_order = new PurchaseOrder;
    $type1[] = "Supplier";
    $type2[] = "Contractor";
    $supplier = $user->getUserListByType($type1);
    $contractor = $user2->getUserListByType($type2);
    $brand_list  = $purchase_order->getPurchaseListByColumn('brand');
    $auser_list = $user->getUserListByType(['Employee']);


      return view('inventory_module.purchase_order.requestdetails',
      [
         'boq_items_lists'       => $boq_items_list,
         'boq_detail'            => $boq_detail,
         'suppliers'             => $supplier,
         'contractors'           => $contractor,
         'brand_list'            => $brand_list,
         'auser_list' =>$auser_list
       ]
      );
    }
      catch (DecryptException $e)
      {


      }
}
public function acceptBOQfirst(Request $request)
{
  try
  {
  $boq_id   = decrypt($request->boq_id);


  $boq_detail = new BillOfQuantity;
  $curr_boq_detail = $boq_detail->getBOQById($boq_id);
  if(isset($curr_boq_detail->id))
  {

  $curr_boq_detail->status = "In Process";
  $curr_boq_detail->au_id = \Auth::user()->id;
  $curr_boq_detail->update();

  parent::successMessage('PR has been accepted and marked as In Process');

   return redirect('boqrequest-pr');


  }
  else
  {
  parent::errorMessage('Something Went Wrong');
  }


  }
    catch (DecryptException $e)
    {


    }
      return redirect()->back();

}

  public function acceptBOQ(BOQRequest $request)
  {

    try
    {
      $form_collect = $request->input();

      foreach($form_collect['user_id'] as $rows)
     {
        $form_collect['user_id_list'][] = decrypt($rows);
     }
      foreach($form_collect['boq_item_id'] as $rows1)
     {
        $form_collect['boq_item_id_list'][] = decrypt($rows1);
     }
     foreach($form_collect['boq_id'] as $rows2)
     {
         $form_collect['boq_id_list'][] = decrypt($rows2);
     }
    //  foreach($request->au_user as $rows4)
    // {
    //     $form_collect['au_user'][] = $rows4;
    // }
     if(isset($request->quotation))
     {
      foreach($request->quotation as $rows3)
     {
         $form_collect['quotation'][] = $this->uploadfile($rows3);
     }

     }


      $boq = new BillOfQuantity;
      $purchase_order = new PurchaseOrder;
      $boq_accept = $boq->acceptBOQ($form_collect['boq_id_list'][0]);
      $boq_detail = $boq->getBOQById($form_collect['boq_id_list'][0]);
     if($boq_accept == "1")
     {
      for($i=0; $i< @count($form_collect['boq_item_id_list']); $i++)
      {
        if(!isset($form_collect['quotation'][$i]))
        {
                  $form_collect['quotation'][$i] = null;
        }
        if(isset($form_collect['brand_list'][$i]))
        {

        if(isset($form_collect['new_brand'][$i]) && $form_collect['brand_list'][$i] == 'Other')
        {

          $form_collect['current_brand'][$i] = $form_collect['new_brand'][$i];
        }
        else
        {
           $form_collect['current_brand'][$i] = $form_collect['brand_list'][$i];
        }


        }
        else
        {
           $form_collect['current_brand'][$i] = null;
        }
        $u_all = \Auth::User();
        $au_id = $u_all->id;
        $boq_item_data[$i] =
        [
          'bill_of_quantity_id'              => $form_collect['boq_id_list'][0],
          'b_o_q_item_id'                    => $form_collect['boq_item_id_list'][$i],
          'user_id'                          => $form_collect['user_id_list'][$i],
          'unit_price'                       => $form_collect['unit_price'][$i],
          'remarks'                          => $form_collect['remarks'][$i],
          'p_number'                         => $purchase_order->generatePONumber($i),
          'quotation'                        => $form_collect['quotation'][$i],
          'status'                           =>"Pending",
          'brand'                            => $form_collect['current_brand'][$i],
          //'au_id'                            =>$form_collect['au_user'][$i],
          'branch_id'                        =>$boq_detail->branch_id,
        ];

      }

      if(@count($boq_item_data))
      {
          $purchase_order = new PurchaseOrder;
          // $purchase_order->massInsertPO($boq_item_data);
          for($j=0; $j< @count($form_collect['boq_item_id_list']); $j++)
          {

            $check_po = $purchase_order->getPODuplicate($boq_item_data[$j]['user_id'],$boq_item_data[$j]['bill_of_quantity_id']);
            if($check_po)
            {
              $boq_item_data[$j]['p_number'] = $check_po->p_number;
            }
            $purchase_order->InsertPO($boq_item_data[$j]);
          }
      }

        parent::setLogMessage('PR "'.$boq_detail->sr_no.'" has been: '.$boq_detail->status.' and PO "'. $purchase_order->p_number.'"been created');
        parent::successMessage('PR has been approved and PO has been created.',parent::getLogMessage());

        return redirect('inventory');
     }

    }
    catch(DecryptException $e)
    {

    }
  }



  public function uploadfile($file,$loaded_image = '/graphics/logo/user.png')
  {
      if((isset($file) && trim(strlen($file)) > 0))
      {
          $file =  \EF::uploadFile($file);

      }
      else
      {
          if(strlen(trim($loaded_image)) > 0)
          {
              $file =  $loaded_image;
          }
          else
          {
             $file = '/graphics/logo/user.png';
          }
      }


      return $file;
  }

  public function viewBOQDetails($id)
  {

    try
    {
          $id = decrypt($id);
          $boq = new BillOfQuantity;
          $boq_detail = $boq->getBOQById($id);
          if(isset($boq_detail->id))
          {

            return view('inventory_module.boq.boq_detail',
            [
              'boq_detail' => $boq_detail,
            ]
        );
          }
          return redirect()->back();
    }
    catch(DecryptException $e)
    {
    }
  }

    public function downloadPDFpr($id)
    {

      try
      {

      $id = decrypt($id);
      $boq = new BillOfQuantity;
      $curr_boq = $boq->getBOQById($id);



      if(isset($curr_boq->id))
      {
      $pdf = PDF::loadView('inventory_module.reports.prPDF',[
             'pr'                   => $curr_boq,
      ]);

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

      }

      return redirect()->back();



    }

    public function PRDetail($id)
    {
      try
      {

      $id = decrypt($id);
      $boq = new BillOfQuantity;
      $curr_boq = $boq->getBOQById($id);



      if(isset($curr_boq->id))
      {
      $vv = view('inventory_module.boq.purchase_req_detail',[
             'pr'                   => $curr_boq,
      ]);

      return $vv;
      }
      parent::errorMessage('Something went wrong.');
      return redirect()->back();
      }
      catch(DecryptException $e)
      {

      }

      return redirect()->back();

    }


    public function PO_Detailrequest($id)
    {
      try
      {
            $id = decrypt($id);
            $mypo = PurchaseOrder::where('bill_of_quantity_id',$id)->first();
            //dd($id);
            $po = new PurchaseOrder;
            $po_detail = $po->getPObyNoAll($mypo->p_number);

            if($po_detail[0]->id)
            {
              return view('inventory_module.purchase_order.purchase_req_detail',
             	[
             		'po_detail' => $po_detail,
             	]
    	  	);
        }
            return redirect()->back();
      }
      catch(DecryptException $e)
      {
      }
    }




    public function vendorupload()
    {

      return view('inventory_module.vendorupload');
    }

    public function vendoruploadsubmit(Request $request)
    {
      $import = new UsersImport();
 $data = \Excel::import($import, request()->file('file'));


parent::successMessage('uploaded done');
      return redirect()->back();
    }


}
