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

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

use App\Mail\CustomerInvoice;
use App\Jobs\SendCustomerInvoice;

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 ResidentialController 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();
        SendCustomerInvoice::dispatch($form, $product, $form->Subscriber->email);

        return $form->_id;
    }

    public function sendInvoice1($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();
        SendCustomerInvoice::dispatch($form, $product, 'nsakinahs1991@gmail.com');

        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 = '';
        $coverage = Coverage::where('Type','R')->orderBy('building_name')->get();
        return view('sales.form.residential_address', compact('coverage','package','dealer_id'));
    }

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

        array_push($data, array(
            'coverage' => $request->coverage,
            'unit' => $request->unit,
            'street' => $request->street,
            'package' => $request->package
        ));
        return view('sales.form.residential_application_information', compact('data'));
    }

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

        $citizen = ''; $street = '';
        if($request->citizenship == "Malaysian"){
            $citizen = $request->citizenship;
        }
        else {
            $citizen = $request->citizenlist;
        }

        if($request->street != null){
            $street = $request->street;
        }

        if (!empty($request->nric_passport1)){
            $nokp = $request->nric_passport1;
        }else {
            $nokp = $request->nric_passport2;
        }

        array_push($data, array(
            'coverage' => $request->coverage,
            'unit' => $request->unit,
            'street' => $street,
            'package' => $request->package,
            'application' => $request->application,
            'name' => $request->name,
            'nric_passport' => $nokp,
            'gender' => $request->gender,
            'race' => $request->race,
            'contact_primary' => $request->contact_primary,
            'contact_secondary' => $request->contact_secondary,
            'citizenship' => $citizen,
            'email' => $request->email
        ));

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

        return view('sales.form.residential_package', compact('data','product','citizen'));
    }

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

        $coverage = Coverage::where('_id',$request->coverage)->first();
        $product = Product::where('formT','R')->where('package_name',$request->package)->first();
        $otc = 0.0; $deposit = 0.0;

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

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

        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), 2);
        }
        else{
            $gst = number_format(floatval($product->retail_price) * 1.06,2);
            $total_monthly = number_format($gst + ($voice_price * 1.06), 2);
        }

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

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

        array_push($data, array(
            'coverage' => $request->coverage,
            'unit' => $request->unit,
            'street' => $request->street,
            'package' => $request->package,
            'application' => $request->application,
            'name' => $request->name,
            'nric_passport' => $request->nric_passport,
            'gender' => $request->gender,
            'race' => $request->race,
            'contact_primary' => $request->contact_primary,
            'contact_secondary' => $request->contact_secondary,
            'citizenship' => $request->citizenship,
            'email' => $request->email,
            'subscription' => $request->subscription,
            'billing' => $request->billing,
            'voice' => $voice,
            'thedate' => $request->thedate,
        ));

       return view('sales.form.residential_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 = ''; $pathVisaF = ''; $pathVisaB = '';

        do {
            $su_id = strtoupper('CBB-'.$this->random_code(6).'R');
        } 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);
        }

        $uploaded = public_path().'/'.$destinationPath;
        // Signature
        $signature_form = $request->cuss_signature;
        $signature_form = str_replace('data:image/jpeg;base64,','',$signature_form);
        $signature_form = str_replace('','+',$signature_form);
        //convert signature_form
        $data = base64_decode($signature_form);
        $file = $uploaded."/signature_form.jpg";
        $savetoServer = file_put_contents($file,$data);
        
        if (($savetoServer === false) || ($savetoServer == -1)) {
            print "Couldn't save signature to jpeg";
        }else {

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

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

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

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

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

                $icon = $request->file('visaF');
                $icon->move($destinationPath,'visaF.'.strtolower($icon->getClientOriginalExtension()));
                $pathVisaF = '/'.$destinationPath.'/visaF.'.strtolower($icon->getClientOriginalExtension());
            }

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

                $icon = $request->file('visaB');
                $icon->move($destinationPath,'visaB.'.strtolower($icon->getClientOriginalExtension()));
                $pathVisaB = '/'.$destinationPath.'/visaB.'.strtolower($icon->getClientOriginalExtension());
            }

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

            $coverage = Coverage::where('_id',$request->coverage)->first();
            $product = Product::where('formT','R')->where('package_name',$request->package)->first();

            $sdl = new Subscriber();
            $sdl->subscriber_id = $su_id;
            $sdl->name = $request->name;
            $sdl->ic = $request->nric_passport;
            $sdl->citizen = $request->citizenship;
            $sdl->gender = $request->gender;
            $sdl->race = $request->race;
            $sdl->email = $request->email;
            $sdl->phone1 = $request->contact_primary;
            $sdl->phone2 = $request->contact_secondary;
            $sdl->unit_no = $request->unit;
            $sdl->building_name = $coverage->building_name;
            $sdl->street = $request->street;
            $sdl->postcode = $coverage->postcode;
            $sdl->city = $coverage->city;
            $sdl->state = $coverage->state;
            $sdl->front_ic = $pathIconF;
            $sdl->back_ic = $pathIconB;
            $sdl->visaF = $pathVisaF;
            $sdl->visaB = $pathVisaB;     
            $sdl->signature = '/'.$destinationPath.'/signature_form.jpg';

            $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->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/residential/application-form/success-submit');
        }
    }

    /**
    ** Dealer
     **/
    public function viewFormAddressD($package,$dealer_id) {

        $coverage = Coverage::where('Type','R')->orderBy('building_name')->get();
        return view('sales.form.dealer.residential_address', compact('coverage','package','dealer_id'));
    }

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

        array_push($data, array(
            'coverage' => $request->coverage,
            'unit' => $request->unit,
            'street' => $request->street,
            'package' => $request->package,
            'dealer_id' => $request->dealer_id
        ));

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

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

        $citizen = ''; $street = '';
        if($request->citizenship == "Malaysian"){
            $citizen = $request->citizenship;
        }
        else {
            $citizen = $request->citizenlist;
        }

        if($request->street != null){
            $street = $request->street;
        }

        if (!empty($request->nric_passport1)){
            $nokp = $request->nric_passport1;
        }else {
            $nokp = $request->nric_passport2;
        }

        array_push($data, array(
            'dealer_id' => $request->dealer_id,
            'coverage' => $request->coverage,
            'unit' => $request->unit,
            'street' => $street,
            'package' => $request->package,
            'application' => $request->application,
            'name' => $request->name,
            'nric_passport' => $nokp,
            'ip' => $request->ip,
            'gender' => $request->gender,
            'race' => $request->race,
            'contact_primary' => $request->contact_primary,
            'contact_secondary' => $request->contact_secondary,
            'citizenship' => $citizen,
            'email' => $request->email
        ));

        $product = Product::where('formT','R')->where('package_name',$request->package)->first();
        
        return view('sales.form.dealer.residential_package', compact('data','product','citizen'));
    }

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

        $coverage = Coverage::where('_id',$request->coverage)->first();
        $product = Product::where('formT','R')->where('package_name',$request->package)->first();
        $otc = 0.0; $deposit = 0.0;

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

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

        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), 2);
        }
        else{
            $gst = number_format(floatval($product->retail_price) * 1.06,2);
            $total_monthly = number_format($gst + ($voice_price * 1.06), 2);
        }

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

        $otc_st = number_format(floatval($otc) * 1.06,2);
        $upfront_total = number_format(floatval($otc_st) + $deposit,2);
        
        array_push($data, array(
            'dealer_id' => $request->dealer_id,
            'coverage' => $request->coverage,
            'unit' => $request->unit,
            'street' => $request->street,
            'package' => $request->package,
            'application' => $request->application,
            'name' => $request->name,
            'nric_passport' => $request->nric_passport,
            'gender' => $request->gender,
            'race' => $request->race,
            'contact_primary' => $request->contact_primary,
            'contact_secondary' => $request->contact_secondary,
            'citizenship' => $request->citizenship,
            'email' => $request->email,
            'subscription' => $request->subscription,
            'billing' => $request->billing,
            'voice' => $voice,
            'ip' => $request->ip,
            'thedate' => $request->thedate,
        ));

       return view('sales.form.dealer.residential_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 = ''; $pathVisaF = ''; $pathVisaB = ''; $pathPaymentReceipt=''; $pathSOForm='';

        do {
            $su_id = strtoupper('CBB-'.$this->random_code(6).'R');
        } 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);
        }

        $uploaded = public_path().'/'.$destinationPath;
        // Signature
        $signature_form = $request->cuss_signature;
        $signature_form = str_replace('data:image/jpeg;base64,','',$signature_form);
        $signature_form = str_replace('','+',$signature_form);
        //convert signature_form
        $data = base64_decode($signature_form);
        $file = $uploaded."/signature_form.jpg";
        $savetoServer = file_put_contents($file,$data);
        
        if (($savetoServer === false) || ($savetoServer == -1)) {
            print "Couldn't save signature to jpeg";
        }else {

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

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

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

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

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

                $icon = $request->file('visaF');
                $icon->move($destinationPath,'visaF.'.strtolower($icon->getClientOriginalExtension()));
                $pathVisaF = '/'.$destinationPath.'/visaF.'.strtolower($icon->getClientOriginalExtension());
            }

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

                $icon = $request->file('visaB');
                $icon->move($destinationPath,'visaB.'.strtolower($icon->getClientOriginalExtension()));
                $pathVisaB = '/'.$destinationPath.'/visaB.'.strtolower($icon->getClientOriginalExtension());
            }

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

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

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

                $icon = $request->file('so_form');
                $icon->move($destinationPath,'so_form.'.strtolower($icon->getClientOriginalExtension()));
                $pathSOForm = '/'.$destinationPath.'/so_form.'.strtolower($icon->getClientOriginalExtension());
            }

            // staff
            $staff = Staff::with('StaffDetail')->where('_id',$request->dealer_id)->first();
            if(!empty($staff)){
                $sl = new Form();
                $sl->type_service = $request->application;
                $sl->type_application = 'R';
                $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','R')->where('package_name',$request->package)->first();

                $sdl = new Subscriber();
                $sdl->subscriber_id = $su_id;
                $sdl->name = $request->name;
                $sdl->ic = $request->nric_passport;
                $sdl->citizen = $request->citizenship;
                $sdl->gender = $request->gender;
                $sdl->race = $request->race;
                $sdl->email = $request->email;
                $sdl->phone1 = $request->contact_primary;
                $sdl->phone2 = $request->contact_secondary;
                $sdl->unit_no = $request->unit;
                $sdl->building_name = $coverage->building_name;
                $sdl->street = $request->street;
                $sdl->postcode = $coverage->postcode;
                $sdl->city = $coverage->city;
                $sdl->state = $coverage->state;
                $sdl->front_ic = $pathIconF;
                $sdl->back_ic = $pathIconB;
                $sdl->visaF = $pathVisaF;
                $sdl->visaB = $pathVisaB;
                $sdl->paymentReceipt = $pathPaymentReceipt;
                $sdl->soForm = $pathSOForm;
                $sdl->signature = '/'.$destinationPath.'/signature_form.jpg';

                $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->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/residential/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/residential/application-form/success-verified');
                }
            }
        }
    }


    public function resendEmail($subscriber_id){
        $f_id = $this->sendInvoice($subscriber_id);
        return $f_id;
    }

    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.invoice', compact ('form', 'product'));
    }
}

