<?php
class Contact {
    public static function create($input) {
            
       $OPFGlobal = new OPFGlobal();
       $OPFGlobal->initOPF();

       $email = $input["email"];

       $SQL = "SELECT contactid FROM vtiger_contactdetails
             INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_contactdetails.contactid AND deleted='0'
             where email = '$email'";

       $result = mysqli_query($OPFGlobal->link,$SQL); 
       
        if($result){
            $rowData = mysqli_fetch_assoc($result);
            if ($rowData <> null) {
                return ['contactid' => $rowData["contactid"]];
            }

        }else{
            throw new Exception("Error consultando la BD ".mysqli_error($OPFGlobal->link),500);
        }

       $dataWS = array();
       $dataWS["email"] = $email;
       $dataWS["firstname"] = $input["name"];
       $dataWS["lastname"] = $input["lastname"];
       $dataWS["mobile"] = $input["phone"];
       $dataWS["homephone"] = $input["phone2"];

       ob_start();
       $contactid = @$OPFGlobal->crearByWS('Contacts', $dataWS,'ContactosWS.log',false,true);
       $output = ob_get_clean();

       if ($output <> "") {
          throw new Exception(json_decode($contactid,true)["id"]["message"],500);   
       }

       return ['contactid' => $contactid];

    }
}
