<?php

namespace App\Http\Controllers;

use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Http\Request;
use App\Http\Requests\VendorRequest;
use App\Department;
use App\Vendor;
use App\Account;



class VendorController extends Controller
{
    public function index()
    {
    	$vendor     = new Vendor;
      $department = new Department;
      $account    = new Account;

    	return view('vendors.manage_vendors',[
    		'vendor_list'           => $vendor->getAllVendors(),
        'department_list'       => $department->getDepartmentList(),
        'account_payable_list'  => $account->getAccountListByType(['Account Payable','Cash','Bank']),
        'account_list'          => $account->getAllSubhead(),

    	]);
    }

    public function storeVendor(VendorRequest $request)
    {
   		$vendor = new Vendor;

      $data_collect = $request->input();

   		$data_collect['photo'] = $request->photo;

   		$curr_vendor = $vendor->storeVendor($data_collect);

   		$curr_vendor['photo'] = $request->photo;

   		if(isset($curr_vendor->id))
   		{
   			parent::setLogMessage($curr_vendor->code.' '.$curr_vendor->name.' vendor has been created');

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

    	return redirect()->back();
    }

    public function updateVendor(VendorRequest $request)
    {
      $vendor = new Vendor;

      $data_collect = $request->input();

   	  $data_collect['photo'] = $request->photo;


      try 
      {
          $data_collect['vendor'] = decrypt($data_collect['vendor']);

          $curr_vendor = $vendor->updateVendor($data_collect);

          if(isset($curr_vendor->id))
          {
          	  parent::setLogMessage($curr_vendor->code.' '.$curr_vendor->name.' vendor has been updated');

              parent::successMessage('Vendor has been updated.',parent::getLogMessage());
          }
      } 
      catch (DecryptException $e) 
      {
            //
      }

      

      return redirect()->back();
    }

    public function removeVendor($id)
    {
      $vendor = new Vendor;

      try 
      {
          $id = decrypt($id);

          $curr_vendor = $vendor->removeVendor($id);

          if(isset($curr_vendor->id))
          {
          	  parent::setLogMessage($curr_vendor->code.' '.$curr_vendor->name.' vendor has been removed');

              parent::successMessage('Vendor has been removed.',parent::getLogMessage());
          }
      } 
      catch (DecryptException $e) 
      {
            //
      }

      

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