<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\User;
use Auth;
use App\Models\FundRequest;
use App\Models\AccountHead;
use App\Models\Journal;

class FundRequestController extends Controller
{

	function index()
	{
		$data['acc_head']=AccountHead::with('children')->where('type_id',2)->where('parent_head',24)->orderBy('name','asc')->get();
		$data['title']='Fund Request';
		return view('admin.fund_req.index',$data);
	}

	/**
	 * save fund request
	 * 
	 * @param  Request $req
	 * 
	 * @return redirect      
	 */
	function store(Request $req)
	{
		$this->validate($req,[
			'purpose'=>'required',
			'amount'=>'required|numeric'
		]);

		$fund=new FundRequest();
		$fund->purpose=$req->get('purpose');
		$fund->description=$req->get('description');
		$fund->amount=$req->get('amount');
		$fund->due_date=$req->get('due_date',date('Y-m-d H:i:s'));
		$fund->request_by=\Auth::user()->id;
		$fund->is_approved=0;
		$fund->save();

		$req->session()->flash('success','Fund request send successfully !');
		return redirect('account/fund_req');	
	}

	/**
	 * change approval status
	 * 
	 * @param  Request $req 
	 * 
	 * @return string      
	 */
	function change_approval_status(Request $req)
	{
		if($req->get('status')==1)
		{
			$jrnl=new Journal();
			$jrnl->debit_account=$req->get('purpose');
			$jrnl->credit_account=5;
			$jrnl->description=$req->get('description');
			$jrnl->amount=$req->get('amount');
			$jrnl->is_approaved=0;
			$jrnl->created_by=\Auth::user()->id;
			$jrnl->save();
		}

		$fund=FundRequest::find($req->get('id'));
		$fund->is_approved=$req->get('status')?1:2;
		$fund->save();

		return "ok";
	}

}