<?php

namespace App\Http\Controllers\Administrator;
use function foo\func;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use Auth;
use DB;
use App\JournalModel;
use App\SearchModel;
use App\AccountChartModel;
use App\ProjectModel;
use App\NoteReceivableModel;
use DataTables;

class IncomeController extends Controller
{
    
    function __construct()
    {
        $this->middleware('permission:Income-List');
        // $this->middleware('permission:Accounting-Icome-Create', ['only' => ['create','store']]);
        // $this->middleware('permission:Accounting-Icome-Edit', ['only' => ['edit','update']]);
    }

    public function index()
    {
        return view('administrator.accounting.income.index');
    }

    public function get_income_list(Request $request)
    {
        $search = $request->input('search.value');
        $count_total = DB::table('nso007_journal')
            ->where('nso007_journal.branch_id' , '=' , \Branch::branch_id())
            ->where('nso007_journal.journal_acccode' , 'LIKE' , '4%')
            ->where('nso007_journal.journal_credit' , '>' , 0)
            ->count();

        $count_filter = DB::table('nso007_journal')
            ->leftjoin('users', 'users.id', '=', 'nso007_journal.journal_by')
            ->leftjoin('nso007_account_chart', 'nso007_journal.journal_acccode', '=', 'nso007_account_chart.id')

            ->where('nso007_journal.branch_id' , '=' , \Branch::branch_id())
            ->where('nso007_journal.journal_acccode' , 'LIKE' , '4%')
            ->where('nso007_journal.journal_credit' , '>' , 0)
            ->where(function($query) use ($search){
                $query->orWhere('nso007_journal.journal_acccode' , 'LIKE' , '%'.$search.'%');
                $query->orWhere('nso007_journal.journal_des' , 'LIKE' , '%'.$search.'%');
                $query->orWhere('nso007_journal.journal_invoice' , 'LIKE' , '%'.$search.'%');
                $query->orWhere('nso007_account_chart.acc_name' , 'LIKE' , '%'.$search.'%');
            })
            ->count();

        $income = DB::table('nso007_journal')
            ->leftjoin('users', 'users.id', '=', 'nso007_journal.journal_by')
            ->leftjoin('nso007_account_chart', 'nso007_journal.journal_acccode', '=', 'nso007_account_chart.id')
            ->select(
                'nso007_journal.id',
                'nso007_account_chart.acc_name AS income_title',
                'nso007_account_chart.id AS income_code',
                'nso007_journal.journal_credit AS income_amount',
                DB::raw("IFNULL(nso007_journal.journal_des, 'N/A') as income_des"),
                'nso007_journal.journal_invoice AS income_invoice',
                'users.user_code AS user_code_by',
                DB::raw("CONCAT(users.user_firstname,' ', users.user_lastname) as user_name_by"),
                'nso007_journal.journal_paydate AS do_date'
            )
            ->where('nso007_journal.branch_id' , '=' , \Branch::branch_id())
            ->where('nso007_journal.journal_acccode' , 'LIKE' , '4%')
            ->where('nso007_journal.journal_credit' , '>' , 0)
            ->orderBy('id','asc')
            ->take(20);
        return  Datatables::of($income)
        ->addIndexColumn()
        ->with([
            "recordsTotal" => $count_total,
            "recordsFiltered" => $count_filter,
        ])
        ->addColumn('action', function($capital) {
           return '<a href="'.route("accouting-income.edit",$capital->id).'" title="Edit"><span class="button_success fa fa-edit"></span></a>';
        })
        ->addColumn('income_amount',function($capital){
            return '$'.number_format($capital->income_amount,2);
        })
        ->addColumn('do_date',function($capital){
            return date('Y-m-d', strtotime($capital->do_date));
        })

        ->make(true);
    }

    public function create()
    {
        $cash_flow = AccountChartModel::select('id', 'acc_name')
        ->whereIn('id', [10000, 10001])
        ->pluck('acc_name', 'id')
        ->prepend('Please Select', '');

        $account_chats = AccountChartModel::select(
                        DB::raw('CONCAT(id," ",acc_name) AS account_mixed'),'id')
                        ->where('id','LIKE','4%')
                        ->pluck('account_mixed','id')
                        ->prepend('Please Select', '');
        $projects = ProjectModel::when(empty(\Branch::branch_key()), function($query){
            $query->where('branch_id',\Branch::branch_id());
        })->pluck('project_name','id')->prepend('Please Select Option', '')->toArray();

        return view('administrator.accounting.income.create',compact('account_chats', 'cash_flow', 'projects'));
    }

    public function edit($id)
    {
        $cash_flow = AccountChartModel::select('id', 'acc_name')
        ->whereIn('id', [10000, 10001])
        ->pluck('acc_name', 'id')
        ->prepend('Please Select', '');
        $journal = JournalModel::find($id);
        $account_chats = AccountChartModel::select(
                        DB::raw('CONCAT(id," ",acc_name) AS account_mixed'),'id')
                        ->where('id','LIKE','4%')
                        ->pluck('account_mixed','id')
                        ->prepend('Please Select', '');
        $projects = ProjectModel::select(
                    DB::raw('CONCAT(project_code," / ",project_name) AS project_mixed'),'id')
                    ->pluck('project_mixed','id')
                    ->prepend('Please Select', '');
        return view('administrator.accounting.income.edit',compact('account_chats','journal', 'cash_flow', 'projects'));
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'pay_for'           => 'required',
            'cash_flow_id'      => 'required',
            'journal_acccode'   => 'required',
            'amount'            => 'required|numeric',
            'journal_paydate'   => 'required',
        ]);

        $user_by = Auth::user()->id;

        $journal = new JournalModel;
        $journal1 = new JournalModel;

        $journal->journal_parentid   = 0;
        $journal->journal_acccode    = $request->journal_acccode;
        $journal->journal_type       = 4;
        $journal->journal_credit     = $request->amount;
        $journal->journal_invoice    = $request->journal_invoice;
        $journal->journal_transactiondate    = date('Y-m-d H:i:s A');
        $journal->journal_paydate    = date('Y-m-d',strtotime($request->journal_paydate));
        $journal->journal_des        = $request->journal_des;
        $journal->journal_by         = $user_by;
        $journal->cash_flow_bank     = $request->cash_flow_id;
        $journal->pay_for            = $request->pay_for;
        $journal->journal_currency   = 1;
        $journal->branch_id          = \Branch::branch_id();
        $journal->save();

        $max_journal_id = DB::table('nso007_journal')->max('id');

        $journal1->journal_parentid   = $max_journal_id;
        $journal1->journal_acccode    = $request->cash_flow_id;
        $journal1->journal_type       = 4;
        $journal1->journal_debit      = $request->amount;
        $journal1->journal_invoice    = $request->journal_invoice;
        $journal1->journal_transactiondate    = date('Y-m-d H:i:s A');
        $journal1->journal_paydate    = date('Y-m-d',strtotime($request->journal_paydate));
        $journal1->journal_des        = $request->journal_des;
        $journal1->journal_by         = $user_by;
        $journal1->cash_flow_bank     = $request->cash_flow_id;
        $journal1->pay_for            = $request->pay_for;
        $journal1->journal_currency   = 1;
        $journal1->branch_id          = \Branch::branch_id();
        $journal1->save();

        $data = array(
            'project_id'            => $request->pay_for, 
            'journal_id'            => $max_journal_id,
            'amount_received'       => $request->amount, 
            'user_log'              => $user_by
        );
        NoteReceivableModel::insert($data);

        \LogActivity::addToLog('Income created successfully!');
        return redirect()->route('accouting-income.index');
    }

    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'pay_for'           => 'required',
            'cash_flow_bank'    => 'required',
            'journal_acccode'   => 'required',
            'journal_credit'    => 'required|numeric',
            'journal_paydate'   => 'required',
        
        ]);

        $user_by = Auth::user()->id;
        
        NoteReceivableModel::where('journal_id', $id)
        ->update([
            'project_id'        => $request->pay_for,
            'amount_received'   => $request->journal_credit,
            'user_log'          => $user_by,
        ]);

        $journal = JournalModel::find($id);

        $journal->journal_acccode    = $request->journal_acccode;
        $journal->journal_credit     = $request->journal_credit;
        $journal->journal_invoice    = $request->journal_invoice;
        $journal->journal_transactiondate    = date('Y-m-d H:i:s A');
        $journal->journal_paydate    = date('Y-m-d',strtotime($request->journal_paydate));
        $journal->journal_des        = $request->journal_des;
        $journal->journal_by         = $user_by;
        $journal->cash_flow_bank     = $request->cash_flow_bank;
        $journal->pay_for            = $request->pay_for;
        $journal->update();

        DB::table('nso007_journal')
            ->where('journal_parentid',$id)
            ->update([
                'journal_acccode'       => $request->cash_flow_bank,
                'journal_debit'         => $request->journal_credit,
                'journal_invoice'       => $request->journal_invoice,
                'journal_transactiondate' => date('Y-m-d H:i:s A'),
                'journal_paydate'       => date('Y-m-d',strtotime($request->journal_paydate)),
                'journal_des'           => $request->journal_des,
                'cash_flow_bank'        => $request->cash_flow_bank,
                'pay_for'               => $request->pay_for,
            ]);

        \LogActivity::addToLog('Income Updated successfully!');
        return redirect()->route('accouting-income.index');
    }

    public function report()
    {
        $account_chats = AccountChartModel::select(
                        DB::raw('CONCAT(id," ",acc_name) AS account_mixed'),'id')
                        ->where('id','LIKE','4%')
                        ->pluck('account_mixed','id')
                        ->prepend('Please Select', '');

        return view('administrator.accounting.income.report',compact('account_chats'));
    }

    public function get_report_income_list(Request $request)
    {
        $search_datatable = $request->input('search.value');
        $count_total = DB::table('nso007_journal')
                            ->where('nso007_journal.branch_id',\Branch::branch_id())
                            ->where('nso007_journal.journal_acccode','LIKE','4%')
                            ->where('nso007_journal.journal_credit','>',0)
                            ->count();
        $count_filter = DB::table('nso007_journal')
                            ->join('users','users.id','nso007_journal.journal_by')
                            ->join('nso007_account_chart','nso007_account_chart.id','nso007_journal.journal_acccode')
                            ->where('nso007_journal.branch_id',\Branch::branch_id())
                            ->where('nso007_journal.journal_acccode','LIKE','4%')
                            ->where('nso007_journal.journal_credit','>',0)
                            ->where(function($query) use ($search_datatable){
                                $query->orWhere('nso007_account_chart.id','LIKE','%'.$search_datatable.'%');
                                $query->orWhere('nso007_account_chart.acc_name','LIKE','%'.$search_datatable.'%');
                                $query->orWhere('nso007_journal.journal_invoice','LIKE','%'.$search_datatable.'%');
                                $query->orWhere('nso007_journal.journal_credit','LIKE','%'.$search_datatable.'%');
                                $query->orWhere('nso007_journal.journal_des','LIKE','%'.$search_datatable.'%');
                                $query->orWhere('nso007_journal.journal_paydate','LIKE','%'.$search_datatable.'%');
                            })
                            ->count();

        $income = DB::table('nso007_journal')
                      ->join('users','users.id','nso007_journal.journal_by')
                      ->join('nso007_account_chart','nso007_account_chart.id','nso007_journal.journal_acccode')
                      ->select(
                            'nso007_journal.id',
                            'nso007_account_chart.acc_name AS income_title',
                            'nso007_account_chart.id AS income_code',
                            'nso007_journal.journal_credit AS income_amount',
                            'nso007_journal.journal_invoice AS income_invoice',
                            'users.user_code AS user_code_by',
                            'nso007_journal.journal_paydate AS do_date',
                            DB::raw("IFNULL(nso007_journal.journal_des,'N/A') AS income_des"),
                            DB::raw("CONCAT(users.user_firstname,' ',users.user_lastname) AS user_name_by")
                      )
                      ->where('nso007_journal.branch_id',\Branch::branch_id())
                      ->where('nso007_journal.journal_acccode','LIKE','4%')
                      ->where('nso007_journal.journal_credit','>',0)
                      ->orderBy('nso007_journal.id','asc')
                      ->take(20);

        if($request->isMethod('GET'))
        {
            return  Datatables::of($income)
                ->addIndexColumn()
                ->with([
                    "recordsTotal" => $count_total,
                     "recordsFiltered" => $count_filter,
                ])
                ->addColumn('income_amount',function($capital){
                    return '$'.number_format($capital->income_amount,2);
                })
                ->addColumn('do_date',function($capital){
                     return date('Y-m-d', strtotime($capital->do_date));
                })
                ->make(true);
        }else{
            $start_date =  (empty($request->start_date))? '': date('Y-m-d',strtotime($request->start_date));
            $end_date   =  (empty($request->end_date))? '': date('Y-m-d',strtotime($request->end_date));
            $incomes = DB::table('nso007_journal')
                      ->join('users','users.id','nso007_journal.journal_by')
                      ->join('nso007_account_chart','nso007_account_chart.id','nso007_journal.journal_acccode')
                      ->select(
                            'nso007_journal.id',
                            'nso007_account_chart.acc_name AS income_title',
                            'nso007_account_chart.id AS income_code',
                            'nso007_journal.journal_credit AS income_amount',
                            'nso007_journal.journal_invoice AS income_invoice',
                            'users.user_code AS user_code_by',
                            'nso007_journal.journal_paydate AS do_date',
                            DB::raw("IFNULL(nso007_journal.journal_des,'N/A') AS income_des"),
                            DB::raw("CONCAT(users.user_firstname,' ',users.user_lastname) AS user_name_by")
                      )
                      ->where('nso007_journal.branch_id',\Branch::branch_id())
                      ->where('nso007_journal.journal_acccode','LIKE','4%')
                      ->where('nso007_journal.journal_credit','>',0)
                      ->where('nso007_journal.journal_acccode','LIKE',isset($request->journal_acccode)? $request->journal_acccode:NULL)
                      ->when(request('start_date', ''), function ($query) use ($start_date, $end_date){ 
                            $query->whereBetween('nso007_journal.journal_paydate', [$start_date, $end_date]);
                      })
                      ->orderBy('nso007_journal.id','desc')
                      ->get();
            echo json_encode($incomes);
        }
    }

    public function report_print(Request $request)
    {
            $start_date =  (empty($request->start_date))? '': date('Y-m-d',strtotime($request->start_date));
            $end_date   =  (empty($request->end_date))? '': date('Y-m-d',strtotime($request->end_date));
            $income = DB::table('nso007_journal')
                      ->join('users','users.id','nso007_journal.journal_by')
                      ->join('nso007_account_chart','nso007_account_chart.id','nso007_journal.journal_acccode')
                      ->select(
                            'nso007_journal.id',
                            'nso007_account_chart.acc_name AS income_title',
                            'nso007_account_chart.id AS income_code',
                            'nso007_journal.journal_credit AS income_amount',
                            'nso007_journal.journal_invoice AS income_invoice',
                            'users.user_code AS user_code_by',
                            'nso007_journal.journal_paydate AS do_date',
                            DB::raw("IFNULL(nso007_journal.journal_des,'N/A') AS income_des"),
                            DB::raw("CONCAT(users.user_firstname,' ',users.user_lastname) AS user_name_by")
                      )
                      ->where('nso007_journal.branch_id',\Branch::branch_id())
                      ->where('nso007_journal.journal_acccode','LIKE','4%')
                      ->where('nso007_journal.journal_credit','>',0)
                      ->where('nso007_journal.journal_acccode','LIKE',isset($request->journal_acccode)? $request->journal_acccode:NULL)
                      ->when(request('start_date', ''), function ($query) use ($start_date, $end_date){ 
                            $query->whereBetween('nso007_journal.journal_paydate', [$start_date, $end_date]);
                      })
                      ->orderBy('nso007_journal.id','desc')
                      ->get();

        $total = 0;
        foreach ($income as $key => $value) {
            $total += $value->income_amount;
        }
        $branch = DB::table('nso007_branches')->where('id',\Branch::branch_id())->first()   ;
        return view('administrator.accounting.income.report-view-print',compact('income','total','branch'));
    }
}
