<?php

namespace App\Http\Controllers\Administrator;

use App\AccountChartModel;
use App\AccountTypeModel;
use App\Helpers\Branch;
use App\ProjectModel;
use App\SupplierModel;
use App\User;
use Gate;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\JournalModel;
use Yajra\DataTables\DataTables;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Zendesk\API\Resources\Core\Users;

class JournalController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    function __construct()
    {
//        $this->middleware('permission:Journal-List');
//        $this->middleware('permission:Journal-Create', ['only' => ['create', 'store']]);
//        $this->middleware('permission:Journal-Voucher-Print', ['only' => ['print_voucher']]);
    }
    public function index()
    {
        $acc_code       = AccountChartModel::select('code',DB::raw('CONCAT(code," ",acc_name) AS account_mixed'))
            ->pluck('account_mixed', 'code')
            ->prepend('Please Select', '');
        $projects = ProjectModel::select(
            DB::raw('CONCAT(id," ",project_name) AS project'),
            'id'
        )
            ->pluck('project', 'id')
            ->prepend('Please Select', '');
        $supplier = SupplierModel::select(
            DB::raw('CONCAT(supplier_code," ",supplier_name) AS supplier'),
            'id'
        )
            ->pluck('supplier', 'id')
            ->prepend('Please Select', '');
        return view('administrator.accounting.journal.index', ['acc_code' => $acc_code,'projects' => $projects,'supplier' => $supplier]);
    }
    public function get_journal(Request $request)
    {
        if($request->isMethod('get')){
            $data = DB::table('nso007_journal as jn')
                ->join('nso007_account_chart as chart', 'chart.code', '=', 'jn.journal_acccode')
                ->leftjoin('nso007_project_stock as project', 'project.id', '=', 'jn.journal_by_project')
                ->leftjoin('nso007_supplier as supplier', 'supplier.id', '=', 'jn.journal_by_supplier')
                ->leftjoin('users', 'users.id', 'jn.journal_by')
                ->select(
                    'chart.acc_name',
                    'chart.code as account_code',
                    'jn.id',
                    'jn.journal_des',
                    'jn.journal_debit',
                    'jn.journal_credit',
                    'jn.journal_invoice',
                    'jn.journal_paydate',
                    'jn.journal_reference_number',
                    'project.project_name',
                    'supplier.supplier_name',
                    'jn.voucher_type',
                    'jn.voucher_ref',
                    'jn.journal_audit_status',
                    'jn.journal_tran_id as tran_id',
                    'jn.journal_status',
                    DB::raw("CONCAT(users.user_firstname,' ',users.user_lastname) AS user_name")
                )
                ->orderby('jn.journal_paydate','DESC');
            $count_total = $data->count();
            $data = $data->take(20);
            return DataTables::of($data)
                ->with([
                    "recordsTotal" => $count_total,
                    "recordsFiltered" => $count_total,
                ])
                ->editColumn('id', '{{$tran_id}}')
                ->editColumn('voucher', function ($data) {
                    $voucher = "";
                    if ($data->voucher_type == 1) {
                        $voucher = "Cash Receipt";
                    } else if ($data->voucher_type == 2) {
                        $voucher = "Cash Disbursement";
                    } else if ($data->voucher_type == 3) {
                        $voucher = "Cash Reimbursement";
                    } else if ($data->voucher_type == 4) {
                        $voucher = "Cash Advance";
                    } else if ($data->voucher_type == 5) {
                        $voucher = "Advance Settlement";
                    } else if ($data->voucher_type == 6) {
                        $voucher = "Journal Entry/Adjustment";
                    }
                    return $voucher;
                })
//                ->editColumn('checkbox', function ($data) {
//                    return '<label><input id="' . $data->id . '" class="checkbox" type="checkbox"></label>';
//                })
                ->editColumn('account_code', function ($data) {
                    return $data->account_code . " " . $data->acc_name;
                })
                ->editColumn('journal_paydate', function ($data) {
                    return date('Y-m-d',strtotime($data->journal_paydate));
                })
                ->editColumn('journal_debit', function ($data) {
                    return $data->journal_debit<0?number_format(abs($data->journal_debit),2):number_format($data->journal_debit,2);
                })
                ->editColumn('journal_credit', function ($data) {
                    return $data->journal_credit<0?number_format(abs($data->journal_credit),2):number_format($data->journal_credit,2);
                })
                ->addColumn('action',function($data){
                    $btn_edit = '';
                    $btn_delete = '';
                    $btn_printv = '';
                    if($data->journal_status==0){
                        if(Gate::check('Journal-Edit'))
                            $btn_edit.= '<a href="'.route('journal.edit',$data->id).'" class="btn btn-sm btn-success"><i class="fa fa-edit"></i></a> ';
                        if(Gate::check('Journal-Delete'))
                            $btn_delete.= '<a href="#" data-id="'.$data->id.'" data-toggle="modal" data-target="#form-delete" class="btn btn-sm btn-danger confirm_delete"><i class="fa fa-trash"></i></a>';
                    }
                    $btn_printv.= '<a href="'.route('voucher.print',$data->voucher_ref).'" class="btn btn-sm btn-primary"><i class="fa fa-print"></i></a> ';
                    return $btn_printv.$btn_edit.$btn_delete;
                })
                ->rawColumns(['checkbox' => 'checkbox', 'tran_id' => 'tran_id','action' => 'action'])
                ->make(true);
        }
        else{
            $from =  (empty($request->start_date))? '': date('Y-m-d',strtotime($request->start_date));
            $to =  (empty($request->end_date))? '': date('Y-m-d',strtotime($request->end_date));
            $ref =  (isset($request->ref) ? $request->ref : null);
            $project_id =  $request->project_id;
            $journal_code =  $request->journal_code;
            $data   = DB::table('nso007_journal as jn')
                ->join(DB::raw("(SELECT chart.acc_name, 
                                            chart.acc_namekh,
                                            chart.code,
                                            SUM(jn.journal_debit) as journal_debit,
                                            SUM(jn.journal_credit) as journal_credit
                                    FROM nso007_journal as jn INNER JOIN nso007_account_chart as chart ON chart.code = jn.journal_acccode
                                    GROUP BY chart.code) charts"), 'charts.code', 'jn.journal_acccode')
                ->leftjoin('nso007_project_stock as project', 'project.id', '=', 'jn.journal_by_project')
                ->select(
                    'charts.acc_name',
                    'charts.code as account_code',
                    'jn.id',
                    'jn.journal_des',
                    'jn.journal_des',
                    'jn.journal_debit',
                    'jn.journal_credit',
                    'jn.journal_invoice',
                    'jn.journal_paydate',
                    'jn.journal_debit',
                    'jn.journal_debit',
                    'jn.journal_credit',
                    'jn.branch_id',
                    'project.project_name as project_name',
                    DB::raw('(CASE
                WHEN jn.voucher_type = "1" THEN "Cash Receipt"
                WHEN jn.voucher_type = "2" THEN "Cash Disbursement"
                WHEN jn.voucher_type = "3" THEN "Cash Reimbursement"
                WHEN jn.voucher_type = "4" THEN "Cash Advance"
                WHEN jn.voucher_type = "5" THEN "Advance Settlement"
                WHEN jn.voucher_type = "6" THEN "Journal Entry/Adjustment" END) AS voucher_type'),
                    'jn.voucher_ref',
                    'jn.journal_status',
                    'jn.journal_tran_id as tran_id'
                )
//                ->where("jn.branch_id",auth()->user()->branch_id)
                ->when($ref,function ($q) use($ref)
                {
                    $q->where('jn.voucher_ref','LIKE','%'.$ref.'%');
                })
                ->when(!empty($project_id),function($q) use($project_id){
                    $q->where('jn.journal_by_project',$project_id);
                })
                ->when(!empty($journal_code),function($q) use($journal_code){
                    $q->where('jn.journal_acccode',$journal_code);
                })
                ->when(request('start_date',''),function($q) use($from, $to){
                    $q->whereBetween('journal_paydate',[$from,$to]);
                });
            echo json_encode($data);
        }
    }
    public function print_voucher($voucher)
    {
        $branch     = DB::table('nso007_branches')->where('id', Branch::branch_id())->first();
        $journal = DB::table('nso007_journal as jn')->join('nso007_account_chart as chart', 'chart.code', 'jn.journal_acccode')
            ->select('chart.acc_name', 'chart.acc_namekh', 'jn.*')
            ->where('jn.voucher_ref', $voucher)
//            ->where('jn.branch_id', Branch::branch_id())
//            ->groupBy('chart.code')
            ->orderBy('jn.id','ASC')
            ->get();
        $projects = ProjectModel::where('id',$journal[0]->journal_by_project)->first();
        $user = User::where('id',$journal[0]->journal_by)->first();
        return view('administrator.accounting.journal.report-print-voucher', ['projects' => $projects,'user' => $user, 'data' => $journal]);
    }
    public function create()
    {
        $acc_chart       = AccountChartModel::select('code',DB::raw('CONCAT(code," ",acc_name) AS account_mixed'))
            ->pluck('account_mixed', 'code')
            ->prepend('Please Select', '');
        $max = JournalModel::max('journal_tran_id');
        $voucher_ref = $max + 1;
        (string) $voucher_ref;
        while (strlen($voucher_ref) < 8) {
            $voucher_ref = "0" . $voucher_ref;
        }
        $voucher_ref = "V-" . $voucher_ref;
        $projects = ProjectModel::select(
            DB::raw('CONCAT(id," ",project_name) AS project'),
            'id'
        )
            ->pluck('project', 'id')
            ->prepend('Please Select', '');
        $supplier = SupplierModel::select(
            DB::raw('CONCAT(id," ",supplier_name) AS supplier'),
            'id'
        )
            ->pluck('supplier', 'id')
            ->prepend('Please Select', '');
        return view('administrator.accounting.journal.create', ['acc_chart' => $acc_chart,'supplier' => $supplier, 'projects' => $projects, 'voucher_ref' => $voucher_ref]);
    }
    public function query_account_code(Request $request)
    {
        $account_code = $request->obj;
        $account_chart = AccountChartModel::where('acctype', $account_code)->get();
        echo \json_encode($account_chart);
    }
    public function store(Request $request)
    {
        $this->validate($request, [
            'date'          => 'required',
            'voucher_type'  => 'required',
            'voucher_ref'   => 'required',
            'acc_chart'      => 'required',
//            'ref_number'    => 'required',
            'debit'         => 'required',
            'credit'        => 'required'
        ]);
        $max_id             = JournalModel::max('id');
        $max_tran_journal   = JournalModel::max('journal_tran_id');
        if (!$max_tran_journal) {
            $max_tran_journal = 0;
        }
        $journal_tran_id = $max_tran_journal + 1;
        $date = date('Y-m-d', strtotime($request->date));
        if (!$max_id) {
            $max_id     =   0;
        }
        $parent_id      = $max_id + 1;
        foreach ($request->acc_chart as $key => $type) {
            $acc_type=AccountChartModel::where('code',$request->acc_chart[$key])->first();

            $type_id=AccountTypeModel::find($acc_type->type_id);
            if ($key ==  0) {
                JournalModel::insert([
                    'journal_parentid'          => 0,
                    'branch_id'                 => auth()->user()->branch_id,
                    'journal_type'              => $type_id->id,
                    'journal_acccode'           => $request->acc_chart[$key],
                    'voucher_type'              => $request->voucher_type,
                    'voucher_ref'               => $request->voucher_ref,
                    'journal_des'               => $request->description[$key],
                    'journal_debit'             => $request->debit[$key],
                    'journal_credit'            => $request->credit[$key],
                    'journal_paydate'           => $date,
                    'journal_by'                => Auth::user()->id,
                    'journal_invoice'           => $request->ref_number,
                    'journal_transactiondate'   => date('Y-m-d H:i:s'),
                    'journal_tran_id'           => $journal_tran_id,
                    'journal_by_project'        => $request->journal_by_project,
                    'journal_by_supplier'       => $request->journal_by_supplier,
                    'journal_status'           => 0
                ]);
            }
            else if ($key > 0) {
                JournalModel::insert([
                    'journal_parentid'          => $parent_id,
                    'branch_id'                 => auth()->user()->branch_id,
                    'journal_type'              => $type_id->id,
                    'journal_acccode'           => $request->acc_chart[$key],
                    'voucher_type'              => $request->voucher_type,
                    'voucher_ref'               => $request->voucher_ref,
                    'journal_des'               => $request->description[$key],
                    'journal_debit'             => $request->debit[$key],
                    'journal_credit'            => $request->credit[$key],
                    'journal_paydate'           => $date,
                    'journal_by'                => Auth::user()->id,
                    'journal_invoice'           => $request->ref_number,
                    'journal_transactiondate'   => date('Y-m-d H:i:s'),
                    'journal_tran_id'           => $journal_tran_id,
                    'journal_by_project'        => $request->journal_by_project,
                    'journal_by_supplier'       => $request->journal_by_supplier,
                    'journal_status'           => 0
                ]);
            } else {
                break;
            }
        }
        return back()->with('success', 'Journal Added Successfully');
    }

    public function show($id)
    {
        //
    }

    public function edit($id)
    {
        $journal = JournalModel::where(function($query) use($id){
            $jn = JournalModel::find($id);
            $query->where('journal_tran_id',$jn->journal_tran_id);
        })->orderBy('id','asc')->get();
        $voucher = "";
        if ($journal[0]->voucher_type == 1) {
            $voucher = "Cash Receipt";
        } else if ($journal[0]->voucher_type == 2) {
            $voucher = "Cash Disbursement";
        } else if ($journal[0]->voucher_type == 3) {
            $voucher = "Cash Reimbursement";
        } else if ($journal[0]->voucher_type == 4) {
            $voucher = "Cash Advance";
        } else if ($journal[0]->voucher_type == 5) {
            $voucher = "Advance Settlement";
        } else if ($journal[0]->voucher_type == 6) {
            $voucher = "Journal Entry/Adjustment";
        }
        $acc_chart       = AccountChartModel::select('code',DB::raw('CONCAT(code," ",acc_name) AS account_mixed'))
            ->pluck('account_mixed', 'code')
            ->prepend('Please Select', '');

        $projects = ProjectModel::select(
            DB::raw('CONCAT(id," ",project_name) AS project'),
            'id'
        )
            ->pluck('project', 'id')
            ->prepend('Please Select', '');
        $supplier = SupplierModel::select(
            DB::raw('CONCAT(id," ",supplier_name) AS supplier'),
            'id'
        )
            ->pluck('supplier', 'id')
            ->prepend('Please Select', '');
        return view('administrator.accounting.journal.edit',compact('supplier','projects','journal','voucher','acc_chart'));
    }

    public function update(Request $request, $id)
    {
        $journal_id = $request->journal_id;
        $ids = [];
        $preID = null;
        $acc_code = [];
        foreach($journal_id as $jn_id){
            if(!empty($jn_id)){
                array_push($ids,$jn_id);
            }
        }

        foreach($journal_id as $i => $jn_id){
            $acc_type=AccountChartModel::where('code',$request->acc_chart[$i])->first();

            $type_id=AccountTypeModel::find($acc_type->type_id);
            if(!empty($jn_id))
            {
                if($i==0){
                    $preID = $jn_id;
                }
                JournalModel::where('id',$jn_id)->update([
                    'journal_acccode'=> $request->acc_chart[$i],
                    'branch_id'                 => auth()->user()->branch_id,
                    'voucher_type'=> $request->voucher_type,
                    'voucher_ref'=>$request->voucher_ref,
                    'journal_type'=> $type_id->id,
                    'journal_des'=> $request->description[$i],
                    'journal_debit'=>$request->debit[$i],
                    'journal_credit'=> $request->credit[$i],
                    'journal_paydate'=>date('Y-m-d',strtotime($request->journal_paydate)),
                    'journal_by_project'        => $request->journal_by_project,
                    'journal_invoice'=> $request->ref_number,
//                    'journal_by_supplier'       => $request->journal_by_supplier,
                    'journal_status' => 0
                ]);
            }
            else
            {
                JournalModel::insert([
                    'journal_parentid'=> JournalModel::find($preID)->id,
                    'branch_id'                 => auth()->user()->branch_id,
                    'journal_acccode '=> $request->acc_chart[$i],
                    'voucher_type'=> $request->voucher_type,
                    'voucher_ref'=>$request->voucher_ref,
                    'journal_type'=> $type_id->id,
                    'journal_des'=> $request->description[$i],
                    'journal_debit'=>$request->debit[$i],
                    'journal_credit'=> $request->credit[$i],
                    'journal_paydate'=>date('Y-m-d',strtotime($request->journal_paydate)),
                    'journal_by_project'        => $request->journal_by_project,
                    'journal_invoice'=> $request->ref_number,
                    'journal_status'=>0,
//                    'journal_by_supplier'       => $request->journal_by_supplier,
                    'journal_tran_id'=> JournalModel::find($preID)->journal_tran_id
                ]);
            }

        }
        return redirect()->route('journal.index')->with('success','Journal Successfully Updated');
    }

    public function destroy($id)
    {
        //
    }
    public function journal_confirm_delete(Request $request)
    {
        $id = $request->delete_id;
        DB::table('nso007_journal')->where(function($query) use($id){
            $jn = DB::table('nso007_journal')->where('id',$id)->select('*')->first();
            $query->where('journal_tran_id',$jn->journal_tran_id);
        })->delete();
        return response()->json(['success' => true,'message' => 'Journal Delete Successfully']);
    }
}
