<?php

namespace App\Http\Controllers;

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

use App\Helpers\DBFunctions;

use DB;
use Auth;
use JavaScript;
use Mailer;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

class AgentController extends Controller {

    public function index(){
        $agents=Agent::with(['team'])->orderBy('id', 'DESC')->get();
        //dd($agents);
        //->whereNull('deleted_at')
        //$roles=Role::all();
        //dd($agents[0]->team);

        return view ('admin.agents.index', compact('agents'));
    }

    public function getNewAgent(){

        $enum   = new DBFunctions();
        $pst    = $enum->get_enum_values('agents','position');
        $agents = Agent::with(['team'])->orderBy('id', 'DESC')->get();
        $team   = Team::whereNull('deleted_at')->orderBy('name', 'ASC')->get();
        ////$roles=Role::all();
        //dd($pst);
        //echo 'ready';
        return view ('admin.agents.new-agent', compact('agents', 'pst', 'team'));
    }

    public function editAgent($id){

        $agent  = Agent::with(['team'])->where('id', $id)->first();
        $team   = Team::orderBy('name', 'ASC')->get();
        $enum   = new DBFunctions();
        $pst    = $enum->get_enum_values('agents','position');
        //$roles=Role::all();
        //dd($pst);
        return view ('admin.agents.edit-agent', compact('agent', 'pst', 'team'));
    }

    public function getAgentInfo($id) {
        $agent  = Agent::with(['team'])->where('id', $id)->first();
        $team   = Team::orderBy('name', 'ASC')->get();
        $enum   = new DBFunctions();
        $pst    = $enum->get_enum_values('agents','position');
        $stats  = DB::select('call sp_agent_dash_counts(?)',array($id));

        if ($agent->position == 'Sales Executive') {
            //$bal = DB::select('call sp_agent_cash_adv_balance(?)',array($id));
            $bal = DB::select('select * from vw_agent_ca_balances where '.' agent_id = '.$id);
            if ($bal == null || $bal == '') {
                $ca_bal     = 0;
                $ca_amount  = 0;
                $ca_pay  = 0;
            } else {
                $ca_amount  = $bal[0]->ca_amount;
                $ca_bal     = $bal[0]->ca_bal;
                $ca_pay     = $bal[0]->ttl_payment_adv;
            }

            return view ('admin.agents.info-details', compact('agent', 'pst', 'team', 'bal', 'stats', 'ca_bal', 'ca_amount', 'ca_pay'));

        } else if ($agent->position == 'Unit Manager') {
            //$bal = DB::select('call sp_manager_cash_adv_balance(?)',array($id));
            $bal = DB::select('select * from vw_manager_ca_balances where '.' manager_id = '.$id);

            if ($bal == null || $bal == '') {
                $ca_bal     = 0;
                $ca_amount  = 0;
                $ca_pay  = 0;
            } else {
                $ca_amount  = $bal[0]->ca_amount;
                $ca_bal     = $bal[0]->ca_bal;
                $ca_pay     = $bal[0]->ttl_payment_adv;
            }
            //dd($ca_bal);
            return view ('admin.agents.info-details', compact('agent', 'pst', 'team', 'bal', 'stats', 'ca_bal', 'ca_amount', 'ca_pay'));

        }

    }

    public function getAgentReleases($id) {
        /*$agent  = Agent::with(['team'])->where('id', $id)->first();
        $team   = Team::orderBy('name', 'ASC')->get();
        $enum   = new DBFunctions();
        $pst    = $enum->get_enum_values('agents','position');

        $sales      = DB::select('select * from vw_agent_sales where ' .' agent_id = '.$id);
        $releases   = DB::select('select * from vw_agent_releases where ' .' agent_id = '.$id);
        $cas        = DB::select('select * from vw_agent_cas where ' .' agent_id = '.$id);
        $pays       = DB::select('select * from vw_agent_ca_payments where ' .' agent_id = '.$id);
        $stats      = DB::select('call sp_agent_dash_counts(?)',array($id));
        $bal        = DB::select('call sp_agent_cash_adv_balance(?)',array($id));*/
        $from       = "2000-01-01 12:00:00";
        $to         = date('Y-m-d');
        $agent_id   = $id;

        $frm    = $from . ' 00:00:00';
        $tto    = $to . ' 23:59:59';

        $rpts   = DB::select('call sp_comm_voucher(?,?,?)',array($frm, $tto, $agent_id));
        //dd($rpts);

        return view ('admin.agents.releases', compact('rpts')); //, compact('agent', 'pst', 'team', 'sales', 'releases', 'cas', 'bal', 'pays', 'stats'));
    }

    public function getAgentUMReleases($id) {

        $from       = "2000-01-01 12:00:00";
        $to         = date('Y-m-d');
        $um_id   = $id;

        $frm    = $from . ' 00:00:00';
        $tto    = $to . ' 23:59:59';

        $rpts   = DB::select('call sp_comm_um_voucher(?,?,?)',array($frm, $tto, $um_id));
        //dd($rpts);

        return view ('admin.agents.um_releases', compact('rpts'));
    }


    public function generate_string_online($input, $strength = 5){
        $input_length = strlen($input);
        $random_string = '';

        for ($i = 0; $i < $strength; $i++) {
            $random_character = $input[mt_rand(0, $input_length - 1)];
            $random_string .= strtoupper($random_character);
        }

        /*$validate = DB::select("select * from payments where trxn_code='$random_string'");
        // dd($validate);
        if ($validate) {
            $permitted_chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
            $this->generate_string($permitted_chars, 12);
        } else {
            return $random_string;
        }*/

        return $random_string;
    }

    public function postNewAgent(Request $request)
    {
        /*dd($request->all());
        $this->validate($request, [
            'code' => 'required|unique',
            'name' => 'required|unique'
            //'full_name'=>'required',
            //'email'=>'required|email|unique:users',
            //'role'=>'required',
            //'password'=>'required|min:5'
        ]);*/

        try {

            DB::beginTransaction();

            $this->validate($request, [
                'code'          => 'required',
                'username'      => 'required',
                'fullname'      => 'required'
            ]);

            $permitted_chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
            $username = $request['username'].'_'.$this->generate_string_online('0123456789', 4);
            $password = $this->generate_string_online($permitted_chars, 10);

            $user = new User();
            $user->name     = $username; //$request['username'];
            $user->full_name= $request['fullname'];
            $user->email    = $request['email_ad'];
            $user->role_id  = 4;
            $user->password = bcrypt($password);
            $user->pwd      = $password;
            $user->save();

            $user->syncRoles($request['role']);

            $user_id = $user->id;

            if ($user) {

                $agent = new Agent();

                $agent->code            =   $request['code'];
                $agent->username        =   $username; //$request['username'];
                $agent->fullname        =   strtoupper($request['fullname']);
                $agent->address         =   strtoupper($request['address']);
                $agent->email_ad        =   $request['email_ad'];
                $agent->fb              =   $request['fb'];
                $agent->contact_no      =   $request['contact_no'];
                $agent->position        =   $request['position'];
                $agent->team_id         =   $request['team_id'];
                $agent->active          =   $request['active'];
                $agent->valid_id        =   $request->has('valid_id') ? 1 : 0;
                $agent->tin_id          =   $request->has('tin_id') ? 1 : 0;
                $agent->nbi_clearance   =   $request->has('nbi_clearance') ? 1 : 0;
                $agent->orientation     =   $request->has('orientation') ? 1 : 0;
                $agent->active          =   1;
                $agent->user_id         =   $user_id;
                $agent->save();

                //create Unit Manager
                $um = new UnitManager();
                $um->agent_id = $agent->id;
                $um->fullname = strtoupper($request['fullname']);
                $um->save();

                //Send email user credentials
                //$this->email_sender($request['email_ad'], $request['fullname'], $username, $password);

            }

            DB::commit();

            return redirect()->route('agents')->with('info', 'New Agent have been created.');

        } catch (\Exception $e) {

            DB::rollBack();
            return redirect()->route('agents')->with('info', $e->getMessage());
            //"{{ route('teams.edit',[$id]) }}"
        }

    }

    public function udpdateAgent(Request $request) {

        //dd($request['checked[1]']);
        $agent_id = $request['agent_id'];

        try {

            DB::beginTransaction();

            $this->validate($request, [
                'code'          => 'required',
                'fullname'      => 'required'
            ]);

            $agent = Agent::where('id', $agent_id)->first();

            $agent->code            =   $request['code'];
            $agent->fullname        =   strtoupper($request['fullname']);
            $agent->address         =   strtoupper($request['address']);
            $agent->email_ad        =   $request['email_ad'];
            $agent->fb              =   $request['fb'];
            $agent->contact_no      =   $request['contact_no'];
            $agent->position        =   $request['position'];
            $agent->team_id         =   $request['team_id'];
            $agent->active          =   $request['active'];
            $agent->valid_id        =   $request->has('valid_id') ? 1 : 0;
            $agent->tin_id          =   $request->has('tin_id') ? 1 : 0;
            $agent->nbi_clearance   =   $request->has('nbi_clearance') ? 1 : 0;
            $agent->orientation     =   $request->has('orientation') ? 1 : 0;
            $agent->update();

            DB::commit();

            return redirect()->route('agents')->with('info', 'The selected Agent have been updated.');

        } catch (\Exception $e) {

            DB::rollBack();
            return redirect()->route('agents')->with('info', $e->getMessage());
            //"{{ route('teams.edit',[$id]) }}"
        }

    }

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

        $team->delete();

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

    public function agent_sales() {

    }

    public function chkFullname(Request $request) {

        $fullname = $request->fullname;
        $agent  = Agent::where('fullname', '=', $fullname)->get();
        //return response()->json(["data"=>$agent]);
        if (isset($fullname)) {

            $agent  = Agent::where('fullname', '=', $fullname)->first();

            if ($agent) {
                return response()->json(["chk"=>true]);
            } else {
                return response()->json(["chk"=>false]);
            }
            //return response()->json(["data"=>$agent]);
        } else {
            return response('No data');
        }
    }

    public function email_test($email) {
        //$mail = new PHPMailer();
        //$mail = new PHPMailer(true);

        $mail = new PHPMailer(true);

        $mail->IsSMTP(); // enable SMTP
        $mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
        $mail->SMTPAuth = true; // authentication enabled
        $mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for Gmail
        //$mail->Host = "smtp.gmail.com";
        $mail->Port = 587; // or 587
        $mail->IsHTML(true);
        $mail->Host = env('MAILER_HOST');
        // $mailer->SMTPAuth = true;
        $mail->Username =  env('MAILER_USR');
        $mail->Password =  env('MAILER_PWD');
        $mail->setFrom(env('MAILER_USR'), 'DPS APP');
        $mail->Subject = "Test";
        $mail->Body = "hello";
        $mail->AddAddress($email);

        if(!$mail->Send()) {
            echo "Mailer Error: " . $mail->ErrorInfo;
        } else {
            echo "Message has been sent";
        }
    }

    public function email_sender($email, $fullname, $uname, $pwd) {

        $data = file_get_contents('../resources/views/email_template/email-template.html');
        $content = str_replace('%fullname%',$fullname,$data);
        $content = str_replace('%username%', $uname, $content);
        $content = str_replace('%password%', $pwd, $content);

        set_time_limit(0);

        $mailer = new PHPMailer(true);
        $mailer->isSMTP();
         $mailer->SMTPOptions = array(
             'ssl' => array(
                 'verify_peer' => false,
                 'verify_peer_name' => false,
                 'allow_self_signed' => true
             )
         );
        $mailer->Host = env('MAILER_HOST');
        // $mailer->SMTPAuth = true;
        $mailer->Username =  env('MAILER_USR');
        $mailer->Password =  env('MAILER_PWD');
        // $mail->SMTPAutoTLS = true;
        $mailer->SMTPDebug = 0; // debugging: 1 = errors and messages, 2 = messages only
        $mailer->SMTPAuth = true;
        $mailer->SMTPSecure = 'ssl';
        $mailer->Port = 465;
        //$mail->SMTPDebug = 2;
        $mailer->setFrom(env('MAILER_USR'), 'DPS User Account');
        $mailer->addAddress($email);
        $mailer->addCC(env('EMAIL_TO_1'));
        $mailer->addCC('caloyregs@gmail.com');
        $mailer->isHTML(true);
        $mailer->Subject = 'User Login Account';
        $mailer->Body    = $content;

        if(!$mailer->send()) {
            dd($mailer->ErrorInfo);
        } /*else {
            return redirect()->route('leaves.index')->with('message', 'Email sent successfully!');
        }*/
    }

}