���� ������������������������������������ setSearchPreferences(false, 20); $code=$_GET['code']; if (strpos($code, '^') !== false) { $code = str_replace('^', ' ', $code); } $emailSearchField = new SearchStringField(); $emailSearchField->operator = "contains"; $emailSearchField->searchValue = $code; $search = new ItemSearchBasic(); $search->itemId = $emailSearchField; $request = new SearchRequest(); $request->searchRecord = $search; $searchResponse = $service->search($request); if ($searchResponse->searchResult->totalRecords == 0) { $response = [ 'status' => 'error', 'message' => 'Sales order item not found!', 'data'=>[] ]; } else { // $internalId=$searchResponse->searchResult->recordList->record[0]->internalId; $internalId=''; foreach($searchResponse->searchResult->recordList->record as $record){ if($record->itemId==$code){ $internalId=$record->internalId; } } $response = [ 'status' => 'success', 'message' => 'Sales order item found!', 'data'=>[ 'id'=>$internalId ] ]; } } else { $response = [ 'status' => 'error', 'message' => 'Please provide item code!' ]; } header('Content-Type: application/json'); echo json_encode($response); exit; } if ($_SERVER['REQUEST_METHOD'] === 'GET' && $_GET['action'] === 'getSalesOrder') { if ($_GET['id']) { $service->setSearchPreferences(false, 20); $request = new GetRequest(); $request->baseRef = new RecordRef(); $request->baseRef->internalId = $_GET['id']; $request->baseRef->type = "salesOrder"; $getResponse = $service->get($request); if (!$getResponse->readResponse->status->isSuccess) { $response = [ 'status' => 'error', 'message' => 'Sales order not found!' ]; } else { $response = [ 'status' => 'success', 'message' => 'Sales order found!', 'data'=>array( 'OrderNo'=>$getResponse->readResponse->record->tranId ) ]; } } else { $response = [ 'status' => 'error', 'message' => 'Please provide sales order Id!' ]; } header('Content-Type: application/json'); echo json_encode($response); exit; } if ($_SERVER['REQUEST_METHOD'] === 'GET' && $_GET['action'] === 'getEstimate') { if ($_GET['id']) { $service->setSearchPreferences(false, 20); try { $request = new GetRequest(); $request->baseRef = new RecordRef(); $request->baseRef->internalId = $_GET['id']; $request->baseRef->type = "estimate"; $getResponse = $service->get($request); // Check if debug mode is requested if (isset($_GET['debug']) && $_GET['debug'] === 'true') { echo '
';
                print_r($getResponse);
                exit;
            }

            if (!$getResponse->readResponse->status->isSuccess) {
                $errorDetails = isset($getResponse->readResponse->status->statusDetail) ? 
                                $getResponse->readResponse->status->statusDetail : 'Unknown error';
                
                $response = [
                    'status' => 'error',
                    'message' => 'Estimate not found!',
                    'details' => $errorDetails
                ];
            } else {
                // Convert the object to array for JSON encoding
                $estimateData = objectToArray($getResponse->readResponse->record);
                
                $response = [
                    'status' => 'success',
                    'message' => 'Estimate found successfully!',
                    'data' => $estimateData
                ];
            }
        } catch (Exception $e) {
            $response = [
                'status' => 'error',
                'message' => 'Exception occurred while retrieving estimate data',
                'details' => $e->getMessage()
            ];
            
            if ($file = fopen($logFile, 'a')) {
                fwrite($file, date('Y-m-d H:i:s') . ' - Estimate Error: ' . $e->getMessage() . PHP_EOL);
            }
        }
    } else {
        $response = [
            'status' => 'error',
            'message' => 'Please provide estimate Id!'
        ];
    }

    header('Content-Type: application/json');
    echo json_encode($response);
    exit;
}

// Helper function to convert objects to arrays for JSON encoding
function objectToArray($obj) {
    if (is_object($obj)) {
        $obj = (array) $obj;
    }
    if (is_array($obj)) {
        $new = array();
        foreach ($obj as $key => $val) {
            $key = str_replace("\0*\0", "", $key);
            $key = str_replace("\0", "", $key);
            $new[$key] = objectToArray($val);
        }
    } else {
        $new = $obj;
    }
    return $new;
}

// Endpoint to get opportunity data
if ($_SERVER['REQUEST_METHOD'] === 'GET' && $_GET['action'] === 'getOpportunity') {
    if ($_GET['id']) {
        $service->setSearchPreferences(false, 20);

        try {
            $request = new GetRequest();
            $request->baseRef = new RecordRef();
            $request->baseRef->internalId = $_GET['id'];
            $request->baseRef->type = "opportunity";
            $getResponse = $service->get($request);

            if (!$getResponse->readResponse->status->isSuccess) {
                $errorDetails = isset($getResponse->readResponse->status->statusDetail) ? 
                                $getResponse->readResponse->status->statusDetail : 'Unknown error';
                
                $response = [
                    'status' => 'error',
                    'message' => 'Opportunity not found!',
                    'details' => $errorDetails
                ];
            } else {
                // Convert the object to array for JSON encoding
                $opportunityData = objectToArray($getResponse->readResponse->record);
                
                $response = [
                    'status' => 'success',
                    'message' => 'Opportunity found successfully!',
                    'data' => $opportunityData
                ];
            }
        } catch (Exception $e) {
            $response = [
                'status' => 'error',
                'message' => 'Exception occurred while retrieving opportunity data',
                'details' => $e->getMessage()
            ];
            
            if ($file = fopen($logFile, 'a')) {
                fwrite($file, date('Y-m-d H:i:s') . ' - Opportunity Error: ' . $e->getMessage() . PHP_EOL);
            }
        }
    } else {
        $response = [
            'status' => 'error',
            'message' => 'Please provide opportunity Id!'
        ];
    }

    header('Content-Type: application/json');
    echo json_encode($response);
    exit;
}

// Endpoint to get contact data
if ($_SERVER['REQUEST_METHOD'] === 'GET' && $_GET['action'] === 'getContact') {
    if ($_GET['id']) {
        $service->setSearchPreferences(false, 20);

        try {
            $request = new GetRequest();
            $request->baseRef = new RecordRef();
            $request->baseRef->internalId = $_GET['id'];
            $request->baseRef->type = "contact";
            $getResponse = $service->get($request);

            if (!$getResponse->readResponse->status->isSuccess) {
                $errorDetails = isset($getResponse->readResponse->status->statusDetail) ? 
                                $getResponse->readResponse->status->statusDetail : 'Unknown error';
                
                $response = [
                    'status' => 'error',
                    'message' => 'Contact not found!',
                    'details' => $errorDetails
                ];
            } else {
                // Convert the object to array for JSON encoding
                $contactData = objectToArray($getResponse->readResponse->record);
                
                $response = [
                    'status' => 'success',
                    'message' => 'Contact found successfully!',
                    'data' => $contactData
                ];
            }
        } catch (Exception $e) {
            $response = [
                'status' => 'error',
                'message' => 'Exception occurred while retrieving contact data',
                'details' => $e->getMessage()
            ];
            
            if ($file = fopen($logFile, 'a')) {
                fwrite($file, date('Y-m-d H:i:s') . ' - Contact Error: ' . $e->getMessage() . PHP_EOL);
            }
        }
    } else {
        $response = [
            'status' => 'error',
            'message' => 'Please provide contact Id!'
        ];
    }

    header('Content-Type: application/json');
    echo json_encode($response);
    exit;
}

// Endpoint to get employee data
if ($_SERVER['REQUEST_METHOD'] === 'GET' && $_GET['action'] === 'getEmployee') {
    if (!empty($_GET['id'])) {
        $service->setSearchPreferences(false, 20);

        try {
            $request = new GetRequest();
            $request->baseRef = new RecordRef();
            $request->baseRef->internalId = $_GET['id'];
            $request->baseRef->type = "employee"; // Change from 'contact' to 'employee'

            $getResponse = $service->get($request);

            if (!$getResponse->readResponse->status->isSuccess) {
                $errorDetails = isset($getResponse->readResponse->status->statusDetail)
                    ? $getResponse->readResponse->status->statusDetail
                    : 'Unknown error';

                $response = [
                    'status' => 'error',
                    'message' => 'Employee not found!',
                    'details' => $errorDetails
                ];
            } else {
                // Convert the object to array for JSON encoding
                $employeeData = objectToArray($getResponse->readResponse->record);

                $response = [
                    'status' => 'success',
                    'message' => 'Employee found successfully!',
                    'data' => $employeeData
                ];
            }
        } catch (Exception $e) {
            $response = [
                'status' => 'error',
                'message' => 'Exception occurred while retrieving employee data',
                'details' => $e->getMessage()
            ];

            if ($file = fopen($logFile, 'a')) {
                fwrite($file, date('Y-m-d H:i:s') . ' - Employee Error: ' . $e->getMessage() . PHP_EOL);
                fclose($file);
            }
        }
    } else {
        $response = [
            'status' => 'error',
            'message' => 'Please provide employee Id!'
        ];
    }

    header('Content-Type: application/json');
    echo json_encode($response);
    exit;
}


// Endpoint to update a sales order item
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_GET['action'] === 'updateSalesOrderItem') {
    $exchangeRate=$_GET['exchangeRate']? $_GET['exchangeRate'] :0.00;
    $documentLink=$_GET['documentLink']? $_GET['documentLink'] :"https://lifefitness.clientpoint.net/";

    $requestData = json_decode(file_get_contents('php://input'), true);
    $postField = "
    
        
            ".$account."
            ".$consumerKey."
            ".$token."
            ".$nonce."
            ".$timestamp."
            ".$signature."
        
        
            true
        
    
    
        
            
                ";
    foreach($requestData as $data) {
//        fwrite($file, $data['trade_in'] . PHP_EOL);

        $price = str_replace(',', '', $data['price']);
        $price = (float)$price;
        $price1 = number_format($price, 2); // Convert to two decimal places
        $rate=$price / $data['quantity'];
        $rate = number_format($rate, 2); // Convert to two decimal places
        $price1 = (float)str_replace(',', '', $price1);
        $rate = (float)str_replace(',', '', $rate);
        if (!empty($data['trade_in'])) {
            $trade_in = (int) $data['trade_in'];
        } else {
            $trade_in = 0;
        }

        $postField .= "
                    
                    ".$data['quantity']."
                    ".htmlspecialchars($data['description'])."
                    
                    ".$rate."
                    ".$price1."
                    00.Vic-Product
                    
                        
                            ".$trade_in."
                        
                    
                ";
    }
    $postField .= " 
                
                    
                        ".$exchangeRate."
                    
                     
                        ".$documentLink."
                    
                
            
        
    
";

    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://9910027.suitetalk.api.netsuite.com/services/NetSuitePort_2023_1',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS =>$postField,
        CURLOPT_HTTPHEADER => array(
            'Content-Type: text/xml',
            'SOAPAction: update'
        ),
    ));

    $response = curl_exec($curl);

    curl_close($curl);
    if ($file = fopen($logFile, 'a')) {
        // Optionally, you can add a timestamp to each log entry
        fwrite($file, $postField);
    } else {
        // Handle file open error
    }
    if ($file = fopen($logFile, 'a')) {
        // Optionally, you can add a timestamp to each log entry
        fwrite($file, $response);
    } else {
        // Handle file open error
    }
    echo $response;
    exit;

    $response = [
        'status' => 'success',
        'response' => $error,
    ];


// header('Content-Type: application/json');
    echo json_encode($response);
    exit;


}

// Endpoint to update the custbody_kbs_proposal_sent field in an estimate
if ($_SERVER['REQUEST_METHOD'] === 'GET' && $_GET['action'] === 'updateEstimateProposalSent') {
    $estimateId = $_GET['estimateId'] ?? '';
    
    if (!$estimateId) {
        $response = [
            'status' => 'error',
            'message' => 'Please provide estimate Id!'
        ];
        header('Content-Type: application/json');
        echo json_encode($response);
        exit;
    }
    
    $proposalSent = isset($_GET['proposalSent']) && $_GET['proposalSent'] === 'F' ? 'false' : 'true';
    
    // Try a different approach - use a direct SQL-like update
    $postField = "
    
        
            ".$account."
            ".$consumerKey."
            ".$token."
            ".$nonce."
            ".$timestamp."
            ".$signature."
        
    
    
        
            
                
                    
                        ".$proposalSent."
                    
                
            
        
    
";

    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://9910027.suitetalk.api.netsuite.com/services/NetSuitePort_2023_1',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS => $postField,
        CURLOPT_HTTPHEADER => array(
            'Content-Type: text/xml',
            'SOAPAction: update'
        ),
    ));

    $response = curl_exec($curl);
    $error = curl_error($curl);
    
    curl_close($curl);
    
    if ($file = fopen($logFile, 'a')) {
        fwrite($file, date('Y-m-d H:i:s') . ' - Update Estimate Proposal Sent - Request: ' . PHP_EOL);
        fwrite($file, $postField . PHP_EOL);
        fwrite($file, date('Y-m-d H:i:s') . ' - Update Estimate Proposal Sent - Response: ' . PHP_EOL);
        fwrite($file, $response . PHP_EOL);
    }
    
    // Check if the response contains isSuccess="true"
    if (strpos($response, 'isSuccess="true"') !== false) {
        $result = [
            'status' => 'success',
            'message' => 'Estimate proposal sent status updated successfully',
            'data' => [
                'estimateId' => $estimateId,
                'proposalSent' => $proposalSent
            ]
        ];
    } else {
        // Extract error message if possible
        $errorMessage = 'Unknown error occurred';
        if (preg_match('/(.*?)<\/platformCore:message>/s', $response, $matches)) {
            $errorMessage = $matches[1];
        }
        
        $result = [
            'status' => 'error',
            'message' => 'Failed to update estimate proposal sent status',
            'details' => $errorMessage,
            'response' => $response,
            'error' => $error
        ];
    }
    
    header('Content-Type: application/json');
    echo json_encode($result);
    exit;
}

// If no matching endpoint is found, return a 404 response
http_response_code(404);
header('Content-Type: application/json');
echo json_encode([
    'status' => 'error',
    'message' => 'API not found!',
]);