<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\BankRequest;
use Illuminate\Contracts\Encryption\DecryptException;
use App\Bank;
use Crypt;

class BankController extends Controller
{
    public function index()
	{
		$bank=new Bank;

		return view('bank.manage_bank',
         	[
         		'banks' => $bank->getAllBanks(),
         	]
	  	);		
	}

	public function storeBank(BankRequest $request)
	{
		
			$form_collect = $request->input();

			$bank = new Bank;

      $curr_bank = $bank->storeBank($form_collect);

			if (isset($curr_bank->id))
			{
          if(\Request::ajax())
          {
              parent::clearMessageLog(1);
            
              $data['id'] = Crypt::encrypt($curr_bank->id);

              $data['bank_name']   = $curr_bank->bank_name;

              $data['location']    = $curr_bank->location;

              $data['branch_code'] = $curr_bank->branch_code;

              return $data;

          }

			    parent::setLogMessage($curr_bank->branch_code.' bank has been created.');

            parent::successMessage('Bank has been created.',parent::getLogMessage());
			}
	
	   return redirect('bank');
	}

	public function updateBank(BankRequest $request)
	{
       try 
       {
         	$form_collect = $request->input();

         	$form_collect['id'] = decrypt($form_collect['id']);

         	$bank = new Bank;

          $curr_bank = $bank->updateBank($form_collect);
        
            if (isset($curr_bank->id))
              {
               parent::setLogMessage($curr_bank->code.' bank has been updated.');

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

       return redirect()->back();
	}
	
	public function removeBank($id)
	{
        parent::errorMessage('Bank not found.');

        try 
        {
          $id = decrypt($id);

          $bank = new Bank;

          if ($bank->removeBank($id))
           {
             parent::setLogMessage(' Bank has been removed.');

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

        return redirect('bank');
	}
}
