<?php

namespace App\Http\Controllers\Administrator;
use Illuminate\Support\Facades\Crypt;
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 App\LibilityModel;
use DataTables;
class LibilityController extends Controller
{
    
    function __construct()
    {
        
    }

    public function index()
    {
        return view('administrator.accounting.libility.index');
    }
    public function datatable_get_libility(Request $request){
        $search = $request->input('search.value');
        $count_total = DB::table('nso007_liability')->count();

        $count_filter = DB::table('nso007_liability')
            ->where(function($query) use ($search){
                $query->orWhere('liability_item' , 'LIKE' , '%'.$search.'%');
                $query->orWhere('liability_from' , 'LIKE' , '%'.$search.'%');
                $query->orWhere('liability_invoice' , 'LIKE' , '%'.$search.'%');
                $query->orWhere('liability_des' , 'LIKE' , '%'.$search.'%');
            })
            ->count();

        $libility = DB::table('nso007_liability')
            ->orderBy('id','asc')
            ->take(20);


        // $count_total = LibilityModel::count();
        // $count_filter = LibilityModel::where('liability_date','LIKE','%'.$search.'%')
        //                               ->orWhere('liability_item','LIKE','%'.$search.'%')
        //                               ->orWhere('liability_invoice','LIKE','%'.$search.'%')
        //                               ->orWhere('liability_from','LIKE','%'.$search.'%')
        //                               ->orWhere('liability_des','LIKE','%'.$search.'%')
        //                               ->orWhere('liability_des','LIKE','%'.$search.'%')
        //                               ->count();

        // $libility = LibilityModel::take(20);
        return  Datatables::of($libility)
        ->addIndexColumn()
        ->with([
            "recordsTotal" => $count_total,
            "recordsFiltered" => $count_filter,
        ])
        ->setRowId('id')
        ->addColumn('liability_amount',function($libility){
                return '$'.number_format($libility->liability_amount,2);
        })
        ->editColumn('action', function ($libility) {
            return '<a href="'.Route("libility.edit",Crypt::encrypt($libility->id)).'" class="button_success fa fa-edit"></a>';
        })
        ->addColumn('liability_date',function($libility){
            return date('Y-m-d',strtotime($libility->liability_date));
        })
        ->addIndexColumn()
        ->make(true);
        
    }

    public function create()
    {
         $account_chart = AccountChartModel::select(
            DB::raw('CONCAT(id," ",acc_name) AS account_mixed'),'id')
          ->where('id','like','2%')
            ->pluck('account_mixed','id')
           
            ->prepend('Please Select', '');
        return view('administrator.accounting.libility.create',compact('account_chart'));
    }
    public function store(Request $request){

        $libility = New LibilityModel;
        $this->validate($request, [
            'liability_item'    => 'required',
            'liability_from'     => 'required',
            'liability_amount'   => 'required|numeric',
            'liability_date'  => 'required',
        ]);
        $libility->liability_item = $request->liability_item;
        $libility->liability_from = $request->liability_from;
        $libility->liability_amount = $request->liability_amount;
        $libility->liability_date = date('Y-m-d',strtotime($request->liability_date));
        $libility->liability_invoice = $request->liability_invoice;
        $libility->liability_user = Auth::user()->id;
        $libility->liability_des = $request->liability_des;
        $libility->save();

        $last_id = $libility->id;
        $data = array(
                    'journal_parentid'=>0,
                    'journal_acccode'=>10000,
                    'journal_type'=>2,
                    'journal_debit'=> $request->liability_amount,
                    'journal_invoice'=>$request->liability_invoice,
                    'journal_transactiondate'=>date('Y-m-d H:i:s A'),
                    'journal_paydate'=>date('Y-m-d',strtotime($request->liability_date)),
                    'journal_des'=>$request->liability_des,
                    'journal_by'=>Auth::user()->id,
                    'journal_referenceid' => $last_id,
        );
        JournalModel::insert($data);
        $max_id = JournalModel::max('id');


        $data1 =array(
                    'journal_parentid'=> $max_id,
                    'journal_acccode'=> $request->liability_item,
                    'journal_type'=>2,
                    'journal_credit'=>$request->liability_amount,
                    'journal_invoice'=>$request->liability_invoice,
                    'journal_transactiondate'=>date('Y-m-d H:i:s A'),
                    'journal_paydate'=>date('Y-m-d',strtotime($request->liability_date)),
                    'journal_des'=>$request->liability_des,
                    'journal_by'=>Auth::user()->id,
                    'journal_referenceid' => $last_id,
        );
        JournalModel::insert($data1);
        \LogActivity::addToLog('Libility created successfully!');
        return redirect()->route('libility.index')
                        ->with('success','Libility created successfully!');

       
    }
    public function edit($id)
    {
        $decrypt_id = Crypt::decrypt($id);
        $libility = LibilityModel::find($decrypt_id);
        $account_chart = AccountChartModel::select(
            DB::raw('CONCAT(id," ",acc_name) AS account_mixed'),'id')
          ->where('id','like','2%')
            ->pluck('account_mixed','id')
           
            ->prepend('Please Select', '');
        return view('administrator.accounting.libility.edit',compact('account_chart','libility'));
    }

    public function update(Request $request, $id)
    {
        $libility = LibilityModel::find($id);
         $this->validate($request, [
            'liability_item'    => 'required',
            'liability_from'     => 'required',
            'liability_amount'   => 'required|numeric',
            'liability_date'  => 'required',
        ]);

        $libility->liability_item = $request->liability_item;
        $libility->liability_from = $request->liability_from;
        $libility->liability_amount = $request->liability_amount;
        $libility->liability_date = date('Y-m-d',strtotime($request->liability_date));
        $libility->liability_invoice = $request->liability_invoice;
        $libility->liability_user = Auth::user()->id;
        $libility->liability_des = $request->liability_des;
        $libility->update();
        \LogActivity::addToLog('Libility updated successfully!');
        return redirect()->route('libility.index')
                        ->with('success','Libility updated successfully');
    }

    public function report()
    {
        $account_charts = AccountChartModel::select(
            DB::raw('CONCAT(id," ",acc_name) AS account_mixed'),'id')
          ->where('id','like','2%')
            ->pluck('account_mixed','id')
           
            ->prepend('Please Select', '');
        return view('administrator.accounting.libility.report',compact('account_charts'));
    }

    public function datatable_libility_report(Request $request)
    {
        $search = $request->input('search.value');
        $count_total = DB::table('nso007_liability')->count();
        $count_filter = DB::table('nso007_liability')
                        ->join('nso007_account_chart','nso007_account_chart.id','nso007_liability.liability_item')
                        ->where('nso007_liability.liability_date','LIKE','%'.$search.'%')
                        ->orWhere('nso007_liability.liability_amount','LIKE','%'.$search.'%')
                        ->orWhere('nso007_account_chart.acc_name','LIKE','%'.$search.'%')
                        ->orWhere('nso007_liability.liability_des','LIKE','%'.$search.'%')
                        ->orWhere('nso007_liability.liability_invoice','LIKE','%'.$search.'%')
                        ->orWhere('nso007_liability.liability_from','LIKE','%'.$search.'%')
                        ->count();

        $libility = DB::table('nso007_liability')
                    ->join('nso007_account_chart','nso007_account_chart.id','nso007_liability.liability_item')
                    ->select(
                        'nso007_liability.id',
                        'nso007_liability.liability_date',
                        'nso007_liability.liability_amount',
                        DB::raw("CONCAT(nso007_account_chart.id,' ', nso007_account_chart.acc_name) AS liability_item"),
                        DB::raw("IFNULL(nso007_liability.liability_des,'N/A') AS liability_des"),
                        DB::raw("IFNULL(nso007_liability.liability_invoice,'N/A') AS liability_invoice"),
                        DB::raw("IFNULL(nso007_liability.liability_from,'N/A') AS liability_from")
                    )
                    ->take(20);

        if($request->isMethod('GET'))
        {
            return  Datatables::of($libility)
            ->addIndexColumn()
            ->with([
                "recordsTotal" => $count_total,
                "recordsFiltered" => $count_filter,
            ])
            ->addColumn('liability_amount',function($libility){
                    return '$'.number_format($libility->liability_amount,2);
            })
            ->addColumn('liability_date',function($libility){
                return date('Y-m-d',strtotime($libility->liability_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));

            $libility = DB::table('nso007_liability')
                    ->join('nso007_account_chart','nso007_account_chart.id','nso007_liability.liability_item')
                    ->select(
                        'nso007_liability.id',
                        'nso007_liability.liability_date',
                        'nso007_liability.liability_amount',
                        DB::raw("CONCAT(nso007_account_chart.id,' ', nso007_account_chart.acc_name) AS liability_item"),
                        DB::raw("IFNULL(nso007_liability.liability_des,'N/A') AS liability_des"),
                        DB::raw("IFNULL(nso007_liability.liability_invoice,'N/A') AS liability_invoice"),
                        DB::raw("IFNULL(nso007_liability.liability_from,'N/A') AS liability_from")
                    )
                    ->where('nso007_liability.liability_item',isset($request->journal_acccode)?$request->journal_acccode:NULL)
                    ->when(request('start_date',''), function($query) use ($start_date, $end_date){
                        $query->whereBetween('nso007_liability.liability_date',[$start_date,$end_date]);
                    })
                    ->get();
            echo json_encode($libility);
        }
        
    }

    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));
        
        $mdoel_searching = new SearchModel();
        $journal_date =  (empty($start_date))? '':' nso007_liability.liability_date BETWEEN "'.$start_date.'" AND "'.$end_date.'" ';
        $journal_acccode =  (empty($request->journal_acccode))? '':' nso007_liability.liability_item = "'.$request->journal_acccode.'" ';

        $data_search = array(
            'journal_date' =>$journal_date,
            'journal_acccode' =>$journal_acccode,
        );
        $search= $mdoel_searching->search($data_search);
        

        $libility = DB::select("SELECT 
                            nso007_liability.id,
                            CONCAT(nso007_account_chart.id,' ', nso007_account_chart.acc_name) AS liability_item,   
                            IFNULL(nso007_liability.liability_des,'N/A') AS liability_des,
                            IFNULL(nso007_liability.liability_invoice,'N/A') AS liability_invoice,
                            IFNULL(nso007_liability.liability_from,'N/A') AS liability_from,
                            nso007_liability.liability_date,
                            nso007_liability.liability_amount
                            FROM nso007_liability
                            INNER JOIN nso007_account_chart ON nso007_account_chart.id = nso007_liability.liability_item
                            $search");

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