<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use App\Item;
use App\PurchaseRequestVendor;
use DB;
use Session;
use Illuminate\Validation\Rule;
use App\ItemVendor;
use App\PurchaseOrder;
use App\ItemPurchaseOrder;
class PurchaseRequestVendorController extends Controller
{

   public function __construct()
   
    {
               
    }

function index()
{
      $vendorList = PurchaseRequestVendor::orderBy('id', 'DESC')->get();
      return view('procurement/vendors.index' ,compact('vendorList') );
}


function create()
{
     $itemList = Item::orderBy('id', 'DESC')->get();
    
     return view('procurement/vendors.addVendor' ,compact('itemList') );
}


function store(Request $request)
{

       $validator = Validator::make($request->all(), [
                    
            'name' => 'required|unique:vendors,name',
            'item_name' => 'required|array',
            'email' => 'required|email',
            'phone' => 'required|numeric|min:11',
            'cnic' => 'required',
            'ntn' => 'required',
            'stn' => 'required',
        ]);

    
       if ($validator->fails()) 
       {
            return redirect('/vendors/add-vendor')
            ->withErrors($validator)
            ->withInput();
        }


    $success = false;

    DB::beginTransaction();

    try {

        $vendor = new PurchaseRequestVendor;
        $vendor->name = $request->name;
        $vendor->email = $request->email;
        $vendor->phone_number = $request->phone;
        $vendor->cnic = $request->cnic;
        $vendor->address = $request->address;
        $vendor->ntn = $request->ntn;
        $vendor->stn = $request->stn;
      
        if ($vendor->save()) 
        {
                
                 foreach ($request->item_name as $key => $value) 
            {
                 $vendor->items()->attach($value);
            }

                $success = true;
            }


        DB::commit();

        return redirect()->route('vendor.list')->with('success' , 'Vendor Added Successfully!');
      } 
        
        catch (\Exception $e) 
      {

       DB::rollback();
      return redirect()->route('vendor.list')->with('success' , 'Error Something went wrong.');
      }

  
}


function destroy($id)
{
 

       if(is_numeric($id))
    {
        DB::beginTransaction();

   try {

        $vendor = PurchaseRequestVendor::find($id);
        $vendor->delete();
        $vendor->items()->wherePivot('purchase_request_vendor_id','=',$id)->detach();
        DB::commit();
   
      } 
        catch (\Exception $e) 
      {
       DB::rollback();

      }
    
    }
 
  return redirect()->route('vendor.list')->with('success' , 'Vendor Removed Successfully!');
}

function edit($id)
{
 
   if(is_numeric($id))
    {
            $findvendor = PurchaseRequestVendor::where("id",$id)->first();

            $ItemList = Item::orderBy('id' , 'DESC')->get();

            $vendorItems = PurchaseRequestVendor::find($findvendor->id)->items;

            $assignItems = '';

            $count = 1;
            
            foreach( $vendorItems as $items)
            {
            $assignItems .= $items->id;
            if($count != sizeof($vendorItems))
            {
            $assignItems  .= ',';
            }
            $count ++;
            }

    return view('procurement/vendors.editVendor' ,compact('findvendor' , 'ItemList' , 'assignItems') );
    }

}


function update(Request $request)
{
 $id = $request->input('id');
if(is_numeric($id))
{
      $validator = Validator::make($request->all(), [
                    
            'name' => 'required|unique:vendors,name,'.$id,
            'email' => 'required|email',
            'phone' => 'required|numeric|min:11',
            'cnic' => 'required',
            'ntn' => 'required',
            'stn' => 'required',
        ]);


       if ($validator->fails()) 
        {
            return redirect('/vendors/edit-vendor/'.$id)
            ->withErrors($validator)
            ->withInput();
        }


        DB::beginTransaction();

        try {


        PurchaseRequestVendor::where('id', '=', $id)->update([

            'name' => $request->name,
            'email' => $request->email,
            'phone_number' => $request->phone,
            'ntn' => $request->ntn,
            'stn' => $request->stn,						'cnic' => $request->cnic,
          ]);


        if($id > 0 && !empty($request->item_name))
        {
             $extraId = array();

             $Itemids = implode(",", $request->item_name);
             
             ItemVendor::where('purchase_request_vendor_id' , $id )
             ->whereNotIn('item_id', [$Itemids] )
             ->delete();

             $vendor = PurchaseRequestVendor::find($id);

            $edited_array = [];
            
            foreach ($request->item_name as $key => $items) 
            {
                  $edited_array[$items] = ['purchase_request_vendor_id' => $id];
            }

          
           $vendor->items()->sync($edited_array);
        }

         DB::commit();
   
      } 
        catch (\Exception $e) 
      { 
        DB::rollback();

        dd($e);
      }

}

  return redirect()->route('vendor.list')->with('success' , 'Vendor Updated Successfully!');
}

public function view($vendorId)
{
   $data['vendor'] = PurchaseRequestVendor::find($vendorId);
   $data['sent_po'] = PurchaseRequestVendor::getPoStatus( $data['vendor']->id , 1);
   $data['partial_receive_po'] = PurchaseRequestVendor::getPoStatus( $data['vendor']->id , 3);
   $data['receive_po'] = PurchaseRequestVendor::getPoStatus( $data['vendor']->id , 2);
   $data['partialy_paid_receipt'] = PurchaseRequestVendor::getReceiptStatus( $data['vendor']->id , 2);
   $data['unpaid_receipt'] = PurchaseRequestVendor::getReceiptStatus( $data['vendor']->id , 0);

   $data['paid_receipt'] = PurchaseRequestVendor::getReceiptStatus( $data['vendor']->id , 1) ;
 
   return view('procurement/vendors.view' ,compact('data') );
}

    public function itemDetail($vendorId = null, $itemId = null)
    {

        $po_array = PurchaseOrder::where( 'vendor_id' , $vendorId )->pluck('id')->toArray();
        $item_purchase_order = ItemPurchaseOrder::whereIn('purchase_order_id' , $po_array)->where('item_id' , $itemId)->orderBy('created_at', 'DESC')->get();
        $item = Item::find($itemId);
        return view('procurement/vendors.vendor-item-detail' ,compact('item_purchase_order' , 'vendorId' , 'item') );
    }


}
