<?php

namespace App\Http\Controllers\Accounting;

use App\Model\account\AccountChartModel;
use App\Model\account\AccountTypeModel;
use App\Model\people\SupplierModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\account\JournalModel;
use App\VoucherModel;
use Yajra\DataTables\DataTables;
use DB;
use Auth;
use Gate;

class JournalController extends Controller
{

    function __construct()
    {
//        $this->middleware('permission:Accounting-Journal-List', ['only' => ['index']]);
//        $this->middleware('permission:Accounting-Journal-Create', ['only' => ['create','store']]);
//        $this->middleware('permission:Accounting-Journal-Edit', ['only' => ['edit','update']]);
//        $this->middleware('permission:Accounting-Journal-Delete', ['only' => 'confirm_delete']);
//        $this->middleware('permission:Accounting-Journal-Print-Voucher', ['only' => ['print_voucher']]);
    }

    public function index()
    {
        $acc_code = AccountChartModel::select('id', 'acc_name')
            ->pluck('acc_name', 'id')
            ->prepend('Please Select', '');

        return view('Accounting.journal.index', ['acc_code' => $acc_code]);
    }

    public function get_journal(Request $request)
    {
        if ($request->ajax()) {
            $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 = $request->reference_no;
            $data = JournalModel::leftjoin('nso007_account_chart as chart', 'chart.id', '=', 'nso007_journal.journal_acccode')
                ->leftjoin('nso007_branch', 'nso007_branch.id', '=', 'nso007_journal.branch_id')
                ->leftjoin('users', 'users.id', 'nso007_journal.journal_by')
                ->selectRaw(
                    'chart.acc_name,
                    chart.id as account_code,
                    nso007_journal.id,
                    nso007_journal.journal_tran_id,
                    nso007_journal.journal_des,
                    nso007_journal.journal_debit,
                    nso007_journal.journal_credit,
                    nso007_journal.journal_invoice,
                    nso007_journal.journal_paydate,
                    nso007_journal.journal_reference_number,
                    nso007_branch.name as branch_name,
                    nso007_journal.voucher_type,
                    nso007_journal.voucher_ref,
                    nso007_journal.journal_audit_status,
                    nso007_journal.journal_tran_id as tran_id,
                    nso007_journal.journal_status,
                    nso007_journal.journal_currency,
                    nso007_journal.journal_referenceid,
                    nso007_journal.transaction_type,
                    users.name,SUM(nso007_journal.journal_debit) as debit,SUM(nso007_journal.journal_credit) as credit'
                )
                ->when(request('start_date', ''), function ($q) use ($from, $to) {
                    $q->whereBetween('journal_paydate', [$from, $to]);
                })
                ->where(function ($query) {
                    $query->where('nso007_journal.branch_id', myBranch()->id);
                })
                ->where(function ($query) use ($ref) {
                    if ($ref) {
                        $query->where('nso007_journal.journal_reference_number', $ref);
                    }
                })
                ->groupBy('nso007_journal.journal_tran_id')
                ->orderby('nso007_journal.journal_tran_id', 'DESC');
            return DataTables::of($data)
                ->editColumn('journal_paydate', function ($data) {
                    return myDate($data->journal_paydate);
                })
                ->editColumn('voucher', function ($data) {
                    if ($data->voucher_type) {
                        return getVoucherType($data->voucher_type);
                    }
                })
                ->addColumn('action', function ($data) {
                    $btn_edit = '';
                    $btn_delete = '';
                    if ($data->journal_status == 0 && $data->journal_audit_status == 0) {
                        if (!$data->journal_referenceid) {
                            $btn_edit .= '<a data-href="' . route('journal.edit', $data->journal_tran_id) . '" data-text="Edit Journal" class="btn btn-warning btn-xs btn_action"><i class="fa fa-edit"></i></a> ';
                            $btn_delete .= ' <a data-href="' . route('journal_confirm_delete',$data->journal_tran_id) . '"  class="btn btn-danger btn_delete btn-xs"><i class="fa fa-trash"></i></a> ';
                        }
                    }
                    return $btn_edit . $btn_delete;
                })
                ->editColumn('checkbox', function ($data) {
                    return '<label><input id="' . $data->journal_tran_id . '" class="checkbox" type="checkbox"></label>';
                })
                ->editColumn('debit', function ($data) {
                    return '<span data-curr="2" data-debit="' . ($data->debit) . '">$'. number_format($data->debit, 2) . '</span>';
                })
                ->editColumn('credit', function ($data) {
                    return '<span  data-curr="2" data-credit="' . ($data->credit) . '">$' . number_format($data->credit, 2) . '</span>';
                })
                ->editColumn('transaction_type', function ($data) {
                        return $data->transaction_type;
                })
                ->rawColumns(['checkbox', 'tran_id','action','debit','credit'])
                ->make(true);
        }
    }


    public function print_voucher(Request $request)
    {
        $journal_tran_id = $request->journal_tran_id;
        $journal_tran_id = explode(",", $journal_tran_id);
        $journal = DB::table('nso007_journal as jn')
            ->join('nso007_account_chart as chart', 'chart.id', 'jn.journal_acccode')
            ->selectRaw('chart.acc_name,chart.acc_namekh,jn.*')
            ->whereIn('jn.journal_tran_id', $journal_tran_id)
            ->orderBy('jn.journal_debit','desc' )
            ->where('jn.branch_id',myBranch()->id)
            ->get();
        return view('Accounting.journal.report-print-voucher', ['data' => $journal]);
    }

    public function create()
    {
        $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;
        return view('Accounting.journal.create', ['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)
    {
        return $this->update($request, null);
    }

    public function edit($id)
    {
        $journal = JournalModel::where('journal_tran_id',$id)->orderBy('id', 'asc')->get();
        return view('Accounting.journal.edit', compact('journal'));
    }

    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'date' => 'required',
            'voucher_ref' => 'required',
            'account_code.*' => 'required|exists:nso007_account_chart,id',
            '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 = $id??($max_tran_journal + 1);
        $date = date('Y-m-d', strtotime($request->date));
        if (!$max_id) {
            $max_id = 0;
        }
        $parent_id = ($max_id + 1);
        $account_code = $request->account_code;
        $this->journal_confirm_delete($id);
        foreach ($account_code as $key => $code) {
            $accType = AccountTypeModel::where('id', 'like', $code . '%')->first();
            $jType = $accType->acctype_group ?? $code;
            JournalModel::insert([
                'branch_id' => Auth::user()->branch_id,
                'journal_parentid' => $key>0?$parent_id:'',
                'journal_type' => $jType,
                'journal_acccode' => $code,
                'voucher_type' => $request->voucher_type,
                'voucher_ref' => $request->voucher_ref,
                'journal_des' => $request->note[$key],
                'journal_debit' => $request->debit[$key],
                'journal_credit' => $request->credit[$key],
                'journal_paydate' => $date,
                'journal_by' => Auth::user()->id,
                'journal_transactiondate' => $date,
                'journal_tran_id' => $journal_tran_id,
                'journal_reference_number' => "ENT".sprintf('%06d', $journal_tran_id),
                'journal_currency' => 2,
                'journal_status' => 0,
                'transaction_type' => 'Entry'
            ]);
        }

        return response()->json(['status' => 'ok','reload'=>1]);
    }


    public function destroy($id)
    {
        //
    }

    public function journal_confirm_delete($id)
    {
        if($id){
            JournalModel::where('journal_tran_id', $id)->delete();
        }
        return response()->json(['status' => 'ok']);
    }
}
