<?php
class Account {
    public static function create($input) {
            
            error_log("INPUT GENERAL CUENTA".print_r($input,true)."\n", 3, "php.log");
       $OPFGlobal = new OPFGlobal();
       $OPFGlobal->initOPF();

       $rut_code = $input["rut_code"];

       $SQL = "SELECT accountid FROM vtiger_account
             INNER JOIN vtiger_crmentity ON vtiger_crmentity.crmid=vtiger_account.accountid AND deleted='0'
             where siccode = '$rut_code'";

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

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

       $dataWS = array();
       $dataWS["accountname"] = $input["accountname"];
       $dataWS["cf_751"] = $input["razon_social"];
       $dataWS["siccode"] = $rut_code;
       $dataWS["cf_946"] = $input["rut"];
       $dataWS["email1"] = $input["email"];
       //$dataWS["phone"] = $input["phone"];
       $dataWS["cf_757"] = $input["status"];
       $dataWS["bill_street"] = $input["address_comercial"];
       $dataWS["bill_city"] = $input["comuna_comercial"];
       $dataWS["bill_state"] = $input["region_comercial"];
       $dataWS["bill_country"] = $input["country_comercial"];
       $dataWS["ship_street"] = $input["address_shipping"];
       $dataWS["ship_city"] = $input["comuna_shipping"];
       $dataWS["ship_state"] = $input["region_shipping"];
       $dataWS["ship_country"] = $input["country_shipping"];

       ob_start();
       $accountid = @$OPFGlobal->crearByWS('Accounts', $dataWS,'CuentasWS.log',false,true);
       $output = ob_get_clean();

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

       return ['accountid' => $accountid];

    }
}
