<?php 
require_once('dbClass.php');

// session_start();
// Retrieve parameters
$data = $_GET['data'] ?? "";
$ReportID = $_GET['ReportID'] ?? 0;
$UserID = $_SESSION['user_id'] ?? 0;
$TemplateID = $_GET['templateId'] ?? 0;
$TypeID = $_GET['typeID'] ?? 0;
$TemplateName=$_GET['templateName'] ?? 0;
$TemplateDescription=$_GET['templateDescription'] ?? 0;

//TO GET THE DATA ON FIRST LOAD
$getAllData=$_GET['getAllData'] ?? 0;
if($getAllData){
    include "reportModel.php";
    $sql = "SELECT * FROM $db[0]";// WHERE 1=1 ";
    $requestArray = [];
    /*
    for($i = 0; $i < sizeof($filterCode); $i++){
        if(isset($_REQUEST[$filterCode[$i][1]]) || isset($_REQUEST[$filterCode[$i][2]])){
            if(isset($_REQUEST[$filterCode[$i][1]])){
                $requestArray[$filterCode[$i][1]] = $_REQUEST[$filterCode[$i][1]];
            }else{
                $requestArray[$filterCode[$i][2]] = $_REQUEST[$filterCode[$i][2]];
            }
        }
    }
      //print_r($requestArray);
    foreach($_REQUEST as $name => $value) {
        if($name != "ReportID" && $name != "view") {
            // $requestArray[$name] = $value;
            if(isset($name)) {
                if(gettype($value) == "array") {
                    if(sizeof($value) > 0) {
                        $sql .= " AND $name IN ('" . implode("','", $value) . "' ) ";
                    }
                } else {
                    if(is_numeric($value)) {
                        $valueINT = (float) $value;
                        if($valueINT !== 0) {
                           $sql .= " AND $name = $valueINT ";
                        }
                    } else {
                        if(strlen($value) > 0) {
                            $sql .= " AND $name = '$value' ";
                        }
                    }
                }
            }
        }
    }*/
  
       //echo $sql;
    $viewResult = db::getInstance()->db_select($sql);
    // print_r($viewResult);
    // echo json_encode($viewResult['result_set']);
    $finalResult = array();
    $jsonData = "[";
	$separator = "";
	for($i = 0; $i < $viewResult['num_rows']; $i++){
		foreach($viewResult['result_set'][$i] as $key => $value){
			//echo $key . "-";
			if(is_numeric($value)) {
				$valueINT = (float) $value;
				$finalResult[$i][$key] = $valueINT;
			} else {
				$finalResult[$i][$key] = $value;
			}
		}
		if(sizeof($finalResult[$i]) > 0 )
			if(strlen(json_encode($finalResult[$i])) > 0)
				$jsonData .= $separator . json_encode($finalResult[$i]);
		$separator = ","; 
	}
	$jsonData .= "]";
    //echo json_encode($jsonData);
    echo $jsonData;
    exit();
}

$lastInsertedID = 0;
if ($TemplateName !== '' && $TemplateName !== 'undefined' && $TemplateName !== 0) {	
	//if($TemplateID == 0){ //NEW template being saved for a new report
		
		$sql = "INSERT INTO kreport_template_data (TemplateName, TemplateDescription, ReportID, TemplateTypeID, UserID, ReportJson) 
										VALUES ('$TemplateName', '$TemplateDescription', '$ReportID', '$TypeID', '$UserID', '$data' )";
		$result = db::getInstanceMaster()->db_insertQuery($sql);
		$TemplateID = $lastInsertedID = $result['last_id'];
		
	/*}else{	//SAVE AS AFTER MAKING CHANGES TO A PRE-LOADED OLD TEMPLATE
	
		//INSERT a copy of existing template - Insert By Select
		$sql = "INSERT INTO kreport_template_data (TemplateName, TemplateDescription, ReportID, TemplateTypeID, UserID, ReportJson) 
                SELECT '$TemplateName', '$TemplateDescription', '$ReportID', '$TypeID', '$UserID', '$data' 
                FROM kreport_template_data WHERE ID = $TemplateID";
        $result = db::getInstanceMaster()->db_insertQuery($sql);
         //print_r($result);
        $lastInsertedID = $result['last_id'];

		//UPDATE new ReportJson in the new template saved.
		$sql = "UPDATE kreport_template_data SET ReportJson = '$data',TemplateName='$TemplateName',TemplateDescription='$TemplateDescription' WHERE ID=$lastInsertedID";
		$result = db::getInstanceMaster()->db_insertQuery($sql);
	}*/
		
}else{

    if (strlen($data) > 0) {
        // Check if there is an existing record for the ReportID
        // echo "in the else block";
        $query = "SELECT * FROM kreport_template_data WHERE ReportID = $ReportID AND ID =$TemplateID";
        $result = db::getInstanceMaster()->db_select($query);
        // print_r($result);resultArray
        if ($result['num_rows'] > 0) {
            // If record exists, update the existing entry
            // $UpdateID = $result["result_set"][0]["ID"];
            $sql = "UPDATE kreport_template_data SET ReportJson = '$data',TemplateTypeID='$TypeID' WHERE ID = $TemplateID";
            $result = db::getInstanceMaster()->db_insertQuery($sql);
        } else {
            // If record does not exist, insert a new entry
/*******************************CHECK THIS ONCE IN DEBUG MODE ************************/
            $sql = "INSERT INTO kreport_template_data (ID,TypeTemplateID, ReportID, UserID, ReportJson) VALUES ('$TemplateID','$TypeID', '$ReportID', '$UserID', '$data')";
            $result = db::getInstanceMaster()->db_insertQuery($sql);
        }
    }
}

// echo $lastInsertedID;
// Check if data is provided

// Retrieve the saved state from the database
$query = "SELECT ReportJson FROM kreport_template_data WHERE ReportID = $ReportID AND ID = $TemplateID" ;
$result = db::getInstanceMaster()->db_select($query);
// print_r($result);

// Check if there's a saved state
if ($result['num_rows'] > 0) {
    // Output the saved state
    $savedState = $result['result_set'][0]["ReportJson"];
    echo $savedState;
 
} else {
    // If no saved state found, output an empty string
    echo "";
}
?>

