<?php
include('includes/config/config.php');
include('includes/functions.php');
include('log_entry.php');
error_log("Start Printing Request Attributes");
$requestStr = "";
foreach ($_REQUEST as $key => $value) {
    $requestStr .= $key . " : " . $value . "\n";
    error_log($key . " : " . $value . "<br />\r\n");
}
error_log("End Printing Request Attributes");
save_log($requestStr, 'Interpretation', 'SAVE', 'save_inter.php');
$noOfRows = $_POST['count_items'];


begin();
//echo $noOfRows;
$id = $_POST['id'];

$initquery = "";
//$data = array();
$endquery = "";
if (!empty($id)) {
    //update case
    $initquery = "update ";
    $endquery = " where id = '" . $id . "' ";
} else {
    //insert case
    $initquery = "INSERT INTO ";
}
$query = $initquery . " interpretation_master set interpretation_header = '" . $interpretation_header . "',modified_by = '" . $_SESSION['user_id'] . "'  $endquery ";
echo $query;
error_log("query: " . $query);

if (!$result = @mysqli_query($conn, $query)) {
    rollback();
    header('HTTP/1.1 500 Internal Server Error');
    echo json_encode(die('failed!' . mysqli_error($conn)));
} else {

    if (empty($id)) {
        $id = mysqli_insert_id($conn);
        error_log("id " . $id);
    } else {
        $query_del = " delete from interpretation_detail where interpretation_id = '" . $id . "' ";
        error_log("delete query for interpretation_detail: " . $query_del);
        $result_del = @mysqli_query($conn, $query_del);
    }
    //clear existing entries into the child table

    for ($i = 0; $i < $noOfRows; $i++) {

        if (isset(${"key$i"}) || ${"key$i"} != null || ${"key$i"} != '') {

            $query1 = "insert into interpretation_detail set interpretation_id='" . $id . "' , interpretation_key='" . ${"key$i"} . "' , interpretation_value='" . ${"value$i"} . "' ";

            error_log("insert query in items " . $query1);

            if (!$result1 = @mysqli_query($conn, $query1)) {
                rollback();
                header('HTTP/1.1 500 Internal Server Error');
                echo json_encode(die('failed!' . mysqli_error($conn)));
            }
        }
    }
}
commit();