import { Component, Inject, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { MdDialogRef, MD_DIALOG_DATA } from '@angular/material';
import { ContactService } from '../../contact.service';

@Component({
  selector: 'app-add-plan',
  templateUrl: './add-plan.component.html',
  styleUrls: ['./add-plan.component.scss']
})
export class AddPlanComponent implements OnInit {
  planForm:FormGroup;
  title="Add New Plan"
  useridd;
  or
  constructor(public dialogRef: MdDialogRef<AddPlanComponent>,
    @Inject(MD_DIALOG_DATA) public data: any,private fb:FormBuilder,private contactService:ContactService) { }

  ngOnInit() {
    this.useridd = JSON.parse(window.atob(window.localStorage.token.split('.')[1]))._id;
    this.or = JSON.parse(window.atob(window.localStorage.token.split(".")[1]))._orgName; 
    this.planForm=this.fb.group({
      Name:[''],
      Status:[''],
      Amount:[''],
      Duration_days:[''],
      SupAdmin:[this.useridd],
      Org:[this.or]
    })
    if(this.data!=null){
      this.title="Edit Plan Details";
      this.patchPlanForm()
    }
  }

  patchPlanForm(){
  this.planForm.patchValue({
      Name:this.data.Name,
      Status:this.data.Status,
      Amount:this.data.Amount,
      Duration_days:this.data.Duration_days,
      SupAdmin:[this.useridd],
      Org:[this.or]
    })
  }

  submit(){
      console.log(this.planForm.value);
      this.contactService.post('/RechargePlan/add',this.planForm.value).subscribe(res=>{
        console.log(res);
        this.dialogRef.close("succ")
      })
  }

  editPlan(){
    var data={
      _id:this.data._id,
      Name:this.planForm.value.Name,
      Status:this.planForm.value.Status,
      Amount:this.planForm.value.Amount,
      Duration_days:this.planForm.value.Duration_days,
      SupAdmin:this.planForm.value.SupAdmin,
      Org:this.planForm.value.Org
    }

    this.contactService.post('/RechargePlan/edit',data).subscribe(res=>{
      console.log(res);
         this.dialogRef.close("succ")
    })
  }

}
