<?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\AccountType;
use App\Models\AccountHead;
use App\Models\Journal;
use App\Models\PaymentHistory;
use App\Models\JournalComment;
use App\Models\FundRequest;

class JounalController extends Controller
{
	public function __construct(){
		$this->middleware('auth');
	}
    
	function index()
	{
		//$data['journals']=Journal::with('debit')->paginate(50);

		$data['journals']=\DB::select("SELECT debit_account,ahd.name,SUM(COALESCE(amount, 0)) AS debit,(SELECT COALESCE(SUM(j1.amount), 0) credit FROM journal j1 WHERE j1.ref_id = j.debit_account) credit FROM
  journal j JOIN acc_head ahd  ON j.debit_account = ahd.id WHERE ahd.type_id IN (1, 2) 
GROUP BY j.debit_account order by j.id desc");


		$data['funds']=FundRequest::with(['acc_head','user'])->where('is_approved',0)
		->orderBY('id','desc')->get();

		$data['approved_funds']=FundRequest::with(['acc_head','user'])->where('is_approved',1)
		->orderBY('id','desc')->get();

		$data['title']='Journal';
		return view('admin.journal.index',$data);
	}

	/**
	 * get journal details with breakdown
	 * @param  integer $id
	 * @return view   
	 */
	function get_details($id)
	{
		$data['journal']=Journal::with(['debit','credit','user'])->where('debit_account',$id)->orWhere('ref_id',$id)->get();
		$data['title']='Journal Details';
		return view('admin.journal.details',$data);
	}

	function create()
	{
		$data['account_types']=AccountType::with(['acc_head'=>function($q){
			return $q->where('parent_head',0);
		}])->orderBy('name','asc')->get();	

		$data['title']='Create Journal';
		return view('admin.journal.create',$data);
	}

	function store(Request $req)
	{


		$this->validate($req,[
			'account_head'=>'required',
			'credit_head'=>'required',
			'amount'=>'required|numeric'
		]);
		$documentUpload = $req->file('filedocument');
		if ( !empty( $documentUpload )) {
		      $documentname = $documentUpload->getClientOriginalName();
		      $path = 'public/account_expense/';
		      $documentUpload->move($path,$documentname);
		      $expenseDocument = $documentname;
		} else {
		  $expenseDocument = '';
		}

		$journal=new Journal();
		$journal->debit_account		=	$req->get('account_head');
		$journal->credit_account	=	$req->get('credit_head');
		$journal->ref_id 			=	$req->get('account_head');
		$journal->description 		=	$req->get('description');
		$journal->amount 			=	$req->get('amount');
		$journal->expense_document 	= 	$expenseDocument;
		$journal->is_approaved 		=	0;
		$journal->created_by 		=	\Auth::user()->id;
		$journal->created_at 		=	$req->get('date',date('Y-m-d'));
		$journal->save();

		$req->session()->flash('success','Journal created successfully !');
		return redirect('account/journal');
	}


	function get_acc_head($id)
	{
		$heads=AccountHead::where('id',$id)->orderBy('name','asc')->get();

		$str="<option value=''>Select Account Type</option>";
		if($heads)
		{
			foreach($heads as $hd)
			{
				$str.="<option value='{$hd->id}'>{$hd->name}</option>";
			}
		}

		return $str;
	}

	function change_approaval_status(Request $req)
	{
		$journal_comment=JournalComment::where('debit_account',$req->get('debit_account'))->first();

		if($journal_comment)
		{
			$journal_comment->debit_account=$req->get('debit_account');
			$journal_comment->approaval_status=$req->get('status');
			$journal_comment->approaved_amount=$req->get('amount');
			$journal_comment->remarks=$req->get('remarks');
			$journal_comment->approaved_by=\Auth::user()->id;

			$journal_comment->save();
		}
		else
		{
			$journal_comment=new JournalComment();

			$journal_comment->debit_account=$req->get('debit_account');
			$journal_comment->approaval_status=$req->get('status');
			$journal_comment->approaved_amount=$req->get('amount');
			$journal_comment->remarks=$req->get('remarks');
			$journal_comment->approaved_by=\Auth::user()->id;

			$journal_comment->save();
		}

		return response()->json(['ok'=>true]);
	}

	function payment($id)
	{
		//$data['journal_comment']=JournalComment::with('user')->where('debit_account',$id)->first();
		$data['fund_req']=FundRequest::where('id',$id)->first();
		$data['acc_head']=AccountHead::with('children')->where('type_id',1)->where('parent_head',0)->orderBy('name','asc')->get();
		$data['title']='Make Payment';
		return view('admin.journal.payment',$data);
	}

	function save_payment(Request $req)
	{
		$this->validate($req,[
			'hdn_id'=>'required',
			'account_head'=>'required',
			'amount'=>'required|numeric'
		]);

		$comment=$req->get('remarks');
		$head_id=$req->get('account_head');

		//Add Journal Entry
		$journal=new Journal();
		$journal->ref_id=$req->get('hdn_id');
		$journal->debit_account=5;
		$journal->credit_account=$head_id;
		$journal->description=$comment;
		$journal->amount=$req->get('amount');
		$journal->created_by=\Auth::user()->id;
		$journal->save();

		FundRequest::where('id',$req->get('hdn_req_id'))->delete();

		$req->session()->flash('success','Payment successfull !');
		return redirect('account/journal');	
	}
}