<?php

namespace App\Http\Controllers\Administrator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use App\User;
use App\SearchModel;
use Auth;
use DB;
use App\JournalModel;
use App\AccountChartModel;
use DataTables;
use App\BankModel;

class CapitalController extends Controller
{

    function __construct()
    {
        $this->middleware('permission:Capital-List');
        // $this->middleware('permission:Accounting-Capitalize-Create', ['only' => ['create','store']]);
        // $this->middleware('permission:Accounting-Capitalize-Edit', ['only' => ['edit','update']]);
    }

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

    public function get_capital_list(Request $request)
    {
        $search = $request->input('search.value');
        $count_total = 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(function ($query) {
                $query->orWhere('nso007_journal.journal_acccode',10000);
                $query->orWhere('nso007_journal.journal_acccode',10001);
            })
            ->where('journal_type' , '=' , '15')
            ->where('nso007_journal.branch_id' , '=' , \Branch::branch_id())
            ->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(function ($query) {
                $query->orWhere('nso007_journal.journal_acccode',10000);
                $query->orWhere('nso007_journal.journal_acccode',10001);
            })
            ->where('journal_type' , '=' , '15')
            ->where('nso007_journal.branch_id' , '=' , \Branch::branch_id())
            ->where(function($query) use ($search){
                $query->orWhere('nso007_account_chart.id' , 'LIKE' , '%'.$search.'%');
                $query->orWhere('nso007_account_chart.acc_name' , 'LIKE' , '%'.$search.'%');
                $query->orWhere('nso007_journal.journal_des' , 'LIKE' , '%'.$search.'%');
                $query->orWhere('nso007_journal.journal_invoice' , 'LIKE' , '%'.$search.'%');
            })

            ->count();

        $capital = 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_journal.journal_paydate AS do_date',
                'nso007_account_chart.id AS acc_code',
                'nso007_account_chart.acc_name AS acc_name',
                'nso007_journal.journal_debit AS debit_amount',
                'nso007_journal.journal_des AS description',
                'nso007_journal.journal_invoice AS reference',
                'users.user_code AS user_log_code',
                DB::raw("CONCAT(users.user_firstname,' ', users.user_lastname) as user_log_name")
            )
            ->where(function ($query) {
                $query->orWhere('nso007_journal.journal_acccode',10000);
                $query->orWhere('nso007_journal.journal_acccode',10001);
            })
            ->where('journal_type' , '=' , '15')
            ->where('nso007_journal.branch_id' , '=' , \Branch::branch_id())
            ->orderBy('id','DESC')
            ->take(20);


        return  Datatables::of($capital)
        ->addIndexColumn()
        ->with([
            "recordsTotal" => $count_total,
            "recordsFiltered" => $count_filter,
        ])
        ->addColumn('action', function($capital) {
           return '<a href="'.route("accouting-capital.edit",$capital->id).'" title="Edit"><span class="button_success fa fa-edit"></span></a>';
        })
        ->addColumn('debit_amount',function($capital){
            return '$ '.number_format($capital->debit_amount,2);
        })
        ->make(true);
    }

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

        $bank_data = BankModel::select('id', 'name', 'cash_flow_type')
        ->where('cash_flow_type', 10001)->where('status', 1)
        ->orderBy('id', 'DESC')
        ->pluck('name', 'id')
        ->prepend('Please Select', '');

        $account_chart = AccountChartModel::select(
                        DB::raw('CONCAT(id," ",acc_name) AS account_mixed'), 'id')
                        ->where('id', 11002)
                        ->pluck('account_mixed', 'id')
                        ->prepend('Please Select', '');

        return view('administrator.accounting.capital.create', compact('cash_flow', 'bank_data', 'account_chart'));
    }

    public function edit($id)
    {
        $journal = JournalModel::find($id);

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

        $bank_data = BankModel::select('id', 'name', 'cash_flow_type')
        ->where('cash_flow_type', 10001)->where('status', 1)
        ->orderBy('id', 'DESC')
        ->pluck('name', 'id')
        ->prepend('Please Select', '');

        $account_chart = AccountChartModel::select(
                        DB::raw('CONCAT(id," ",acc_name) AS account_mixed'), 'id')
                        ->where('id', 11002)
                        ->pluck('account_mixed', 'id')
                        ->prepend('Please Select', '');
        return view('administrator.accounting.capital.edit',compact('account_chart','journal', 'cash_flow', 'bank_data'));
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'cash_flow_id'       => '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    = 11002;
        $journal->journal_type       = 15;
        $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->pay_to             = $request->bank_id;
        $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       = 15;
        $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->pay_to             = $request->bank_id;
        $journal1->journal_currency   = 1;
        $journal1->branch_id          = \Branch::branch_id();
        $journal1->save();

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

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

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

        $journal = JournalModel::find($id);
        $journal_id = $journal->journal_parentid;

        $journal->journal_acccode    = $request->journal_acccode;
        $journal->journal_debit      = $request->journal_debit;
        $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->pay_to             = $request->pay_to;
        $journal->update();

        JournalModel::where('id', $journal_id)
        ->update([
            'journal_credit'           => $request->journal_debit,
            '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,
            'journal_by'               => $user_by,
            'pay_to'                   => $request->pay_to,
        ]);


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

    public function report()
    {
        $cash_flow = AccountChartModel::select('id', 'acc_name')
        ->whereIn('id', [10000, 10001])
        ->pluck('acc_name', 'id')
        ->prepend('Please Select', '');
        return view('administrator.accounting.capital.report',compact('cash_flow'));
    }

    public function get_report_capital_list(Request $request)
    {

        $search_datatable = $request->input('search.value');
        $count_total = DB::table('nso007_journal')
                       ->where(function ($query) {
                            $query->orWhere('nso007_journal.journal_acccode',10000);
                            $query->orWhere('nso007_journal.journal_acccode',10001);
                       })
                       ->where('nso007_journal.journal_type',15)
                       ->where('nso007_journal.branch_id',\Branch::branch_id())
                       ->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(function ($query) {
                            $query->orWhere('nso007_journal.journal_acccode',10000);
                            $query->orWhere('nso007_journal.journal_acccode',10001);
                       })
                       ->where('nso007_journal.journal_type',15)
                       ->where('nso007_journal.branch_id',\Branch::branch_id())
                       ->where(function ($query) use ($search_datatable) {
                           $query->orWhere('nso007_account_chart.acc_name','LIKE','%'.$search_datatable.'%');
                           $query->orWhere('nso007_account_chart.id','LIKE','%'.$search_datatable.'%');
                           $query->orWhere('nso007_journal.journal_paydate','LIKE','%'.$search_datatable.'%');
                           $query->orWhere('nso007_journal.journal_invoice','LIKE','%'.$search_datatable.'%');
                           $query->orWhere('nso007_journal.journal_des','LIKE','%'.$search_datatable.'%');
                       })
                       ->count();

        $capital = 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_journal.journal_paydate AS do_date',
                            'nso007_account_chart.id AS acc_code',
                            'nso007_account_chart.acc_name AS acc_name',
                            'nso007_journal.journal_debit AS debit_amount',
                            DB::raw("IFNULL(nso007_journal.journal_des,'N/A') AS description"),
                            'nso007_journal.journal_invoice AS reference',
                            'users.user_code AS user_log_code',
                            DB::raw("CONCAT(users.user_firstname,' ',users.user_lastname) AS user_log_name")
                       )
                       ->where(function ($query) {
                            $query->orWhere('nso007_journal.journal_acccode',10000);
                            $query->orWhere('nso007_journal.journal_acccode',10001);
                       })
                       ->where('nso007_journal.journal_type',15)
                       ->where('nso007_journal.branch_id',\Branch::branch_id())
                       ->orderBy('nso007_journal.id','desc')
                       ->take(20);
        

        if($request->isMethod('GET'))
        {
            return  Datatables::of($capital)
                ->with([
                    "recordsTotal" => $count_total,
                     "recordsFiltered" => $count_filter,
                ])
                ->addColumn('debit_amount',function($capital){
                    return '$ '.number_format($capital->debit_amount,2);
                })
                ->addColumn('do_date',function($capital){
                    return date('Y-m-d',strtotime($capital->do_date));
                })
                ->addIndexColumn()
                ->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));
            $capital = 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_journal.journal_paydate AS do_date',
                            'nso007_account_chart.id AS acc_code',
                            'nso007_account_chart.acc_name AS acc_name',
                            'nso007_journal.journal_debit AS debit_amount',
                            DB::raw("IFNULL(nso007_journal.journal_des,'N/A') AS description"),
                            'nso007_journal.journal_invoice AS reference',
                            'users.user_code AS user_log_code',
                            DB::raw("CONCAT(users.user_firstname,' ',users.user_lastname) AS user_log_name")
                       )
                       ->where(function ($query) {
                            $query->orWhere('nso007_journal.journal_acccode',10000);
                            $query->orWhere('nso007_journal.journal_acccode',10001);
                       })
                       ->where('nso007_journal.journal_type',15)
                       ->where('nso007_journal.branch_id',\Branch::branch_id())
                       ->where('nso007_journal.journal_acccode','LIKE',isset($request->cash_flow)? $request->cash_flow:NULL)
                       ->when(request('start_date', ''), function ($query) use ($from, $to){ 
                            $query->whereBetween('nso007_journal.journal_paydate', [$from, $to]);
                       })
                       ->orderBy('nso007_journal.id','desc')
                       ->get();
            echo json_encode($capital);
        }
        
    }

    public function get_report_capital_list_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));

        $mdoel_searching = new SearchModel();
        $journal_date =  (empty($start_date))? '':' nso007_journal.journal_paydate BETWEEN "'.$start_date.'" AND "'.$end_date.'" ';
        $cash_flow =  (empty($request->cash_flow))? '':' nso007_journal.journal_acccode = "'.$request->cash_flow.'" ';

        $data_search = array(
            'journal_date' =>$journal_date,
            'cash_flow' =>$cash_flow,
        );
        $search= $mdoel_searching->search($data_search);
        $search = (empty($search))? " WHERE (nso007_journal.journal_acccode = 10000 OR nso007_journal.journal_acccode = 10001) AND nso007_journal.journal_type = 15 AND nso007_journal.branch_id = ".\Branch::branch_id() :" " .$search. "  AND (nso007_journal.journal_acccode = 10000 OR nso007_journal.journal_acccode = 10001) AND nso007_journal.journal_type = 15  AND nso007_journal.branch_id = ".\Branch::branch_id() ;

        $capital = DB::select("
            SELECT nso007_journal.id,
            nso007_journal.journal_paydate AS do_date,
            nso007_account_chart.id AS acc_code,
            nso007_account_chart.acc_name AS acc_name,
            nso007_journal.journal_debit AS debit_amount,
            IFNULL(nso007_journal.journal_des, 'N/A') AS description,
            nso007_journal.journal_invoice AS reference,
            users.user_code AS user_log_code,
            CONCAT(users.user_firstname,' ',users.user_lastname) AS user_log_name
            FROM nso007_journal
            INNER JOIN users ON nso007_journal.journal_by = users.id
            INNER JOIN nso007_account_chart ON  nso007_journal.journal_acccode = nso007_account_chart.id
            $search
            ORDER BY nso007_journal.id DESC
        ");
        $total = 0 ;

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


}