Files
BE_CPONE/application/controllers/ais_130126/Packet.php
2026-04-27 10:26:26 +07:00

422 lines
14 KiB
PHP

<?php
class Packet extends MY_Controller
{
var $db_onedev;
public function index()
{
echo "Resultentry API";
}
public function __construct()
{
parent::__construct();
$this->db_onedev = $this->load->database("onedev", true);
$this->db_log = $this->load->database("log", true);
$this->load->helper(array('form', 'url'));
}
public function error_log($data, $userid = 999)
{
$sql = "INSERT INTO ais_error_log (
AisErrorLogFnName,
AisErrorLogMessage,
AisErrorLogQuery,
AisErrorLogJson,
AisErrorLogUserID,
AisErrorLogCreated
)
VALUES(
?,
?,
?,
?,
?,
NOW()
)";
$qry = $this->db_log->query($sql, array($data['fn_name'], $data['message'], $data['query'], $data['json'], $userid));
//echo $this->db_log->last_query();
return true;
}
/**
* Generic POST request function
* @param string $url API endpoint URL
* @param array $data Request payload
* @param array $headers Custom headers (optional)
* @return array Response from API
*/
public function post_request($url, $data = array(), $headers = array())
{
// Default headers
$default_headers = array(
'Content-Type: application/json'
);
// Merge custom headers with default headers
$final_headers = array_merge($default_headers, $headers);
// Initialize cURL
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $final_headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
// Execute cURL request
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
// Close cURL
curl_close($ch);
// Prepare result
$result = array(
'success' => false,
'http_code' => $http_code,
'response' => null,
'error' => null
);
if ($error) {
$result['error'] = $error;
} else {
$result = json_decode($response, true);
if ($result['status'] == 200) {
$result['success'] = true;
} else {
$result['success'] = false;
}
}
return $result;
}
public function get_request($url, $headers = array())
{
// Retrieve configuration
$config = $this->get_config();
$token = $config['AisConfigAuthToken'] ?? 'default-token';
$header_token = $config['AisConfigHeaderToken'];
// Default headers based on the curl command
$default_headers = array(
'Header-Token: ' . $header_token,
'Authorization: Bearer ' . $token
);
// Merge custom headers with default headers
$final_headers = array_merge($default_headers, $headers);
// Initialize cURL
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $final_headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// Execute cURL request
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
// Close cURL
curl_close($ch);
// Prepare result
$result = array(
'success' => false,
'http_code' => $http_code,
'response' => null,
'error' => null
);
if ($error) {
$result['error'] = $error;
} else {
$decoded = json_decode($response, true);
$result['response'] = $decoded;
// Check if response is successful based on http code
if ($http_code === 200) {
$result['success'] = true;
}
}
return $result;
}
function get_config()
{
$sql = "SELECT * FROM ais_config LIMIT 1";
$qry = $this->db_onedev->query($sql);
if (!$qry) {
$this->error_log(array('fn_name' => 'get_config', 'message' => 'ais_config select', 'query' => $this->db_onedev->last_query(), 'json' => ''), 999);
exit;
}
$dt_config = $qry->row_array();
return $dt_config;
}
/**
* POST request to auth API
* @param string $username Username for authentication
* @param string $password Password for authentication
* @return array Response from API
*/
public function post_auth()
{
$dt_config = $this->get_config();
$baseUrl = $dt_config['AisConfigBaseUrl'];
$url = $baseUrl . '/api/auth/auth.php';
$headers = array(
'Header-Token: ' . $dt_config['AisConfigHeaderToken']
);
$username = $dt_config['AisConfigUsername'];
$password = $dt_config['AisConfigPassword'];
$data = array(
'username' => $username,
'password' => $password
);
$result = $this->post_request($url, $data, $headers);
$sql = "INSERT INTO ais_login_log(
AisLoginLogUsername,
AisLoginLogPassword,
AisLoginLogHeaderToken,
AisLoginLogResult,
AisLoginLogCreated
)
VALUES(
?,
?,
?,
?,
NOW()
)";
$qry = $this->db_log->query($sql, array($username, $password, $dt_config['AisConfigHeaderToken'], json_encode($result)));
if (!$qry) {
$this->error_log(array('fn_name' => 'post_auth', 'message' => 'ais_login_log insert', 'query' => $this->db_log->last_query(), 'json' => json_encode($result)), 999);
exit;
}
//print_r($result);
//exit;
// Check if success
if (!$result['success']) {
$this->error_log(array('fn_name' => 'post_auth', 'message' => 'failed auth', 'query' => '', 'json' => json_encode($result)), 999);
$errors = array('status' => 'error', 'message' => 'Gagal Login');
echo json_encode($errors);
exit;
} else {
// Update token
$token = $result['data']['token'];
;
$sql = "UPDATE ais_config SET AisConfigAuthToken = ? WHERE AisConfigID = 1";
$qry = $this->db_onedev->query($sql, array($token));
//echo $this->db_onedev->last_query();
//exit;
if (!$qry) {
$this->error_log(array('fn_name' => 'post_auth', 'message' => 'ais_config update', 'query' => $this->db_onedev->last_query(), 'json' => ''), 999);
$errors = array('status' => 'error', 'message' => 'Gagal Update Token');
echo json_encode($errors);
exit;
}
//$success = array('status' => 'success', 'message' => 'Berhasil Login', 'token' => $token);
return $token;
}
}
/**
* POST request to jenis layanan API
* @param array $data Array of jenis layanan data
* @return array Response from API
*/
function monitoring_packet()
{
$sql_base = "SELECT
p.T_PacketID,
p.T_PacketName AS packet_name,
p.T_PacketType,
p.T_PacketPrice,
p.T_PacketSasCode AS packet_code,
p.T_PacketStartDate,
p.T_PacketEndDate,
ph.T_PriceHeaderID,
ph.T_PriceHeaderName AS priceheader_name,
ph.T_PriceHeaderCode AS priceheader_code,
ph.T_PriceHeaderStartDate,
ph.T_PriceHeaderEndDate,
ap.Ais_PacketStatus AS Ais_PacketStatus,
IF(MAX(ap.Ais_PacketID) IS NULL, 'N', 'Y') AS packet_status
FROM t_packet p
JOIN t_priceheader ph
ON ph.T_PriceHeaderID = p.T_PacketT_PriceHeaderID
LEFT JOIN ".$this->db_log->database.".ais_packet ap
ON ap.Ais_PacketT_PacketSasCode = p.T_PacketSasCode
";
// Ambil parameter
$packet_name = $this->input->get('packet_name');
$packet_code = $this->input->get('packet_code');
$priceheader_name = $this->input->get('priceheader_name');
$priceheader_code = $this->input->get('priceheader_code');
$packet_status = $this->input->get('packet_status'); // Y / N
// Pagination
$page = $this->input->get('page') ? intval($this->input->get('page')) : 1;
$limit = 10;
$offset = ($page - 1) * $limit;
$params = [];
$where_clauses = [];
// Status packet Y/N dari ais_packet
if ($packet_status === 'Y') {
$where_clauses[] = "ap.Ais_PacketID IS NOT NULL";
} elseif ($packet_status === 'N') {
$where_clauses[] = "ap.Ais_PacketID IS NULL";
}
// Filter by packet name
if ($packet_name) {
$where_clauses[] = "p.T_PacketName LIKE ?";
$params[] = "%$packet_name%";
}
// Filter by packet code
if ($packet_code) {
$where_clauses[] = "p.T_PacketSasCode LIKE ?";
$params[] = "%$packet_code%";
}
// Filter by priceheader name
if ($priceheader_name) {
$where_clauses[] = "ph.T_PriceHeaderName LIKE ?";
$params[] = "%$priceheader_name%";
}
// Filter by priceheader code
if ($priceheader_code) {
$where_clauses[] = "ph.T_PriceHeaderCode LIKE ?";
$params[] = "%$priceheader_code%";
}
// Build WHERE
$where_sql = "";
if (!empty($where_clauses)) {
$where_sql = " WHERE " . implode(" AND ", $where_clauses);
}
// Count total records for pagination
// Count distinct packet ID
$count_sql = "
SELECT COUNT(*) AS total
FROM (
SELECT p.T_PacketID
FROM t_packet p
JOIN t_priceheader ph
ON ph.T_PriceHeaderID = p.T_PacketT_PriceHeaderID
LEFT JOIN ".$this->db_log->database.".ais_packet ap
ON ap.Ais_PacketT_PacketSasCode = p.T_PacketSasCode
$where_sql
GROUP BY p.T_PacketID
) AS x
";
$qry_count = $this->db_onedev->query($count_sql, $params);
$total = $qry_count->row()->total ?? 0;
// Main SQL
$sql = $sql_base . $where_sql . "
GROUP BY p.T_PacketID
ORDER BY p.T_PacketID ASC
LIMIT $limit OFFSET $offset";
$qry = $this->db_onedev->query($sql, $params);
if (!$qry) {
echo json_encode(['status' => 'error', 'message' => 'Gagal mengambil data monitoring packet.']);
exit;
}
$data = $qry->result_array();
echo json_encode([
'status' => 'success',
'message' => 'Berhasil mengambil data monitoring packet.',
'data' => $data,
'total' => $total,
'page' => $page,
'limit' => $limit,
'total_page' => ceil($total / $limit)
]);
exit;
}
function get_json_response()
{
$packet_code = $this->input->get('packet_code');
if (empty($packet_code)) {
return $this->output
->set_status_header(400)
->set_content_type('application/json')
->set_output(json_encode([
'status' => 'error', 'message' => 'packet_code parameter is required']));
}
$sql = "SELECT
Ais_PacketT_PacketSasCode AS packet_code,
Ais_PacketLastUpdated AS packet_update,
Ais_PacketJson AS packet_json,
Ais_PacketStatus AS status,
Ais_PacketResponse AS packet_response
FROM ais_packet
WHERE Ais_PacketT_PacketSasCode = ?
ORDER BY Ais_PacketLastUpdated DESC";
// Query ke database LOG
$qry = $this->db_log->query($sql, array($packet_code));
$results = $qry->row_array();
$results = $qry->result_array();
if ($results) {
// Loop through each result to decode JSON
foreach ($results as &$result) {
$result['packet_json'] = json_decode($result['packet_json']);
$result['packet_response'] = json_decode($result['packet_response']);
}
unset($result); // Unset reference to avoid side effects
echo json_encode(['status' => 'success', 'data' => $results]);
} else {
echo json_encode(['status' => 'error', 'message' => 'Data not found for the given sas code.']);
}
exit;
}
}