<?php

namespace App\Http\Controllers;

use App\Models\CAPayment;
use App\Models\CashAdvancePayment;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;
use App\Models\Developer;
use App\Models\Team;
use App\Models\UnitManager;
use App\Models\CashAdvance;
use App\Models\Agent;
use App\User;

use App\Helpers\DBFunctions;

use DB;
use Auth;
use JavaScript;

class CashAdvanceController extends Controller
{

    public function index() {

        $role_      = Auth::user()->role_id;
        $user_id    = Auth::user()->id;

        if ($role_ == 4) {
            $user_agent = DB::select('select * from vw_user_agent'. ' where user_id = '. $user_id);
            $uagent     = $user_agent[0]->agent_id;
            //$cas = CashAdvance::with(['agent'])->whereNull('deleted_at')->where('agent_id', '=', $uagent)->orderBy('id', 'DESC')->get();
            $cas = DB::select('select * from vw_agent_cas where agent_id='.$uagent);
            //dd($cas);
            return view('admin.cash_advances.index', compact('cas'));
        } else {
            //$cas = CashAdvance::with(['agent'])->whereNull('deleted_at')->orderBy('id', 'DESC')->get();
            $cas = DB::select('select * from vw_agent_cas');
            //dd($cas);
            return view('admin.cash_advances.index', compact('cas'));
        }
    }

    public function payments() {

        $role_      = Auth::user()->role_id;
        $user_id    = Auth::user()->id;

        if ($role_ == 4) {
            $user_agent = DB::select('select * from vw_ca_payments'. ' where user_id = '. $user_id);
            $uagent     = $user_agent[0]->agent_id;
            //$cas = CashAdvance::with(['agent'])->whereNull('deleted_at')->where('agent_id', '=', $uagent)->orderBy('id', 'DESC')->get();
            $cas = DB::select('select * from vw_agent_cas where agent_id='.$uagent);
            //dd($cas);
            return view('admin.cash_advances.index', compact('cas'));
        } else {
            //$cas = CashAdvance::with(['agent'])->whereNull('deleted_at')->orderBy('id', 'DESC')->get();
            $cas = DB::select('select * from vw_ca_payments');
            //dd($cas);
            return view('admin.cash_advances.payments', compact('cas'));
        }
    }

    /*public function getNewAdvancePayment(){

        $enum   = new DBFunctions();
        $pst    = $enum->get_enum_values('agents','position');
        $agents = Agent::with(['team'])->orderBy('id', 'DESC')->get();
        //dd($pst);
        //echo 'ready';

        return view ('admin.cash_advances.new', compact('agents', 'pst'));
    }*/

    public function getNewAdvance(){

        $enum   = new DBFunctions();
        $pst    = $enum->get_enum_values('agents','position');
        $agents = Agent::with(['team'])->orderBy('id', 'DESC')->get();
        //dd($pst);
        //echo 'ready';

        return view ('admin.cash_advances.new', compact('agents', 'pst'));
    }

    public function postNewAdvance(Request $request) {
        try {

            DB::beginTransaction();

            $validate = [
                'agent_id'  => 'required',
                'amount'    => 'required'
            ];

            $validator = \Validator::make($request->all(), $validate);

            // dd($validator);
            if ( $validator->fails() ) {
                //dd( $validator );
                return back()
                    ->withErrors($validator)
                    ->withInput();
            }

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

            $r_date             = $request['ca_date'];
            $ca_date            = date("Y-m-d", strtotime($r_date));

            $rdata = [
                'agent_id'      => $request['agent_id'],
                'ca_date'       => $ca_date,
                'amount'        => $request['amount'],
                'remarks'       => $request['remarks'],
                'status'        => 'On-process',
                'user_id'       => $userid
            ];

            $ca = new CashAdvance();
            $ca->fill($rdata);
            $ca->save();

            DB::commit();

            return redirect()->route('advances')->with('info', 'The new Cash Advance was created.');

        } catch (\Exception $e) {
            DB::rollBack();
            //return redirect()->route('advances.new')->with('info', 'Oppsss something went wrong..');
            return redirect()->route('advances.new')->with('info', $e->getMessage());
        }

    }

    public function getNewPayment(){

        $enum   = new DBFunctions();
        $pst    = $enum->get_enum_values('agents','position');
        //$agents = Agent::with(['team'])->orderBy('id', 'DESC')->get();
        $agents = $user_agent = DB::select('select * from vw_ca_agents_list');
        //dd($agents);
        //echo 'ready';

        return view ('admin.cash_advances.payment', compact('agents', 'pst'));
    }

    public function postPayment(Request $request) {
        //dd($request->all());
        try {

            DB::beginTransaction();

            $validate = [
                'agents'  => 'required',
                'amount'  => 'required'
            ];

            $validator = \Validator::make($request->all(), $validate);

            // dd($validator);
            if ( $validator->fails() ) {
                //dd( $validator );
                return back()
                    ->withErrors($validator)
                    ->withInput();
            }

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

            $r_date             = $request['pay_date'];
            $pay_date           = date("Y-m-d", strtotime($r_date));
            $amt                = $this->tofloat($request['amount']);

            $rdata = [
                'agent_id'      => $request['agents'],
                'manager_id'    => $request['manager_id'],
                'payment_date'  => $pay_date,
                'amount'        => $amt, //$request['amount']
                'remarks'       => $request['remarks'],
                'user_id'       => $userid
            ];

            $ca = new CAPayment();
            $ca->fill($rdata);
            $ca->save();

            DB::commit();

            return redirect()->route('advances.payments')->with('info', 'New Payment was created.');

        } catch (\Exception $e) {
            DB::rollBack();
            dd($e->getMessage());
            //return redirect()->route('advances.new')->with('info', 'Oppsss something went wrong..');
            return redirect()->route('advances.payment')->with('info', $e->getMessage());
        }

    }

    function tofloat($numberString) {
        return floatval(preg_replace("/[^0-9.]/", '', $numberString));
    }

    public function getEditAdvance($id){

        $enum   = new DBFunctions();
        $status = $enum->get_enum_values('cash_advances','status');
        $agents = Agent::with(['team'])->orderBy('id', 'DESC')->get();
        $adv   = CashAdvance::with(['agent', 'user'])->where('id', $id)->first();
        //dd($agents);
        //echo 'ready';

        return view ('admin.cash_advances.edit', compact('adv','agents', 'status'));
    }

    public function getEditPayment($id){

        $enum   = new DBFunctions();
        $status = $enum->get_enum_values('cash_advances','status');
        $agents = $user_agent = DB::select('select * from vw_ca_agents_list');
        $adv   = CashAdvancePayment::with(['agent'])->where('id', $id)->first();
        //dd($adv);
        //echo 'ready';

        return view ('admin.cash_advances.payment-edit', compact('adv','agents', 'status'));
    }

    public function postUpdatePayment(Request $request) {

        //dd($request->all());
        $id = $request['id_'];

        try {

            DB::beginTransaction();

            $validate = [
                'agents'  => 'required',
                'amount'    => 'required'
            ];

            $validator = \Validator::make($request->all(), $validate);

            // dd($validator);
            if ( $validator->fails() ) {
                //dd( $validator );
                return back()
                    ->withErrors($validator)
                    ->withInput();
            }

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

            $r_date             = $request['pay_date'];
            $pay_date           = date("Y-m-d", strtotime($r_date));
            $amt                = $this->tofloat($request['amount']);

            $rdata = [
                //'agent_id'      => $request['agents'],
                //'manager_id'    => $request['manager_id'],
                'payment_date'  => $pay_date,
                'amount'        => $amt,
                'remarks'       => $request['remarks'],
                'user_id'       => $userid
            ];

            $ca = CashAdvancePayment::where('id',$id)->first();
            $ca->fill($rdata);
            $ca->update();

            DB::commit();

            return redirect()->route('advances.payments')->with('info', 'Payments was updated successfully.');

        } catch (\Exception $e) {
            DB::rollBack();
            //return redirect()->route('advances.new')->with('info', 'Oppsss something went wrong..');
            return redirect()->route('advances.payment.new')->with('info', $e->getMessage());
        }

    }

    public function postUpdateAdvance(Request $request) {

        $id = $request['id_'];

        try {

            DB::beginTransaction();

            $validate = [
                'agent_id'  => 'required',
                'amount'    => 'required'
            ];

            $validator = \Validator::make($request->all(), $validate);

            // dd($validator);
            if ( $validator->fails() ) {
                //dd( $validator );
                return back()
                    ->withErrors($validator)
                    ->withInput();
            }

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

            $r_date             = $request['ca_date'];
            $ca_date            = date("Y-m-d", strtotime($r_date));

            $rdata = [
                'agent_id'      => $request['agent_id'],
                'ca_date'       => $ca_date,
                'amount'        => $request['amount'],
                'remarks'       => $request['remarks'],
                'status'        => $request['status'],
                'user_id'       => $userid
            ];

            $ca = CashAdvance::where('id',$id)->first();
            $ca->fill($rdata);
            $ca->update();

            DB::commit();

            return redirect()->route('advances')->with('info', 'The new Cash Advance have been created.');

        } catch (\Exception $e) {
            DB::rollBack();
            //return redirect()->route('advances.new')->with('info', 'Oppsss something went wrong..');
            return redirect()->route('advances.new')->with('info', $e->getMessage());
        }

    }

    public function bal_agents() {
        return view ('admin.cash_advances.balance.agents', compact('adv','agents', 'status'));
    }

    public function bal_managers() {

        $cas = DB::select('select * from vw_bal_ca_managers');
        //dd($cas);

        return view ('admin.cash_advances.balance-managers', compact('cas'));
    }

    public function Delete(Request $request){
        $id     = $request['id'];
        $team   = CashAdvance::where('id', $id)->first();

        $team->delete();

        return redirect()->back()->with('info', "The selected record have been deleted.");
    }

    public function payment_delete(Request $request){

        $id     = $request['id'];
        $pay    = CashAdvancePayment::where('id', $id)->first();

        $pay->delete();

        return redirect()->back()->with('info', "The selected record have been deleted.");
    }

    public function getAgentData(Request $request)
    {
        $id     = $request->agent_id;
        //$um_id  = $request->manager_id;

        if (isset($id)) {

            $agents     = DB::select('select * from vw_ca_agents_list where agent_id='.$id);
            $um_id      = $agents[0]->manager_id;

            $balance    = 0;
            if ($um_id != null || $um_id != '') {
                $bal2       = DB::select('select * from vw_manager_ca_balances_v2 where manager_id = '.$um_id);

                if ($bal2 == null || $bal2 == '') {
                    $balance    = 0;
                } else {
                    $balance    = $bal2[0]->ca_bal;
                    /*if ($balance <= 0) {
                        $balance = 0;
                    } else {
                        $balance    = $bal2[0]->ca_bal;
                    }*/
                }
             } else {
                $bal        = DB::select('select * from vw_agent_ca_balances_v2 where agent_id = '.$id);
                if ($bal == null || $bal == '') {
                    $balance     = 0;
                } else {
                    $balance     = $bal[0]->ca_bal;
                    /*if ($balance <= 0) {
                        $balance = 0;
                    } else {
                        $balance    = $bal[0]->ca_bal;
                    }*/
                }
            }
            if ($balance <=0 ) {
                $balance = 0;
            }

            return response()->json(["agents"=>$agents, "balance"=>$balance]);

        } else {
            return response('No data');
        }

    }

}