<?php
   
    $mess="Error";
    $CompID=0;
    if (isset($_POST["comp_id"]))
    {
         $CompID=$_POST["comp_id"]; 
    }
    if($CompID==0) {
          $mess= "Error: Web Co ID invalid";
          die($mess);
    }
    include_once 'opendb.php';
    $EDIT_TIME=date("ymdHi");
    $cust_name=$_POST["ACC_NAME"];
    $cust_name = str_replace("&", "and", $cust_name);
    $cust_add=$_POST["ADDRESS"];
    $cust_add = str_replace("&", "and", $cust_add);
    $sql = "UPDATE subsidiary SET SUB_NAME='".$cust_name."'," 
                                ."ADDRESS='".$cust_add."'," 
                                ."EMAIL='".$_POST["EMAIL"]."'," 
                                ."PLACE=''," 
                                ."PHONE='".$_POST["PHONE"]."'," 
                                ."MOBILE='".$_POST["MOBILE"]."'," 
                                ."FAX='',"
                                ."CONT_NAME=''," 
                                ."CONT_PHONE='',"
                                ."AREA_CODE=''," 
                                ."Area_Name='".$_POST["AREA"]."'," 
                                ."SMAN_CODE='".$_POST["client_Code"]."'," 
                                ."SUB_TYPE='C'," 
                                ."Inactive=0,"                                   
                                ."Reg_No1='".$_POST["REG_NO"]."'," 
                                ."price_level=0," 
                                ."App_Pass='12345'," 
                                ."EDIT_TIME=".$EDIT_TIME;
    if($_POST["Action"]=='New'){
        $sql.=",create_source=2,comp_id=$CompID,sub_code='". $_POST["ACC_CODE"] . "'  WHERE pkey=".$_POST["pKey"];
    } else {
         if ( !startsWith( $_POST["ACC_CODE"],"W")){
            $conn->close();
            die("Error : Edit not permitted for this customer");
        }
        $sql.="  WHERE sub_code like '". $_POST["ACC_CODE"] . "' and comp_id=".$CompID;
    } 
   // die($sql);
    if ($conn->query($sql) === TRUE) {
        $mess="OK";
    } else {
        $mess= "Error updating customer record: " . $conn->error.$sql;
        $errorLog = "Error updating customer record: " . $conn->error . "\nSQL Query: " . $sql . "\n";
        $logFile = 'error_logs.txt'; // Specify the log file path here.
        file_put_contents($logFile, $errorLog, FILE_APPEND);
    }
    $conn->close();
    echo  $mess;
    
      function startsWith ($string, $startString)
    {
        $len = strlen($startString);
        return (substr($string, 0, $len) === $startString);
    }
    
?>