<?php
namespace App\Http\Controllers\Form;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

use App\Mail\CustomerBInvoice;
use App\Jobs\SendCustomerInvoiceB;

use Carbon\Carbon;
use Validator;
use File;

use App\Model\Coverage;
use App\Model\Product;

use App\Model\Form;
use App\Model\Subscriber;
use App\Model\PackageDetail;
use App\Model\FormStatus;

use App\Staff;
use App\Model\StaffDetail;

class BusinessController extends Controller
{
    public function successSubmit(){
        return view('sales.form.after_submit_form');
    }

    public function successVerified(){
        return view('sales.form.success_verify');
    }

    public function sendInvoice($subscriber_id) {

        $subscriber  = Subscriber::with('Form')->where('subscriber_id',$subscriber_id)->first();
        $form = Form::with('Subscriber','PackageDetail')->where('_id',$subscriber->_id)->first();
        $product = Product::where('speed',$form->PackageDetail->name)->where('formT',$form->type_application)->first();
        SendCustomerInvoiceB::dispatch($form, $product, $form->Subscriber->email);

        return $form->_id;
    }

    function random_code($limit) {
        return substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, $limit);
    }


    public function viewFormAddress($package) {

        $dealer_id = '';
        return view('sales.form.business_address', compact('package','dealer_id'));
    }

    public function viewFormApplication(Request $request) {   
        $data = array();

        array_push($data, array(
            'unit_no' => $request->unit_no,
            'caddress' => $request->caddress,
            'ccity' => $request->ccity,
            'cstate' => $request->cstate,
            'postcode' => $request->postcode,
            'package' => $request->package
        ));
        return view('sales.form.business_application_information', compact('data'));
    }

    public function viewFormPackage(Request $request)
    {   
        $data = array();
        array_push($data, array(
            'unit_no' => $request->unit_no,
            'caddress' => $request->caddress,
            'ccity' => $request->ccity,
            'cstate' => $request->cstate,
            'postcode' => $request->postcode,
            'package' => $request->package,
            'application' => $request->application,
            'company_name' => $request->company_name,
            'company_register' => $request->company_register,
            'company_number' => $request->company_number,
            'company_fax' => $request->company_fax,
            'full_name' => $request->full_name,
            'nric_passport' => $request->nric_passport,
            'designation' => $request->designation,
            'contact_primary' => $request->contact_primary,
            'contact_secondary' => $request->contact_secondary,
            'email' => $request->email,
        ));

        $pg = $request->package;

        return view('sales.form.business_package', compact('data','pg'));
    }

    public function viewFormPreview(Request $request){

        $data = array();

        $product = Product::where('formT','B')->where('package_name',$request->package)->first();
        $otc = 0.0;

        $total_monthly = 0; 
        $gst ='';
        $promo_st = '';

        $voice = "No";
        if($request->voice == "Yes"){ 
            $voice =  $request->voice;
            $voice_price = 20;
        }else {
            $voice = "No";
            $voice_price = 0;
        }

        $ip_fee = 0; $ip_tax = 0;
        if ($request->ip == "1 Fixed IP RM200/1P/Month") {
            $ip_fee = 200 ;
            $ip_tax = number_format((floatval($ip_fee) * 1.06),2); 
        }elseif ($request->ip == "5 Fixed IP RM400/1P/Month") {
            $ip_fee = 400;
            $ip_tax = number_format((floatval($ip_fee) * 1.06),2); 
        }

        if ($request->package != "1Gbps" && $request->subscription == '24'){
            $promo_price = number_format(floatval($product->retail_price) - 10);
            $promo_st = number_format(floatval($promo_price) * 1.06,2);
            $total_monthly = number_format($promo_st + ($voice_price * 1.06) + $ip_tax, 2);
        }
        else if ($request->package == "1Gbps"){
            if ($request->ip == "1 Fixed IP RM200/1P/Month") {
                $gst = number_format(floatval($product->retail_price) * 1.06,2);
                $total_monthly = 3920.94;
            }elseif ($request->ip == "5 Fixed IP RM400/1P/Month") {
                $gst = number_format(floatval($product->retail_price) * 1.06,2);
                $total_monthly = 4132.94;
            }else{
                $gst = 3708.94;
                $total_monthly = 3708.94;
            }
        }else{
            $gst = number_format(floatval($product->retail_price) * 1.06,2);
            $total_monthly = number_format($gst + ($voice_price * 1.06) + $ip_tax, 2);
        }
        

        if($request->subscription == '12' && $voice == 'No'){
            $otc = 300;
            $deposit = $product->deposit;
        }else if( $request->subscription == '12' && $voice == 'Yes'){
            $otc = 300 + 100;
            $deposit = $product->deposit;
        }else {
            $otc = 0.0;
            $deposit = $product->deposit;
        }

        $otc_st = number_format(floatval($otc) * 1.06,2);
        $upfront_total = number_format(floatval($otc_st) + $deposit,2);

        $total = number_format((floatval($product->retail_price) * 1.06) + ($otc * 1.06) + $deposit + $ip_tax, 2);

        array_push($data, array(
            'unit_no' => $request->unit_no,
            'caddress' => $request->caddress,
            'ccity' => $request->ccity,
            'cstate' => $request->cstate,
            'postcode' => $request->postcode,
            'package' => $request->package,
            'application' => $request->application,
            'company_name' => $request->company_name,
            'company_register' => $request->company_register,
            'company_number' => $request->company_number,
            'company_fax' => $request->company_fax,
            'full_name' => $request->full_name,
            'nric_passport' => $request->nric_passport,
            'designation' => $request->designation,
            'contact_primary' => $request->contact_primary,
            'contact_secondary' => $request->contact_secondary,
            'email' => $request->email,
            'subscription' => $request->subscription,
            'billing' => $request->billing,
            'voice' => $voice,
            'ip' => $request->ip,
            'ip_fee' => $ip_fee,
            'ip_tax' => $ip_tax,
            'thedate' => $request->thedate,
        ));

        return view('sales.form.business_preview', compact('data','coverage','product','deposit','otc', 'otc_st','gst','promo_price','promo_st','total_monthly', 'upfront_total'));
    }

    public function storeFormData(Request $request){

        $su_id = ''; $pathIconF = ''; $pathIconB = ''; $pathForm9 = '';

        do {
            $su_id = strtoupper('CBB-'.$this->random_code(6).'B');
        } while (Subscriber::where("subscriber_id", "=", $su_id)->first() instanceof Subscriber);

        
        $destinationPath = 'document/'.$su_id;
        // create folder/dir if not exist
	info(public_path());
        if(!File::exists(public_path().'/'.$destinationPath)){
            File::makeDirectory(public_path().'/'.$destinationPath,0777,true);
        }

        if($request->hasfile('front_ic')){ 

            $icon = $request->file('front_ic');
            $icon->move($destinationPath,'frontic.'.$icon->getClientOriginalExtension());
            $pathIconF = '/'.$destinationPath.'/frontic.'.$icon->getClientOriginalExtension();
        }

        if($request->hasfile('back_ic')){ 

            $icon = $request->file('back_ic');
            $icon->move($destinationPath,'backic.'.$icon->getClientOriginalExtension());
            $pathIconB = '/'.$destinationPath.'/backic.'.$icon->getClientOriginalExtension();
        }

        if($request->hasfile('form9')){ 

            $icon = $request->file('form9');
            $icon->move($destinationPath,'formD.'.$icon->getClientOriginalExtension());
            $pathForm9 = '/'.$destinationPath.'/formD.'.$icon->getClientOriginalExtension();
        }

        if($pathForm9 != '' && $pathIconB != '' && $pathIconF != ''){

            $sl = Form::create([
                'type_service' => $request->application,
                'type_application' => 'B',
                'status_payment' => 'paid',
                'status_email' => 'unverified',
                'remark_form' => ''
            ]);

            $product = Product::where('formT','B')->where('package_name',$request->package)->first();

            $sdl = new Subscriber();
            $sdl->subscriber_id = $su_id;
            $sdl->name = $request->full_name;
            $sdl->ic = $request->nric_passport;
            $sdl->company_name = $request->company_name;
            $sdl->company_reg = $request->company_register;
            $sdl->company_num = $request->company_number;
            $sdl->company_fax = $request->company_fax;
            $sdl->designation = $request->designation;
            $sdl->email = $request->email;
            $sdl->phone1 = $request->contact_primary;
            $sdl->phone2 = $request->contact_secondary;
            $sdl->unit_no = $request->unit_no;
            $sdl->street = $request->caddress;
            $sdl->postcode = $request->postcode;
            $sdl->city = $request->ccity;
            $sdl->state = $request->cstate;
            $sdl->front_ic = $pathIconF;
            $sdl->back_ic = $pathIconB;
            $sdl->form9_44 = $pathForm9;
                                            
            $packageD = new PackageDetail();
            $packageD->contract = $request->subscription;
            $packageD->name = $product->speed;
            if ($request->gst != null){
                $packageD->montly_fee = $request->gst;
            }else {
                $packageD->montly_fee = $request->promo_st;
            }
            $packageD->voice_fee = $request->voice;
            $packageD->ip = $request->ip;
            $packageD->deposit = $request->deposit;
            $packageD->upfront_payment = $request->otc;
            $packageD->ip_tax = $request->ip_tax;
            $packageD->rfs = $request->rfs;

            $sl->subscriber()->save($sdl);
            $sl->packagedetail()->save($packageD);

            $f_id = $this->sendInvoice($su_id);
            $stat = new FormStatus();
            $stat->form_id = $f_id;
            $stat->status_id = 1;
            $stat->date = new \MongoDB\BSON\UTCDateTime(time()*1000);
            $stat->status = 'Submitted';
            $stat->desc = 'The form already been submit';
            $sl->formstatus()->save($stat);

            return redirect('http://db.citybroadband.my/business/application-form/success-submit');
        }
    }

    /***
    ** Dealer
    ***/

    public function viewFormAddressD($package,$dealer_id) {
        return view('sales.form.dealer.business_address', compact('package','dealer_id'));
    }

    public function viewFormApplicationD(Request $request) {   
        $data = array();

        array_push($data, array(
            'unit_no' => $request->unit_no,
            'caddress' => $request->caddress,
            'ccity' => $request->ccity,
            'cstate' => $request->cstate,
            'postcode' => $request->postcode,
            'package' => $request->package,
            'dealer_id' => $request->dealer_id,
        ));
        return view('sales.form.dealer.business_application_information', compact('data'));
    }

    public function viewFormPackageD(Request $request)
    {   
        $data = array();
        array_push($data, array(
            'unit_no' => $request->unit_no,
            'caddress' => $request->caddress,
            'ccity' => $request->ccity,
            'cstate' => $request->cstate,
            'postcode' => $request->postcode,
            'package' => $request->package,
            'application' => $request->application,
            'company_name' => $request->company_name,
            'company_register' => $request->company_register,
            'company_number' => $request->company_number,
            'company_fax' => $request->company_fax,
            'full_name' => $request->full_name,
            'nric_passport' => $request->nric_passport,
            'ip' => $request->ip,
            'designation' => $request->designation,
            'contact_primary' => $request->contact_primary,
            'contact_secondary' => $request->contact_secondary,
            'email' => $request->email,
            'dealer_id' => $request->dealer_id,
        ));

        $pg = $request->package;

        return view('sales.form.dealer.business_package', compact('data','pg'));
    }

    public function viewFormPreviewD(Request $request){
        $data = array();

        $product = Product::where('formT','B')->where('package_name',$request->package)->first();
        $otc = 0.0;

        $total_monthly = 0; 
        $gst ='';
        $promo_st = '';

        $voice = "No";
        if($request->voice == "Yes"){ 
            $voice =  $request->voice;
            $voice_price = 20;
        }else {
            $voice = "No";
            $voice_price = 0;
        }
        
        $ip_fee = 0; $ip_tax = 0;
        if ($request->ip == "1 Fixed IP RM200/1P/Month") {
            $ip_fee = 200 ;
            $ip_tax = number_format((floatval($ip_fee) * 1.06),2); 
        }elseif ($request->ip == "5 Fixed IP RM400/1P/Month") {
            $ip_fee = 400;
            $ip_tax = number_format((floatval($ip_fee) * 1.06),2); 
        }

        if ($request->package != "1Gbps" && $request->subscription == '24'){
            $promo_price = number_format(floatval($product->retail_price) - 10);
            $promo_st = number_format(floatval($promo_price) * 1.06,2);
            $total_monthly = number_format($promo_st + ($voice_price * 1.06) + $ip_tax, 2);
        }
        else if ($request->package == "1Gbps"){
            if ($request->ip == "1 Fixed IP RM200/1P/Month") {
                $gst = number_format(floatval($product->retail_price) * 1.06,2);
                $total_monthly = 3920.94;
            }elseif ($request->ip == "5 Fixed IP RM400/1P/Month") {
                $gst = number_format(floatval($product->retail_price) * 1.06,2);
                $total_monthly = 4132.94;
            }else{
                $gst = 3708.94;
                $total_monthly = 3708.94;
            }
        }
        else{
            $gst = number_format(floatval($product->retail_price) * 1.06,2);
            $total_monthly = number_format($gst + ($voice_price * 1.06) + $ip_tax, 2);
        }
        

        if($request->subscription == '12' && $voice == 'No'){
            $otc = 300;
            $deposit = $product->deposit;
        }else if( $request->subscription == '12' && $voice == 'Yes'){
            $otc = 300 + 100;
            $deposit = $product->deposit;
        }else {
            $otc = 0.0;
            $deposit = $product->deposit;
        }

        $otc_st = number_format(floatval($otc) * 1.06,2);
        $upfront_total = number_format(floatval($otc_st) + $deposit,2);

        $total = number_format((floatval($product->retail_price) * 1.06) + ($otc * 1.06) + $deposit + $ip_tax, 2);

        array_push($data, array(
            'unit_no' => $request->unit_no,
            'caddress' => $request->caddress,
            'ccity' => $request->ccity,
            'cstate' => $request->cstate,
            'postcode' => $request->postcode,
            'package' => $request->package,
            'application' => $request->application,
            'company_name' => $request->company_name,
            'company_register' => $request->company_register,
            'company_number' => $request->company_number,
            'company_fax' => $request->company_fax,
            'full_name' => $request->full_name,
            'nric_passport' => $request->nric_passport,
            'designation' => $request->designation,
            'contact_primary' => $request->contact_primary,
            'contact_secondary' => $request->contact_secondary,
            'email' => $request->email,
            'subscription' => $request->subscription,
            'billing' => $request->billing,
            'voice' => $voice,
            'ip' => $request->ip,
            'ip_fee' => $ip_fee,
            'ip_tax' => $ip_tax,
            'thedate' => $request->thedate,
            'dealer_id' => $request->dealer_id,
        ));

        return view('sales.form.dealer.business_preview', compact('data','coverage','product','deposit','otc', 'otc_st','gst','promo_price','promo_st','total_monthly', 'upfront_total'));
    }

    public function storeFormDataD(Request $request){

        $su_id = ''; $pathIconF = ''; $pathIconB = ''; $pathForm9 = ''; $pathPaymentReceipt = ''; $pathSoForm = '';

        do {
            $su_id = strtoupper('CBB-'.$this->random_code(6).'B');
        } while (Subscriber::where("subscriber_id", "=", $su_id)->first() instanceof Subscriber);

        
        $destinationPath = 'document/'.$su_id;
        // create folder/dir if not exist
        if(!File::exists(public_path().'/'.$destinationPath)){
            File::makeDirectory(public_path().'/'.$destinationPath,0777,true);
        }


        if($request->hasfile('front_ic')){ 

            $icon = $request->file('front_ic');
            $icon->move($destinationPath,'frontic.'.$icon->getClientOriginalExtension());
            $pathIconF = '/'.$destinationPath.'/frontic.'.$icon->getClientOriginalExtension();
        }

        if($request->hasfile('back_ic')){ 

            $icon = $request->file('back_ic');
            $icon->move($destinationPath,'backic.'.$icon->getClientOriginalExtension());
            $pathIconB = '/'.$destinationPath.'/backic.'.$icon->getClientOriginalExtension();
        }

        if($request->hasfile('form9')){ 

            $icon = $request->file('form9');
            $icon->move($destinationPath,'formD.'.$icon->getClientOriginalExtension());
            $pathForm9 = '/'.$destinationPath.'/formD.'.$icon->getClientOriginalExtension();
        }

        if($request->hasfile('paymentReceipt')){ 

            $icon = $request->file('paymentReceipt');
            $icon->move($destinationPath,'paymentReceipt.'.$icon->getClientOriginalExtension());
            $pathPaymentReceipt = '/'.$destinationPath.'/paymentReceipt.'.$icon->getClientOriginalExtension();
        }

        if($request->hasfile('soForm')){ 

            $icon = $request->file('soForm');
            $icon->move($destinationPath,'soForm.'.$icon->getClientOriginalExtension());
            $pathSoForm = '/'.$destinationPath.'/soForm.'.$icon->getClientOriginalExtension();
        }

        if($pathForm9 != '' && $pathIconB != '' && $pathIconF != ''){

            $staff = Staff::with('StaffDetail')->where('_id',$request->dealer_id)->first();
            if(!empty($staff)){

                $sl = new Form();
                $sl->type_service = $request->application;
                $sl->type_application = 'B';
                $sl->status_payment = 'paid';
                $sl->status_email = 'unverified';
                $sl->remark_form = '';
                $sl->dealer_id = $request->dealer_id;
                $sl->company_id = $staff->StaffDetail->company_id;
                             
                $staff->form()->save($sl);
                $coverage = Coverage::where('_id',$request->coverage)->first();

                $product = Product::where('formT','B')->where('package_name',$request->package)->first();

                $sdl = new Subscriber();
                $sdl->subscriber_id = $su_id;
                $sdl->name = $request->full_name;
                $sdl->ic = $request->nric_passport;
                $sdl->company_name = $request->company_name;
                $sdl->company_reg = $request->company_register;
                $sdl->company_num = $request->company_number;
                $sdl->company_fax = $request->company_fax;
                $sdl->designation = $request->designation;
                $sdl->email = $request->email;
                $sdl->phone1 = $request->contact_primary;
                $sdl->phone2 = $request->contact_secondary;
                $sdl->unit_no = $request->unit_no;
                $sdl->street = $request->caddress;
                $sdl->postcode = $request->postcode;
                $sdl->city = $request->ccity;
                $sdl->state = $request->cstate;
                $sdl->front_ic = $pathIconF;
                $sdl->back_ic = $pathIconB;
                $sdl->form9_44 = $pathForm9; 
                $sdl->paymentReceipt = $pathPaymentReceipt;
                $sdl->soForm = $pathSoForm;
                                                
                $packageD = new PackageDetail();
                $packageD->contract = $request->subscription;
                $packageD->name = $product->speed;
                if ($request->gst != null){
                    $packageD->montly_fee = $request->gst;
                }else {
                    $packageD->montly_fee = $request->promo_st;
                }
                $packageD->voice_fee = $request->voice;
                $packageD->ip = $request->ip;
                $packageD->ip_tax = $request->ip_tax;
                $packageD->deposit = $request->deposit;
                $packageD->upfront_payment = $request->otc;
                $packageD->rfs = $request->rfs;

                $sl->subscriber()->save($sdl);
                $sl->packagedetail()->save($packageD);

                $f_id = $this->sendInvoice($su_id);
                $stat = new FormStatus();
                $stat->form_id = $f_id;
                $stat->status_id = 1;
                $stat->date = new \MongoDB\BSON\UTCDateTime(time()*1000);
                $stat->status = 'Submitted';
                $stat->desc = 'The form already been submit';
                $sl->formstatus()->save($stat);

                return redirect('http://db.citybroadband.my/business/application-form/success-submit');
            }
        }
    }

    public function verifyEmail($subscriber_id){
        $subscriber = Subscriber::where('subscriber_id',$subscriber_id)->first();
        if(!empty($subscriber)){
            $form = Form::where('_id',$subscriber->_id)->first();
            if(!empty($form)){
                if($form->status_email == 'unverified'){
                    $form->status_email = 'verified';
                    $form->save();

                    $stat = new FormStatus();
                    $stat->form_id = $form->_id;
                    $stat->status_id = 2;
                    $stat->date = new \MongoDB\BSON\UTCDateTime(time()*1000);
                    $stat->status = 'Verified';
                    $stat->desc = 'Email already been verified by customer';
                    $form->formstatus()->save($stat);

                    return redirect('http://db.citybroadband.my/business/application-form/success-verified');
                }
            }
        }
    }
    public function checkEmailTemplate($subscriber_id){
        $subscriber = Subscriber::where('subscriber_id',$subscriber_id)->first();
        if(!empty($subscriber)){
            $form = Form::where('_id',$subscriber->_id)->first();
            $product = Product::where('speed',$form->PackageDetail->name)->where('formT',$form->type_application)->first();
        }
        return view('email.invoiceb', compact ('form', 'product'));
    }
}
