<?php

namespace App\Http\Controllers;
use Illuminate\Contracts\Encryption\DecryptException;

use Illuminate\Http\Request;
use App\Http\Requests\BranchRequest;

use App\Branch;
use App\Account;
use EF;


class BranchController extends Controller
{
    public function index()
    {
        return view('branch.manage_branch',
            [
                'branch_list'   => $this->getBranchList(),
                'branch_labels' => EF::branchWhiteLabel(),
            ]
        );
    }
    

    public function storeBranch(BranchRequest $request)
    {

        $branch  = new Branch;
        $account = new Account;
        $form_collect = $request->input();

        $form_collect['code'] = str_replace("/"," ",$form_collect['code']);

        $curr_branch = $branch->storeBranch($form_collect,EF::branchWhiteLabel());

        if(isset($curr_branch->id))
        {
           
            parent::setLogMessage(ucwords(EF::branchWhiteLabel()['module']).' '.$curr_branch->name.' has been created');

            parent::successMessage(ucwords(EF::branchWhiteLabel()['module']).' has been created.',parent::getLogMessage());

             

          
        }

        return redirect('branch');
    }

    public function updateBranch(BranchRequest $request)
    {
        try 
        {
            $labels = EF::branchWhiteLabel();

            $form_collect = $request->input();

            $form_collect['code'] = str_replace("/"," ",$form_collect['code']);

            $form_collect[$labels['branch']] = decrypt($form_collect[$labels['branch']]);

            $branch = new Branch;

            $curr_branch = $branch->updateBranch($form_collect,$labels);

            if(isset($curr_branch))
            {
                parent::setLogMessage(ucwords(EF::branchWhiteLabel()['module']).' "'.$curr_branch->name.'" has been updated');

                parent::successMessage(ucwords(EF::branchWhiteLabel()['module']).' has been updated.',parent::getLogMessage());
            }
        } 
        catch (DecryptException $e) 
        {
            
        }

        return redirect('branch');
    }

    public function removeBranch($id)
    {
        return redirect('home');
        
        parent::errorMessage('Branch not found.');

        try 
        {
            $id = decrypt($id);

            $branch = new Branch;

            if($branch->removeBranch($id))
            {
                parent::successMessage('Branch has been removed.');
            } 
        } 
        catch (DecryptException $e) 
        {
            
        }

        return redirect('branch');
    }

    public function getBranchList()
    {
        $branch = new Branch;
        
        return $branch->getBranchList();
    }
}
