nhance/app/Controllers/TicketController.php

2077 lines
87 KiB
PHP

<?php
namespace App\Controllers;
use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
use App\Models\TicketMasterModel;
use App\Models\TicketClaimStatusModel;
use App\Models\ClientModel;
use App\Models\TicketHistoryModel;
use App\Models\TicketMailTemplateModel;
use App\Models\TicketMessageModel;
use App\Models\TicketNoteModel;
use App\Models\UserModel;
use App\Models\ClientPolicyModel;
use App\Models\EmployeePolicyModel;
use DOMDocument;
use Psr\Log\LoggerInterface;
use Kint\Kint;
use App\Models\EmployeeModel;
use App\Helpers\MailHelper;
use App\Models\InsurerModel;
use CodeIgniter\API\ResponseTrait;
class TicketController extends BaseController
{
use ResponseTrait;
protected $myLogger;
public $ticketType;
public $priorityType;
public $relationshipType;
public $modeOFIntimate;
public $claimType;
public $claimStatus;
public $placeHolders;
public $extraFields;
public $nonIDReason;
protected $clientModel;
protected $ticketMasterModel;
protected $ticketHistoryModel;
protected $ticketMailTemplateModel;
protected $ticketMessageModel;
protected $ticketNoteModel;
protected $triggerType;
protected $userModel;
protected $employeeModel;
protected $clientPolicyModel;
protected $employeePolicyModel;
protected $extraFieldsDisplayForFrontend;
public function __construct()
{
$this->myLogger = \Config\Services::mylogger();
set_session_context('Ticket Master Controller');
$this->ticketMasterModel = new TicketMasterModel();
$this->ticketType = [1 => "Claim-GMC", 2 => "Claim-GPA", 3 => "EDLI", 4 => "GTLI"];
$this->priorityType = [
1 => "Low",
2 => "Medium",
3 => "High",
4 => "Urgent",
5 => "Emergency",
6 => "Critical"
];
$this->relationshipType = [
"self" => "Self",
"spouse" => "Spouse",
"son" => "Son",
"daughter" => "Daughter",
"father" => "Father",
"mother" => "Mother",
"father-in-law" => "Father-in-Law",
"mother-in-law" => "Mother-in-Law"
];
$this->modeOFIntimate = [
1 => "In Person",
2 => "Courier",
3 => "Online Mode - Email",
4 => "Smart Service Desk",
5 => "Direct to TPA"
];
$this->claimType = [
1 => [
1 => "Main Hospitalization",
3 => "Pre / Post",
2 => "OPD",
4 => "ReOpen",
],
2 => [
1 => "TTD",
2 => "PTD",
3 => "PPD",
4 => "Death",
]
];
$this->triggerType = [
1 => "Trigger 1",
2 => "Trigger 2",
3 => "Trigger 3",
4 => "Trigger 4",
5 => "Trigger 5",
6 => "Trigger 6",
7 => "Trigger 7",
8 => "Trigger 8",
];
$this->placeHolders = [
'((ACM))' => 'acm',
'((ACM_CONTACT))' => 'acm_mobile',
'((EMPLOYEE_NAME))' => 'emp_name',
'((EMPLOYEE_ID))' => 'emp_code',
'((CORPORATE_NAME))' => 'client_name',
'((INSURED_NAME))' => 'insured_name',
'((CLAIM_NO))' => 'claim_number',
'((RELATIONSHIP))' => 'relationship',
'((POLICY_TYPE))' => 'policy_type',
'((AUTO_QUERY_CONTENT))' => 'auto_query_content',
'((CLAIM_FORM_LINK))' => 'claim_form_link',
'((CLAIM_FEEDBACK_FORM))' => 'claim_feedback_form',
'((SETTLED_LETTER))' => 'settle_letter',
'((APPROVED_LETTER))' => 'approved_letter',
'((APPROVED_DESCRIBTION))' => 'approved_description',
];
$this->extraFields = [
1 => ['non_id_reason'],
10 => ['pay_initiate_date'],
3 => ['raised_date'],
4 => ['raised_date'],
5 => ['claim_number', 'registration_date'],
7 => ['query_received_date'],
8 => ['denial_reason','denial_date'],
9 => ['approved_amount','approved_date', 'approved_letter', "approved_description"],
11 => ['utr_details', 'settled_date', 'settle_letter'],
40 => ['approved_amount','approved_date', 'approved_letter', "approved_description"],
44 => ['utr_details', 'settled_date', 'settle_letter'],
30 => ['approved_amount','approved_date', 'approved_letter', "approved_description"],
34 => ['utr_details', 'settled_date', 'settle_letter'],
20 => ['approved_amount','approved_date', 'approved_letter', "approved_description"],
24 => ['utr_details', 'settled_date', 'settle_letter'],
14 => ['return_remark', 'awb_no_courier_name'],
48 => ['return_remark', 'awb_no_courier_name'],
59 => ['return_remark', 'awb_no_courier_name'],
54 => ['return_remark', 'awb_no_courier_name'],
13 => ['cancel_remark'],
47 => ['cancel_remark'],
53 => ['cancel_remark'],
58 => ['cancel_remark'],
2 => [],
6 => [],
12 => [],
15 => [],
16 => [],
17 => [],
18 => [],
19 => [],
21 => [],
22 => [],
23 => [],
25 => [],
26 => [],
27 => [],
28 => [],
29 => [],
31 => [],
32 => [],
33 => [],
35 => [],
36 => [],
37 => [],
38 => [],
39 => [],
41 => [],
42 => [],
43 => [],
45 => [],
46 => [],
49 => [],
50 => [],
51 => [],
52 => [],
55 => [],
56 => [],
57 => [],
60 => []
];
$this->extraFieldsDisplayForFrontend = [
1 => ['non_id_reason' => 'Non ID Reason'],
10 => ['pay_initiate_date' => 'Payment Initiated Date'],
3 => ['raised_date' => 'Raised Date'],
4 => ['raised_date' => 'Raised Date'],
5 => [
'claim_number' => 'Claim Number',
'registration_date' => 'Registration Date'
],
7 => ['query_received_date' => 'Query Received Date'],
8 => [
'denial_reason' => 'Denial Reason',
'denial_date' => 'Denial Date'
],
9 => [
'approved_amount' => 'Approved Amount',
'approved_date' => 'Approved Date',
'approved_letter' => 'Approved Letter',
'approved_description' => 'Approved Description'
],
11 => [
'utr_details' => 'UTR Details',
'settled_date' => 'Settled Date',
'settle_letter' => 'Settle Letter'
],
40 => [
'approved_amount' => 'Approved Amount',
'approved_date' => 'Approved Date',
'approved_letter' => 'Approved Letter',
'approved_description' => 'Approved Description'
],
44 => [
'utr_details' => 'UTR Details',
'settled_date' => 'Settled Date',
'settle_letter' => 'Settle Letter'
],
30 => [
'approved_amount' => 'Approved Amount',
'approved_date' => 'Approved Date',
'approved_letter' => 'Approved Letter',
'approved_description' => 'Approved Description'
],
34 => [
'utr_details' => 'UTR Details',
'settled_date' => 'Settled Date',
'settle_letter' => 'Settle Letter'
],
20 => [
'approved_amount' => 'Approved Amount',
'approved_date' => 'Approved Date',
'approved_letter' => 'Approved Letter',
'approved_description' => 'Approved Description'
],
24 => [
'utr_details' => 'UTR Details',
'settled_date' => 'Settled Date',
'settle_letter' => 'Settle Letter'
],
14 => [
'return_remark' => 'Return Remark',
'awb_no_courier_name' => 'AWB No Courier Name'
],
48 => [
'return_remark' => 'Return Remark',
'awb_no_courier_name' => 'AWB No Courier Name'
],
59 => [
'return_remark' => 'Return Remark',
'awb_no_courier_name' => 'AWB No Courier Name'
],
54 => [
'return_remark' => 'Return Remark',
'awb_no_courier_name' => 'AWB No Courier Name'
],
13 => ['cancel_remark' => 'Cancel Remark'],
47 => ['cancel_remark' => 'Cancel Remark'],
53 => ['cancel_remark' => 'Cancel Remark'],
58 => ['cancel_remark' => 'Cancel Remark']
];
$this->nonIDReason = [
"Newborn Baby" => "Newborn Baby",
"Newly Wedded Spouse" => "Newly Wedded Spouse",
"Policy Pending" => "Policy Pending",
"New Joinee" => "New Joinee",
"Exceptional Case" => "Exceptional Case"
];
$this->ticketMasterModel = new TicketMasterModel();
$this->claimStatus = new TicketClaimStatusModel();
$this->clientModel = new ClientModel();
$this->ticketHistoryModel = new TicketHistoryModel();
$this->ticketMailTemplateModel = new TicketMailTemplateModel();
$this->ticketNoteModel = new TicketNoteModel();
$this->ticketMessageModel = new TicketMessageModel();
$this->userModel = new UserModel();
$this->employeeModel = new EmployeeModel();
$this->clientPolicyModel = new ClientPolicyModel();
$this->employeePolicyModel = new EmployeePolicyModel();
}
public function ticketList()
{
$data['ticket_type'] = $this->ticketType;
$data['modeOFIntimate'] = $this->modeOFIntimate;
$data['priorityType'] = $this->priorityType;
$data['claimType'] = $this->claimType;
if ($this->request->is('get')) {
$data['page_name'] = "Claims";
$data['claim_status'] = $this->claimStatus->select('id,ticket_type,claim_status')->where('is_active', 1)->findAll();
$data['client_list'] = $this->clientModel->select('id,client_name')->where('is_active', 1)->findAll();
$data['ticket_data'] = $this->ticketSearch(1);
return $this->loadLayout('ticket_search', $data);
} else {
$isFromDashboard = $this->request->getPost("is_dashboard");
log_message('error', 'Is From Dashboard: ' . $isFromDashboard);
if (isset($isFromDashboard) && !empty($isFromDashboard)){
$data['page_name'] = "Claims";
if ($isFromDashboard == 1) {
$data['ticket_data'] = $this->ticketSearch(3);
}else if ($isFromDashboard == 2){
$data['ticket_data'] = $this->ticketSearch(4);
}else if ($isFromDashboard == 3){
$data['ticket_data'] = $this->ticketSearch(2);
}else if ($isFromDashboard == 4){
$data['ticket_data'] = $this->ticketSearch(5);
}
$data['claim_status'] = $this->claimStatus->select('id,ticket_type,claim_status')->where('is_active', 1)->findAll();
$data['client_list'] = $this->clientModel->select('id,client_name')->where('is_active', 1)->findAll();
// dd($data);
return $this->loadLayout('ticket_search', $data);
}
else{
$data['ticket_data'] = $this->ticketSearch();
$html = view('ticket_list', $data);
return $this->respond(['status' => true, 'html' => $html], 200);
}
}
}
public function ticketSearch($action = null)
{
$db = db_connect();
// log_message('error', 'Ticket Search Action: ' . $action);
$subquery = $db->table('ticket_master tm')
->select([
'tm.id AS ticket_id',
"CASE
WHEN DATEDIFF(
CURDATE(),
COALESCE(latest_history.created_at, tm.created_at)
) BETWEEN 0 AND 6 THEN '0-6 Days'
WHEN DATEDIFF(
CURDATE(),
COALESCE(latest_history.created_at, tm.created_at)
) BETWEEN 7 AND 12 THEN '7-12 Days'
WHEN DATEDIFF(
CURDATE(),
COALESCE(latest_history.created_at, tm.created_at)
) BETWEEN 13 AND 20 THEN '13-20 Days'
ELSE 'Above 20 Days'
END AS tat"
])
->join(
'(SELECT th.ticket_id, MAX(th.created_at) AS created_at
FROM ticket_history th
WHERE th.field_name = "claim_status_id"
GROUP BY th.ticket_id) AS latest_history',
'latest_history.ticket_id = tm.id',
'left'
)
->where('tm.is_active', 1)
->groupBy('tm.id, tm.created_at, latest_history.created_at');
//action 1 get last 100 rows, action 2 filter and get all rows related to that, action 3 gets according to dashboard, action 4 gets according to ACM, action 5 tat
if ($action == 1) {
$query = $db->table('ticket_master tm')
->select([
'tm.id',
'tm.ticket_type_id',
'tm.claim_status_id',
'tm.is_head_approved',
'tcs.claim_status AS status',
'tm.claim_number AS claim_no',
'tm.tpa_id',
'tm.tpa_no',
'tm.emp_name',
'tm.emp_code',
'tm.relationship',
'i.name AS insurer_name',
'c.client_name',
'tm.insured_name',
'c.short_name',
'DATE_FORMAT(tm.created_at, "%d-%m-%Y") AS ticket_created_date',
'COALESCE(tat_category.tat, "0-6 Days") AS tat',
'tm.claim_status_id',
'(SELECT first_name FROM user_profiles WHERE user_profiles.id = tm.acm_id) AS acm_name',
'(SELECT name FROM insurers WHERE insurers.id = tm.insurer_id) AS insurer_name',
'(SELECT name FROM tpa WHERE tpa.id = tm.tpa_id) AS tpa_name',
'tm.acm_id',
'tm.insurer_id',
'tm.tpa_id',
'tm.client_policy_id',
'tm.policy_no',
'tm.priority',
'tm.relationship',
'tm.emp_mobile',
'tm.emp_mail',
'tm.emp_personal_mail',
'tm.mode_of_intimation',
'tm.claim_type',
'tm.hospital_name',
'tm.doa',
'tm.dod',
'tm.claim_amount',
'tm.pod_no',
'tm.date_of_join',
'tm.date_of_incep',
'tm.dob',
'tm.date_of_accident',
'tm.date_of_death',
'tm.date_of_intimat',
'tm.si_amt',
'tm.raised_date',
'tm.registration_date',
'tm.query_received_date',
'tm.denial_date',
'tm.approved_date',
'tm.settled_date',
'tm.denial_reason',
'tm.approved_letter',
'tm.approved_amount',
'tm.utr_details',
'tm.settle_letter',
'tm.return_remark',
'tm.cancel_remark',
'tm.awb_no_courier_name',
'tm.non_id_reason',
'tm.pay_initiate_date',
'tm.approved_description'
])
->join('insurers i', 'i.id = tm.insurer_id AND i.is_active = 1', 'left')
->join('clients c', 'c.id = tm.client_id AND c.is_active = 1', 'left')
->join('ticket_claim_status tcs', 'tcs.id = tm.claim_status_id AND tcs.is_active = 1', 'left')
->join("({$subquery->getCompiledSelect()}) tat_category", 'tm.id = tat_category.ticket_id', 'left')
->where('tm.is_active', 1)
->orderBy('tm.id', 'DESC');
$data = $query->get()->getResultArray();
// dd(db_connect()->getLastQuery());
return $data;
} else if ($action == 3) {
$ids = $this->request->getPost('ids');
$ids = array_filter(explode(',', $ids));
if (!empty($ids)) {
$idsStr = implode(',', array_map('intval', $ids)); // sanitize IDs to be integers
$where = "tm.id IN ($idsStr)";
} else {
$where = '1 = 0'; // No valid IDs, return empty result
}
// dd($where);
} else if ($action == 4){
$acm_id = $this->request->getPost('ids');
// dd($acm_id);
if (!empty($acm_id)) {
$where = "tm.acm_id = $acm_id";
} else {
$where = '1 = 0'; // No valid IDs, return empty result
}
}else if ($action == 5) {
$search_data = $this->request->getPost();
$where = "tm.created_at >= '" . $search_data['from_date'] . "' AND tm.created_at <= '" . $search_data['to_date'] . "'" ."and ticket_type_id = ".$search_data['ticket_type_id'];
} else {
$search_data = $this->request->getPost();
// print_r($search_data); die()
$where = [];
foreach ($search_data as $search_objects => $key) {
if ($key != null && $key != '' && $key != 0 && $search_objects != 'is_dashboard') {
$where[$search_objects] = $key;
}
}
// print_rr($where);
}
$query = $db->table('ticket_master tm')
->select([
'tm.id',
'tm.ticket_type_id',
'tcs.claim_status AS status',
'tm.claim_number AS claim_no',
'tm.claim_status_id',
'tm.is_head_approved',
'tm.tpa_id',
'tm.tpa_no',
'tm.emp_name',
'tm.emp_code',
'tm.relationship',
'i.name AS insurer_name',
'c.client_name',
'tm.insured_name',
'c.short_name',
'DATE_FORMAT(tm.created_at, "%d-%m-%Y") AS ticket_created_date',
'COALESCE(tat_category.tat, "0-6 Days") AS tat',
'(SELECT first_name FROM user_profiles WHERE user_profiles.id = tm.acm_id) AS acm_name',
'(SELECT name FROM insurers WHERE insurers.id = tm.insurer_id) AS insurer_name',
'(SELECT name FROM tpa WHERE tpa.id = tm.tpa_id) AS tpa_name',
'tm.claim_status_id',
'tm.acm_id',
'tm.insurer_id',
'tm.tpa_id',
'tm.client_policy_id',
'tm.policy_no',
'tm.priority',
'tm.relationship',
'tm.emp_mobile',
'tm.emp_mail',
'tm.emp_personal_mail',
'tm.mode_of_intimation',
'tm.claim_type',
'tm.hospital_name',
'tm.doa',
'tm.dod',
'tm.claim_amount',
'tm.pod_no',
'tm.date_of_join',
'tm.date_of_incep',
'tm.dob',
'tm.date_of_accident',
'tm.date_of_death',
'tm.date_of_intimat',
'tm.si_amt',
'tm.raised_date',
'tm.registration_date',
'tm.query_received_date',
'tm.denial_date',
'tm.approved_date',
'tm.settled_date',
'tm.denial_reason',
'tm.approved_letter',
'tm.approved_amount',
'tm.utr_details',
'tm.settle_letter',
'tm.return_remark',
'tm.cancel_remark',
'tm.awb_no_courier_name',
'tm.non_id_reason',
'tm.pay_initiate_date',
'tm.approved_description'
])
->join('insurers i', 'i.id = tm.insurer_id AND i.is_active = 1', 'left')
->join('clients c', 'c.id = tm.client_id AND c.is_active = 1', 'left')
->join('ticket_claim_status tcs', 'tcs.id = tm.claim_status_id AND tcs.is_active = 1', 'left')
->join("({$subquery->getCompiledSelect()}) tat_category", 'tm.id = tat_category.ticket_id', 'left')
->where('tm.is_active', 1)
->where($where)
->orderBy('tm.id', 'DESC');
$data = $query->get()->getResultArray();
// dd($db->getLastQuery()->getQuery());
// dd($data);
if ($action == 5){
$tat = $this->request->getPost("tat_category");
$data = array_values(array_filter($data, function($dat) use ($tat) {
return $dat['tat'] == $tat;
}));
}
// print_rr($data);
// log_message('error',' Claims Master Data '.json_encode($data));die();
// print_rr($data);die();
return $data;
}
public function ticket_form($ticket_type)
{
$data = $this->ticket_form_data($ticket_type);
// dd($data);
return $this->loadLayout('ticket_form_handler', $data);
}
public function ticket_form_data($ticket_type, $claim_status_id = null)
{
$this->myLogger->logme('error', "Fetching ticket form data for Ticket Type: $ticket_type");
$data = [
'ticket_form' => 1,
'selected_ticket_type' => $ticket_type,
'ticket_type' => $this->ticketType,
'priorityType' => $this->priorityType,
'relationshipType' => $this->relationshipType,
'modeOFIntimate' => $this->modeOFIntimate,
'nonIDReason' => $this->nonIDReason
];
switch ($ticket_type) {
case 2:
$data['ticket_form'] = 'GPA';
break;
case 3:
$data['ticket_form'] = 'EDLI';
break;
case 4:
$data['ticket_form'] = 'GTLI';
break;
}
// Fetch ACM Users
$db = db_connect();
$data['acms'] = $db->table('user_profiles')
->select('id, first_name')
->where(['is_active' => 1, 'role' => 3])
->get()
->getResultArray();
// Fetch Claim Status
if(empty($claim_status_id)){
if($ticket_type == 2){
$claim_status_id = 15;
}else if($ticket_type == 3){
$claim_status_id = 25;
}else if($ticket_type == 4){
$claim_status_id = 35;
}else{
$claim_status_id = 1;
}
}
$data['claim_status'] = $this->transFormClaimStatus($claim_status_id, $ticket_type);
$data['extra_fields'] = $this->getExtraFields($data['claim_status']);
$data['extra_fields_array_for_validate'] = $this->getExtraFields($data['claim_status'], 1);
if ($ticket_type == 1) {
$data['claim_type'] = $this->claimType[1];
} else {
$data['claim_type'] = $this->claimType[2];
}
$this->myLogger->logme('error', "Ticket form data fetched successfully for Ticket Type: $ticket_type");
return $data;
}
//transform the claim status
public function transFormClaimStatus($claimStatusId, $ticket_type)
{
// Fetch the main claim status by ID
$claimStatusData = $this->claimStatus
->select('*')
->where(['is_active' => 1, 'ticket_type' => $ticket_type])
->where('id', $claimStatusId)
->first();
// dd($claimStatusData);
// Initialize the filtered claim status array
$filteredClaimStatus = [];
if (!empty($claimStatusData)) {
// Add the main claim status to the result
$filteredClaimStatus[] = $claimStatusData;
// Decode the allowed_status JSON field
$filterClaimStatusIds = json_decode($claimStatusData['allowed_status'], true);
// Fetch additional claim statuses if IDs exist
if (!empty($filterClaimStatusIds) && is_array($filterClaimStatusIds)) {
$additionalClaimStatuses = $this->claimStatus
->select('*')
->where(['is_active' => 1, 'ticket_type' => $ticket_type])
->whereIn('id', $filterClaimStatusIds)
->get()
->getResultArray();
// Merge additional claim statuses into the result
$filteredClaimStatus = array_merge($filteredClaimStatus, $additionalClaimStatuses);
}
}
return $filteredClaimStatus;
}
public function getExtraFields(array $claimStatus, $nonFilterArray = 0): array
{
$extra_fields = [];
if($nonFilterArray == 1){
foreach ($claimStatus as $value) {
if (isset($this->extraFields[$value['id']])) {
if (!isset($extra_fields[$value['id']])) {
$extra_fields[$value['id']] = [];
}
$extra_fields[$value['id']] = array_merge($extra_fields[$value['id']], $this->extraFields[$value['id']]);
}
}
}else{
foreach ($claimStatus as $value) {
if (isset($this->extraFields[$value['id']])) {
$extra_fields[] = $this->extraFields[$value['id']];
}
}
$extra_fields = array_values(array_unique(array_merge(...$extra_fields)));
}
return $extra_fields;
}
public function view_ticket($ticket_id)
{
// $ticket_data = $this->ticketMasterModel->where('id', $ticket_id)->where('is_active', 1)->first();
$ticket_data = $this->ticketMasterModel->getTicketDataByTicketID($ticket_id);
$ticket_data = $this->formatDateForClaim($ticket_data, 'd/m/Y');
if (in_array($ticket_data['claim_status_id'], [15, 25, 35])) {
$ticket_data['auto_query_content'] = $this->getCheckListAndConvertArrayToString($ticket_data);
}
// dd($ticket_data);
$template_data = $this->ticketMasterModel->getTemplateDataByTicketID($ticket_id);
if (!empty($template_data)) {
$template_data['mail_content'] = $this->replacePlaceholders($template_data['mail_content'], $ticket_data);
$template_data['subject'] = $this->replacePlaceholders($template_data['subject'], $ticket_data);
}
$data = $this->ticket_form_data($ticket_data['ticket_type_id'], $ticket_data['claim_status_id']);
$data['reply_data'] = $template_data;
$data['placeHolders'] = $this->placeHolders;
$data['message_data'] = $this->getTicketMessage($ticket_id);
$data['view_ticket_page'] = [];
if($ticket_data['ticket_type_id'] == 1){
$data['member_data'] = $this->employeeModel->getEmployeeByEmployeeCode($ticket_data['emp_code']);
}else{
$data['member_data'] = array_filter(
$this->employeeModel->getEmployeeByEmployeeCode($ticket_data['emp_code']),
function ($member) {
return isset($member['emp_relationship']) && $member['emp_relationship'] == 'Self';
}
);
}
$data['ticket_history'] = $this->ticketHistory($ticket_id);
$data['ticket_check_list'] = db_connect()->table('ticket_check_list')->where('is_active', 1)->where('ticket_type_id', $ticket_data['ticket_type_id'])->get()->getResultArray();
if (!empty($ticket_data['client_policy_id'])){
$ticket_data['client_policy_id_text'] = $this->clientPolicyModel->select('concat(policy_type.policy_type,"-",client_policy.policy_no) as client_policy_name')->join('policy_type','policy_type.id = client_policy.policy_type_id and policy_type.is_active = 1')->where('client_policy.id',$ticket_data['client_policy_id'])->first()['client_policy_name'];
}
// dd($data);
$data['ticket_data'] = $ticket_data;
$data['acms'] = $this->employeeModel->getAcmUsingClientID($ticket_data['client_id']);
// dd($data);
return $this->loadLayout('ticket_edit_onbording', $data);
}
public function formatDateForClaim($ticket_data, $out_put_format = 'Y-m-d')
{
if (empty($ticket_data['doa'])) {
$ticket_data['doa'] = null;
} else {
$ticket_data['doa'] = change_date_format($ticket_data['doa'], null, $out_put_format);
}
if (empty($ticket_data['dod'])) {
$ticket_data['dod'] = null;
} else {
$ticket_data['dod'] = change_date_format($ticket_data['dod'], null, $out_put_format);
}
if (empty($ticket_data['dob'])) {
$ticket_data['dob'] = null;
} else {
$ticket_data['dob'] = change_date_format($ticket_data['dob'], null, $out_put_format);
}
if (empty($ticket_data['date_of_join'])) {
$ticket_data['date_of_join'] = null;
} else {
$ticket_data['date_of_join'] = change_date_format($ticket_data['date_of_join'], null, $out_put_format);
}
if (empty($ticket_data['date_of_incep'])) {
$ticket_data['date_of_incep'] = null;
} else {
$ticket_data['date_of_incep'] = change_date_format($ticket_data['date_of_incep'], null, $out_put_format);
}
if (empty($ticket_data['date_of_accident'])) {
$ticket_data['date_of_accident'] = null;
} else {
$ticket_data['date_of_accident'] = change_date_format($ticket_data['date_of_accident'], null, $out_put_format);
}
if (empty($ticket_data['date_of_death'])) {
$ticket_data['date_of_death'] = null;
} else {
$ticket_data['date_of_death'] = change_date_format($ticket_data['date_of_death'], null, $out_put_format);
}
if (empty($ticket_data['date_of_intimat'])) {
$ticket_data['date_of_intimat'] = null;
} else {
$ticket_data['date_of_intimat'] = change_date_format($ticket_data['date_of_intimat'], null, $out_put_format);
}
if (empty($ticket_data['raised_date'])) {
$ticket_data['raised_date'] = null;
} else {
$ticket_data['raised_date'] = change_date_format($ticket_data['raised_date'], null, $out_put_format);
}
if (empty($ticket_data['registration_date'])) {
$ticket_data['registration_date'] = null;
} else {
$ticket_data['registration_date'] = change_date_format($ticket_data['registration_date'], null, $out_put_format);
}
if (empty($ticket_data['query_received_date'])) {
$ticket_data['query_received_date'] = null;
} else {
$ticket_data['query_received_date'] = change_date_format($ticket_data['query_received_date'], null, $out_put_format);
}
if (empty($ticket_data['denial_date'])) {
$ticket_data['denial_date'] = null;
} else {
$ticket_data['denial_date'] = change_date_format($ticket_data['denial_date'], null, $out_put_format);
}
if (empty($ticket_data['approved_date'])) {
$ticket_data['approved_date'] = null;
} else {
$ticket_data['approved_date'] = change_date_format($ticket_data['approved_date'], null, $out_put_format);
}
if (empty($ticket_data['settled_date'])) {
$ticket_data['settled_date'] = null;
} else {
$ticket_data['settled_date'] = change_date_format($ticket_data['settled_date'], null, $out_put_format);
}
if (empty($ticket_data['pay_initiate_date'])) {
$ticket_data['pay_initiate_date'] = null;
} else {
$ticket_data['pay_initiate_date'] = change_date_format($ticket_data['pay_initiate_date'], null, $out_put_format);
}
return $ticket_data;
}
public function createTicket()
{
$ticket_data = $this->request->getPost();
$ticket_data = $this->formatDateForClaim($ticket_data);
// $ticket_data = $this->getLastMatchedStatus($ticket_data, );
// print_rr($ticket_data); die;
if ($ticket_data) {
$return_value = $this->ticketMasterModel->insert($ticket_data);
if ($return_value) {
//mail trigger part
$this->putHistoryAfterInsert($ticket_data, $return_value);
$mail_responce = $this->sendAutoMailTrigger($return_value);
$this->autoMessageInsertBasedOnMailResponse($mail_responce, $return_value);
return $this->respond(['status' => true, 'ticket_id' => $return_value, 'code' => 200, 'data' => $ticket_data, "message" => "Claim created successfully", 'mail_responce' => $mail_responce], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to create claim'], 200);
}
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'claim data not found'], 200);
}
}
public function updateTicket()
{
$ticket_id = $this->request->getPost('ticket_master_id');
$ticket_data = $this->request->getPost();
$ticket_data = $this->formatDateForClaim($ticket_data);
$old_ticket_data = $this->ticketMasterModel->where('id', $ticket_id)->where('is_active', 1)->first();
$ticket_data['claim_status_id'] = $this->getLastMatchedStatus($ticket_data, $old_ticket_data);
// print_rr($ticket_data); die;
if ($ticket_data) {
$return_value = $this->ticketMasterModel->where('id', $ticket_id)->set($ticket_data)->update();
if ($return_value) {
$mail_responce = null;
if($old_ticket_data['claim_status_id'] != $ticket_data['claim_status_id']){
//mail trigger part
$mail_responce = $this->sendAutoMailTrigger($ticket_id);
$this->autoMessageInsertBasedOnMailResponse($mail_responce, $ticket_id);
}
//send mail to the head for rejected ticket approvel
if($ticket_data['claim_status_id'] == 8 && $ticket_data['is_head_approved'] == 0){
$this->sendMailToTheHead($ticket_data);
}else{
$this->myLogger->logme('error', "Head Mail can't be sent");
$this->myLogger->logme('error', "CLAIM STATUS ID : {data}", ['data' => $ticket_data['claim_status_id']]);
$this->myLogger->logme('error', "IS HEAD APPROVED : {data}", ['data' => $ticket_data['is_head_approved']]);
}
return $this->respond(['status' => true, 'code' => 200, 'data' => $ticket_data, "message" => "Claim updated successfully", 'mail_responce' => $mail_responce], 200);
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to update claim'], 200);
}
} else {
return $this->respond(['status' => false, 'code' => 404, 'message' => 'claim data not found'], 200);
}
}
public function mailTemplate()
{
$data = [];
$data['trigger_type'] = $this->triggerType;
$data['policy_type'] = $this->ticketType;
$data['placeHolders'] = $this->placeHolders;
$data['ticket_data'] = $this->ticketMailTemplateModel->where('is_active', 1)->findAll();
foreach ($data['ticket_data'] as $key => $ticket_data) {
$tooltip_array = $this->claimStatus->select('claim_status')->where('ticket_type',$data['ticket_data'][$key]['ticket_type'])->where('trigger_type',$data['ticket_data'][$key]['trigger_type'])->where('is_active',1)->first();
if (isset($tooltip_array) && $tooltip_array != null){
$data['ticket_data'][$key]['tool_tip'] = $tooltip_array['claim_status'];
}else{
$data['ticket_data'][$key]['tool_tip'] =$data['ticket_data'][$key]['template_name'];
}
}
// dd($data['ticket_data']);
$data['ticket_type'] = $this->ticketType;
$data['trigger_type'] = $this->triggerType;
return $this->loadLayout('ticket_mail_template', $data);
}
public function crudTemplate($action)
{
//action 1 is create. action 2 is edit and action 3 is delete
if ($action == 1) {
$received_data = $this->request->getPost();
if (isset($received_data['id']) && $received_data['id'] != '') {
$status = $this->ticketMailTemplateModel->save($received_data);
if ($status) {
return $this->respond(['status' => true], 200);
} else {
return $this->respond(['status' => false], 200);
}
} else {
$status = $this->ticketMailTemplateModel->save($received_data);
if ($status) {
return $this->respond(['status' => true], 200);
} else {
return $this->respond(['status' => false], 200);
}
}
} elseif ($action == 2) {
$table_id = (int)$this->request->getPost('id');
$data = $this->ticketMailTemplateModel->where('id', $table_id)->where('is_active', 1)->first();
if ($data && isset($data['ticket_type']) && isset($data['trigger_type'])) {
$tooltip_array = $this->claimStatus->select('claim_status')
->where('ticket_type', $data['ticket_type'])
->where('trigger_type', $data['trigger_type'])
->where('is_active', 1)
->first();
$data['tool_tip'] = (isset($tooltip_array['claim_status']))
? $tooltip_array['claim_status']
: $data['template_name'];
} else {
// Handle case where $data is null or missing required fields
$data = $data ?: []; // Ensure $data is an array if null
$data['tool_tip'] = $data['template_name'];
}
if ($data) {
return $this->respond(['status' => true, 'data' => $data], 200);
} else {
return $this->respond(['status' => false], 404);
}
} elseif ($action == 3) {
$table_id = (int)$this->request->getPost('id');
$sql = "update ticket_mail_template set is_active = 0 where id = $table_id ";
$status = $this->ticketMailTemplateModel->query($sql);
if ($status) {
return $this->respond(['status' => true], 200);
} else {
return $this->respond(['status' => false], 404);
}
}
}
public function crudNote($action)
{
// action = 1 is read, action 2 is insert/update
if ($action == 1) {
$ticket_master_id = $this->request->getPost('id');
$is_auto_query = $this->request->getPost('is_auto_query');
// print_rr($is_auto_query);
if (isset($ticket_master_id) && $ticket_master_id != '') {
$data = $this->ticketNoteModel->where('is_active', 1)->where('ticket_id', $ticket_master_id)->where('is_auto_query', $is_auto_query)->first();
if ($data) {
return $this->respond(['status' => true, 'data' => $data], 200);
} else {
return $this->respond(['status' => false], 200);
}
}
} elseif ($action == 2) {
$data = $this->request->getPost();
// if (isset($data['id']) && $data['id'] != ''){
// print_rr($data);die();
$status = $this->ticketNoteModel->save($data);
$id = isset($data['id']) ? $data['id'] : $this->ticketNoteModel->insertID();
// }
if ($status) {
return $this->respond(['status' => true, 'id' => $id], 200);
} else {
return $this->respond(['status' => false], 200);
}
}
}
public function saveReply()
{
$received_data = $this->request->getPost();
// print_r($received_data); die;
$received_data['sender'] = 'staff';
$status = $this->ticketMessageModel->insert($received_data);
if ($status) {
$return = $this->sendReplyMessage($received_data);
return $this->respond(['status' => true, 'code' => 200, 'return' => $return], 200);
} else {
return $this->respond(['status' => false, 'code' => 404], 404);
}
}
public function getTicketMessage($ticket_master_id)
{
// log_message('error','Function called');die();
// $ticket_master_id = $this->request->getPost('id');
$dataToSend = [];
$user_id = get_session_userid();
// $logged_user = $this->userModel->select('first_name,last_name,profile')->where('id', $user_id)->first();
// $dataToSend['user_name'] = $logged_user['first_name'] . ' ' . $logged_user['last_name'];
$dataToSend['messages'] = $this->ticketMessageModel
->select('ticket_messages.*,up.first_name as user_name')
->join('user_profiles up', 'up.id = ticket_messages.created_by', 'left')
->where('ticket_messages.is_active', 1)
->where('ticket_messages.ticket_id', $ticket_master_id)
->orderBy('ticket_messages.created_at', 'DESC')
->findAll();
foreach ($dataToSend['messages'] as $message) {
$mail_content_converted = $this->convertHtmlToText($message['mail_content']);
$message['mail_content'] = $mail_content_converted;
}
$dataToSend['emp_name'] = $this->ticketMasterModel->select('emp_name')
->where('id', $ticket_master_id)->where('is_active', 1)
->first()['emp_name'];
// dd($dataToSend);
if ($dataToSend) {
return $dataToSend;
} else {
$data = [];
return $data;
}
}
public function convertHtmlToText($html)
{
if(!empty($html)){
$dom = new DOMDocument();
@$dom->loadHTML($html);
return strip_tags($dom->saveHTML());
}else{
return '';
}
}
public function removeTicket()
{
$ticket_id = $this->request->getGet('ticket_id');
if(!empty($ticket_id)){
$data['is_active'] = 0;
$this->ticketMasterModel->where('id', $ticket_id)->set($data)->update();
return $this->respond(['status' => true, 'code' => 200, 'message' => 'Claim removed successfully'], 200);
}else{
return $this->respond(['status' => false, 'code' => 404, 'message' => 'Failed to remove Claim'], 200);
}
}
//---- Email Trigger Part----------------------------------------------------------------------------------------------
public function constructMailContent($ticket_id)
{
$this->myLogger->logme('error', "Constructing mail content for Ticket ID: $ticket_id");
try {
// Fetch Ticket Data
$ticket_data = $this->ticketMasterModel->getTicketDataByTicketID($ticket_id);
// print_r($ticket_data); die;
if (!$ticket_data) {
$this->myLogger->logme('error', "No ticket data found for Ticket ID: $ticket_id");
return null;
}
$this->myLogger->logme('error', "Fetched ticket data: " . json_encode($ticket_data));
// Fetch Email Template Data
$template_data = $this->ticketMasterModel->getTemplateDataByTicketID($ticket_id);
// print_r($template_data); die;
if (!$template_data) {
$this->myLogger->logme('error', "No email template found for Claim Status ID: " . $ticket_data['claim_status_id']);
return null;
}
if (in_array($ticket_data['claim_status_id'], [15, 25, 35])) {
$ticket_data['auto_query_content'] = $this->getCheckListAndConvertArrayToString($ticket_data);
}
// print_r($ticket_data); die;
$this->myLogger->logme('error', "Fetched email template: " . json_encode($template_data));
// Generate Email Content
$subject = $this->replacePlaceholders($template_data['subject'], $ticket_data);
$message = $this->replacePlaceholders($template_data['mail_content'], $ticket_data);
// print_r($subject);
// print_r($message);
// die;
// Validate Essential Fields
if (empty($ticket_data['emp_mail'])) {
$this->myLogger->logme('error', "Employee email is missing for Ticket ID : '" . $ticket_id . "'");
return null;
}
if (empty($subject) || empty($message)) {
$this->myLogger->logme('error', "Generated email content is empty for Ticket ID: '" . $ticket_id . "'");
return null;
}
// Construct Mail Data
$mailData = [
'mail' => [$ticket_data['emp_mail'], $ticket_data['emp_personal_mail'] ?? ""],
'subject' => $subject,
'message' => $message,
'cc' => $ticket_data['common_mails'] ?? '',
'attachments' => []
];
// // if the employee personal mail is not empty then send the mail to the employee personal mail
// if(!empty($ticket_data['emp_personal_mail'])){
// $mailData[] = [
// 'mail' => [$ticket_data['emp_mail'], $ticket_data['emp_personal_mail'] ?? ""],
// 'subject' => $subject,
// 'message' => $message,
// 'cc' => $ticket_data['common_mails'] ?? '',
// 'attachments' => []
// ];
// }
// print_r($mailData); die;
$this->myLogger->logme('error', "Final Email Data");
return $mailData;
} catch (\Exception $e) {
$this->myLogger->logme('error', "Exception in constructMailContent: " . $e->getMessage());
return null;
}
}
public function replacePlaceholders($content, $ticket_data)
{
$this->myLogger->logme('error', "Replacing placeholders in content");
if (!empty($ticket_data) && !empty($content)) {
// print_rr($ticket_data);die();
if (!isset($ticket_data['id'])) { $ticket_data['id'] = $ticket_data['ticket_master_id'];}
if (!isset($ticket_data['ticket_master_id'])) {$ticket_data['ticket_master_id'] = $ticket_data['id'];}
foreach ($this->placeHolders as $key => $value) {
if ($value == "emp_code") {
$replaceData = $ticket_data[$value] ?? '';
} else if ($value == "policy_type") {
$replaceData = str_replace("Claim-", "", $this->ticketType[$ticket_data['ticket_type_id']] ?? "");
} else if ($value == "claim_form_link"){
$replaceData = '<a href="' . base_url('claim-form-download/' . md5($ticket_data['insurer_id'])) . '" target="_blank">Click here to download Claim Form</a>';
} else if ($value == "claim_feedback_form" && $ticket_data['ticket_type_id'] == 1){
$replaceData = '<a href="' . base_url('claims-feedback-form/' . md5($ticket_data['id'])) . '" target="_blank">Click to open Claim Feedback Form</a>';
} else if ($value == "settle_letter"){
$replaceData = '<a href="' . $ticket_data['settle_letter'] . '" target="_blank"> View Settlement Letter </a>';
}else if ($value == "approved_letter"){
$replaceData = '<a href="' . $ticket_data['approved_letter'] . '" target="_blank"> View Approved Letter </a>';
}else {
$replaceData = isset($ticket_data[$value]) ? $ticket_data[$value] : '';
}
$content = str_replace($key, $replaceData, $content);
}
}
$this->myLogger->logme('error', "Final content after placeholder replacement");
return $content;
}
//mail send function
public function sendTrigger($mail_content)
{
$this->myLogger->logme('error', "Sending email with content");
if (!empty($mail_content)) {
$mail_content['from_mail'] = "claims@nhanceindia.in";
$response = MailHelper::send_email($mail_content);
} else {
$response = ['status' => false, 'code' => 404, 'message' => "Mail not sent, mail data empty"];
$this->myLogger->logme('error', "Mail not sent, mail data empty");
}
$this->myLogger->logme('error', "Email sent response: " . json_encode($response));
return $response;
}
//reply mail part
public function sendReplyMessage($mail_data)
{
$this->myLogger->logme('error', "Preparing reply email for Ticket ID: " . $mail_data['ticket_id']);
$acm_mails = $this->ticketMasterModel->getTicketDataByTicketID($mail_data['ticket_id']);
if (!$acm_mails) {
$this->myLogger->logme('error', "No ACM mails found for Ticket ID: " . $mail_data['ticket_id']);
$this->myLogger->logme('error', "Reply mail not send");
return false;
}
$ticket_data = $this->ticketMasterModel->getTicketDataByTicketID($mail_data['ticket_id']);
// print_rr($ticket_data);die();
if (!$ticket_data) {
$this->myLogger->logme('error', "No ticket data found for Ticket ID : " . $mail_data['ticket_id']);
$this->myLogger->logme('error', "Reply mail not send");
return null;
}
if (!empty($mail_data)) {
$mail_data['mail_content'] = $this->replacePlaceholders($mail_data['mail_content'], $ticket_data);
$mail_data['mail_subject'] = $this->replacePlaceholders($mail_data['mail_subject'], $ticket_data);
}
$this->myLogger->logme('error', "Fetched ACM emails");
// if(!empty($ticket_data['emp_personal_mail'])){
// $this->myLogger->logme('error', "Send employee personal mail start");
// $emailPersonalData = [
// 'mail' => $ticket_data['emp_personal_mail'],
// 'subject' => $mail_data['mail_subject'],
// 'message' => $mail_data['mail_content'],
// 'common' => [],
// 'cc' => $acm_mails['common_mails'],
// 'attachments' => []
// ];
// $this->sendTrigger($emailPersonalData);
// $this->myLogger->logme('error', "Send employee personal mail successfully");
// }else{
// $this->myLogger->logme('error', "Send employee personal mail is empty");
// }
$emailData = [
'mail' => [$mail_data['emp_mail'], $ticket_data['emp_personal_mail'] ?? ""],
'subject' => $mail_data['mail_subject'],
'message' => $mail_data['mail_content'],
'common' => [],
'cc' => $acm_mails['common_mails'],
'attachments' => []
];
$this->myLogger->logme('error', "Final Reply Email Data");
return $this->sendTrigger($emailData);
}
//auto mail part
public function sendAutoMailTrigger($ticket_id)
{
$auto_mail_enable = $this->ticketMasterModel->getTemplateDataByTicketID($ticket_id);
// print_rr($auto_mail_enable);
$mail_responce = [];
if (!empty($auto_mail_enable) && $auto_mail_enable['is_auto_mail'] == 1) {
$mail_content = $this->constructMailContent($ticket_id);
// print_r($mail_content); die;
// foreach ($mail_content as $key => $value) {
$mail_responce = $this->sendTrigger($mail_content);
// $this->myLogger->logme('error', '{data} - Auto Mail Sent, Successfully', ['data' => $key + 1]);
$this->myLogger->logme('error', 'Auto Mail Sent, Successfully');
// }
} elseif (!empty($auto_mail_enable) && $auto_mail_enable['is_auto_mail'] == 0) {
$this->myLogger->logme('error', 'Auto Mail Not Sent, Reason: Automail Not Enabled');
} else {
$this->myLogger->logme('error', 'Auto Mail Not Sent, Reason: Mail Template Not Created');
}
return $mail_responce;
}
//---- End Email Trigger Part----------------------------------------------------------------------------------------------
public function ticketHistory($ticket_id)
{
$sql = "SELECT
th.id,
th.field_name,
th.display_name,
th.old_value,
th.new_value,
th.created_at,
CONCAT_WS(' ', creator.first_name, creator.last_name) AS modified_by,
-- Claim Status
old_status.claim_status as old_status_value,
new_status.claim_status as new_status_value,
-- Account Manager
CONCAT(old_account_manager.first_name, ' ', old_account_manager.last_name) as old_account_manager,
CONCAT(new_account_manager.first_name, ' ', new_account_manager.last_name) as new_account_manager,
-- Insured Employee ID Change
old_insured_emp.name as old_insured_id_name,
new_insured_emp.name as new_insured_id_name,
ticket_master.ticket_type_id
FROM
ticket_history th
-- Join for the user who made the change
LEFT JOIN user_profiles creator
ON th.created_by = creator.id
-- Status value lookups
LEFT JOIN ticket_claim_status old_status
ON th.field_name = 'claim_status_id'
AND th.old_value = old_status.id
AND old_status.is_active = 1
LEFT JOIN ticket_claim_status new_status
ON th.field_name = 'claim_status_id'
AND th.new_value = new_status.id
LEFT JOIN user_profiles as old_account_manager
ON th.field_name = 'acm_id'
AND th.old_value = old_account_manager.id
LEFT JOIN user_profiles as new_account_manager
ON th.field_name = 'acm_id'
AND th.new_value = new_account_manager.id
LEFT JOIN employees as old_insured_emp
ON th.field_name = 'insured_emp_id'
AND th.old_value = old_insured_emp.id
LEFT JOIN employees as new_insured_emp
ON th.field_name = 'insured_emp_id'
AND th.new_value = new_insured_emp.id
LEFT JOIN ticket_master as ticket_master
on th.field_name = 'claim_type'
AND th.ticket_id = ticket_master.id
WHERE
th.ticket_id = $ticket_id
AND th.is_active = 1
ORDER BY
th.created_at DESC";
$data = $this->ticketHistoryModel->query($sql)->getResultArray();
// dd(db_connect()->getLastQuery());
$priorityType = $this->priorityType;
$relationshipType = $this->relationshipType;
$modeOFIntimate = $this->modeOFIntimate;
$claim_type = $this->claimType;
foreach ($data as &$row) {
if ($row['field_name'] == 'claim_status_id') {
$new_old_value = isset($row['old_status_value']) ? $row['old_status_value'] : '-';
$new_new_value = $row['new_status_value'];
$row['old_value'] = $new_old_value;
$row['new_value'] = $new_new_value;
} elseif ($row['field_name'] == 'acm_id') {
$new_old_value = isset($row['old_account_manager']) ? $row['old_account_manager'] : '-';
$new_new_value = $row['new_account_manager'];
$row['old_value'] = $new_old_value;
$row['new_value'] = $new_new_value;
} elseif ($row['field_name'] == 'insured_emp_id') {
$new_old_value = isset($row['old_insured_id_name']) ? $row['old_insured_id_name'] : '-';
$new_new_value = $row['new_insured_id_name'];
$row['old_value'] = $new_old_value;
$row['new_value'] = $new_new_value;
} elseif ($row['field_name'] == 'priority') {
$new_old_value = isset($priorityType[$row['old_value']]) ? $priorityType[$row['old_value']] : '-';
$new_new_value = isset($priorityType[$row['new_value']]) ? $priorityType[$row['new_value']] : '-';
$row['old_value'] = $new_old_value;
$row['new_value'] = $new_new_value;
} elseif ($row['field_name'] == 'relationship') {
$new_old_value = isset($relationshipType[$row['old_value']]) ? $relationshipType[$row['old_value']] : '-';
$new_new_value = isset($relationshipType[$row['new_value']]) ? $relationshipType[$row['new_value']] : '-';
$row['old_value'] = $new_old_value;
$row['new_value'] = $new_new_value;
} elseif ($row['field_name'] == 'mode_of_intimation') {
$new_old_value = isset($modeOFIntimate[$row['old_value']]) ? $modeOFIntimate[$row['old_value']] : "-";
$new_new_value = isset($modeOFIntimate[$row['old_value']]) ? $modeOFIntimate[$row['old_value']] : "-";
$row['old_value'] = $new_old_value;
$row['new_value'] = $new_new_value;
} elseif ($row['field_name'] == 'claim_type') {
$new_old_value = isset($claim_type[$row['ticket_type_id']][$row['old_value']]) ? $claim_type[$row['ticket_type_id']][$row['old_value']] : '-';
$new_new_value = isset($claim_type[$row['ticket_type_id']][$row['new_value']]) ? $claim_type[$row['ticket_type_id']][$row['new_value']] : '-';
$row['old_value'] = $new_old_value;
$row['new_value'] = $new_new_value;
} elseif ($row['field_name'] == 'claim_type') {
$new_old_value = isset($claim_type[$row['old_value']]) ? $claim_type[$row['old_value']] : '-';
$new_new_value = isset($claim_type[$row['new_value']]) ? $claim_type[$row['new_value']] : '-';
$row['old_value'] = $new_old_value;
$row['new_value'] = $new_new_value;
} else {
$new_old_value = isset($row['old_value']) ? $row['old_value'] : '-';
$new_new_value = isset($row['new_value']) ? $row['new_value'] : '-';
$row['old_value'] = $new_old_value;
$row['new_value'] = $new_new_value;
}
}
return ($data);
}
public function sendMailWithAutoQuery()
{
$ticket_ids = $this->ticketMessageModel
->select('ticket_master.id')
->join('ticket_master', 'ticket_master.id = ticket_messages.ticket_id AND ticket_master.is_active = 1 and ticket_master.claim_status_id in (4,17,27,37)')
->join('ticket_claim_status AS tcs', 'tcs.id = ticket_messages.claim_status AND (tcs.is_active = 1)')
->join('ticket_notes', 'ticket_notes.ticket_id = ticket_messages.ticket_id AND ticket_notes.is_auto_query = 1 AND ticket_notes.is_active = 1')
->where('ticket_messages.is_active', 1)
->where('ticket_messages.claim_status in (4,17,27,37)')
->groupBy('ticket_master.id')
->having('DATEDIFF(CURDATE(), MAX(ticket_messages.created_at)) =', 7)
->having('count(ticket_messages.id) < ', 6)
->findAll();
// var_dump($ticket_ids);die();
foreach ($ticket_ids as $ticket) {
$ticket_id = $ticket['id'];
$acm_mails = $this->ticketMasterModel->getTicketDataByTicketID($ticket_id);
$ticket_data = $this->ticketMasterModel->getTicketDataByTicketID($ticket_id);
$template_data = $this->ticketMasterModel->getTemplateDataByTicketID($ticket_id);
if (!empty($template_data)) {
$template_data['mail_content'] = $this->replacePlaceholders($template_data['mail_content'], $ticket_data);
$template_data['subject'] = $this->replacePlaceholders($template_data['subject'], $ticket_data);
}
$emailData = [
'mail' => $template_data['emp_mail'],
'subject' => $template_data['subject'],
'message' => $template_data['mail_content'],
'common' => [],
'cc' => $acm_mails['common_mails'],
'attachments' => []
];
$this->myLogger->logme('error', "Final Reply Email Data");
// var_dump($emailData);
$this->sendTrigger($emailData);
}
return 'Ticket id\'s : '.json_encode($ticket_ids);
}
public function ticketReports()
{
if ($this->request->is('get')) {
$default_start = new \DateTime();
$data['default_end'] = $default_start->format('d-m-Y');
$data['default_start'] = $default_start->modify('-60 days')->format('d-m-Y');
$data['policy_type'] = $this->ticketType;
$data['account_manager'] = $this->userModel->select('first_name')->where('is_active', 1)->where('role', 3)->findAll();
$data['report_type'] = [
'acc_manager_wise_status' => 'Account Manger Wise Status Report',
'tpa_wise_status' => 'TPA Wise Status Report',
'tat_band_wise' => 'TAT Wise Status Report'
];
//
$this->loadLayout('ticket_reports', $data);
} else {
$received_data = $this->request->getPost();
$from_Date = $received_data['fromDate'];
$to_Date = $received_data['toDate'];
$fromDate = \DateTime::createFromFormat('d-m-Y', $from_Date)->format('Y-m-d');
$toDate = \DateTime::createFromFormat('d-m-Y', $to_Date)->format('Y-m-d');
$policy_type = $received_data['policy_type'];
// print_rr($received_data);
if ($received_data['report_type'] == "acc_manager_wise_status"){
$viewData['policy_type'] = $received_data['policy_type'];
$viewData['account_manager_wise_data'] = $this->ticketMasterModel->accountManagerWiseReport($policy_type,$fromDate,$toDate);
// print_rr($viewData);die();
if ($policy_type == 1){
$viewData['column_order'] = [
'ACM_NAME', 'ID NOT GENERATED', 'NON ID', 'CDA', 'INFORMATION REQUIRED',
'UNDER PROCESS - CLAIM NO. UPDATION',
'UNDER PROCESS - QUERY DOCUMENT RECEIVED', 'APPROVED', 'PAYMENT INITIATED',
'TOTAL'
];
$ordered_data = [];
foreach ($viewData['account_manager_wise_data'] as $tpa_data) {
$temp = [];
foreach ($viewData['column_order'] as $key) {
$temp[$key] = isset($tpa_data[$key]) ? $tpa_data[$key] : 0; // Default to 0 if key is missing
}
$ordered_data[] = $temp;
}
$viewData['tpa_wise_data'] = $ordered_data;
// print_rr($viewData);die();
$html = view('claims_report_acc_manager_wise', $viewData);
return $this->respond(['status' => true, 'html' => $html], 200);
}else{
$viewData['column_order'] = [
'ACM_NAME', 'CLAIM INTIMATION', 'INTIMATION TO INSURER', 'CLIENT PENDING',
'INSURER PENDING','INVESTIGATION','APPROVED','TOTAL', 'NOT COVERED',
'CLOSED', 'SETTLED', 'CLEARED_TOTAL'
];
$ordered_data = [];
foreach ($viewData['account_manager_wise_data'] as $tpa_data) {
$temp = [];
foreach ($viewData['column_order'] as $key) {
$temp[$key] = isset($tpa_data[$key]) ? $tpa_data[$key] : 0; // Default to 0 if key is missing
}
$ordered_data[] = $temp;
}
$viewData['tpa_wise_data'] = $ordered_data;
// print_rr($viewData);die();
$html = view('claims_report_acc_manager_wise', $viewData);
return $this->respond(['status' => true, 'html' => $html], 200);
}
} elseif ($received_data['report_type'] == 'tpa_wise_status') {
$viewData['tpa_wise_data'] = $this->ticketMasterModel->tpaWiseReport($policy_type, $fromDate, $toDate);
$viewData['column_order'] = [
'TPA_NAME', 'NON ID', 'ID NOT GENERATED', 'CDA', 'INFORMATION REQUIRED',
'UNDER PROCESS - CLAIM NO. UPDATION',
'UNDER PROCESS - QUERY DOCUMENT RECEIVED', 'APPROVED', 'PAYMENT INITIATED',
'TOTAL', 'SETTLED', 'CLOSED', 'CANCELLED', 'RETURNED', 'CLEARED_TOTAL','TPA_ID'
];
// Reorder data based on column order
$ordered_data = [];
foreach ($viewData['tpa_wise_data'] as $tpa_data) {
$temp = [];
foreach ($viewData['column_order'] as $key) {
$temp[$key] = isset($tpa_data[$key]) ? $tpa_data[$key] : 0; // Default to 0 if key is missing
}
$ordered_data[] = $temp;
}
$viewData['tpa_wise_data'] = $ordered_data;
// print_r($ordered_data);die();
// $html = view('claims_report_tpa_wise', $viewData);
$html = view('claims_report_tpa_wise',$viewData);
return $this->respond(['status' => true, 'html' => $html], 200);
} else if ($received_data['report_type'] == 'tat_band_wise') {
$viewData['data'] = $this->ticketMasterModel->getTATReport($policy_type, $fromDate, $toDate);
$viewData['policyType'] = $policy_type;
$viewData['fromDate'] = $fromDate;
$viewData['toDate'] = $toDate;
$html = view('tat_report_band_wise_list', $viewData);
return $this->respond(['status' => true, 'html' => $html], 200);
}
}
}
// -------------------------------------------------------------------------------------------------------------------------
// function for Reject ticket Head Approvel mail sent function
public function sendMailToTheHead($ticket_data)
{
$this->myLogger->logme('error', "sendMailToTheHead Function Called");
if(!empty($ticket_data)){
// print_r($ticket_data); die;
$head_mail = $this->employeeModel
->select('user_profiles.email')
->join('clients', 'employees.client_id = clients.id')
->join('client_rm', 'clients.id = client_rm.client_id')
->join('user_profiles', 'client_rm.user_id = user_profiles.id')
->where('employees.is_active', 1)
->where('client_rm.is_active', 1)
->where('client_rm.level', 1)
->where('employees.id', $ticket_data['emp_id'])
->first();
if(!empty($head_mail)){
$template_data = $this->ticketMailTemplateModel
->where('ticket_mail_template.ticket_type', 0)
->where('ticket_mail_template.trigger_type', 0)
->first();
if(!empty($template_data)){
$subject = $this->replacePlaceholders($template_data['subject'], $ticket_data);
$message = $this->replacePlaceholders($template_data['mail_content'], $ticket_data);
$emailData = [
'mail' => $head_mail['email'],
'subject' => $subject,
'message' => $message,
'common' => [],
];
$this->sendTrigger($emailData);
}else{
$this->myLogger->logme('error', "Head Mail can't be sent because Template data is empty");
}
}else{
$this->myLogger->logme('error', "Head Mail can't be sent because head mail is empty");
}
}else{
$this->myLogger->logme('error', "Head Mail can't be sent because ticket data is empty");
}
}
public function getLastMatchedStatus($incoming_form_values, $old_ticket_data)
{
if (empty($incoming_form_values) || !isset($incoming_form_values['claim_status_id']) || !isset($incoming_form_values['extra_fields_array_for_validate'])) {
return null;
}
$lastMatchedStatus = $incoming_form_values['claim_status_id'];
// Use the provided `extra_fields_array_for_validate` from the incoming data
$statusMapping = json_decode($incoming_form_values['extra_fields_array_for_validate']);
if($incoming_form_values['claim_status_id'] != $old_ticket_data['claim_status_id']){
foreach ($statusMapping as $status => $requiredFields) {
if(!empty($requiredFields) && $status != $old_ticket_data['claim_status_id']){
// Ensure requiredFields is an array
if (!is_array($requiredFields)) {
$requiredFields = [$requiredFields];
}
// Check if all required fields exist and are not empty in the incoming form values
$allFieldsMatched = true;
foreach ($requiredFields as $field) {
if(in_array($field, ['approved_description'])){
continue;
}
if (!isset($incoming_form_values[$field]) || empty($incoming_form_values[$field])) {
$allFieldsMatched = false;
break;
}
}
// Update the last matched status if all fields are validated
if ($allFieldsMatched) {
$lastMatchedStatus = $status;
}
}
}
if($lastMatchedStatus == 1){
if(!empty($incoming_form_values['tpa_no'])){
$lastMatchedStatus = 2;
}
}
}
return $lastMatchedStatus;
}
public function getPolicyStartDate()
{
$data = $this->request->getPost();
$client_policy_id = $data['policy_id'];
$policy_start_date = $this->clientPolicyModel->select('policy_start_date')->where('id', $client_policy_id)->first()['policy_start_date'];
// dd($data);
if (isset($data['employeeId']) && $data['employeeId'] != "" && $data['employeeId'] != null) {
// dd($data);
$emp_id = $data['employeeId'];
$empData = $this->employeeModel->select('dob,doj')->where('id',$emp_id)->findAll();
if (!empty($empData) && $empData != "" && $empData != null ) {
foreach ($empData as &$emp) { // Loop through the data
$doi = $this->employeePolicyModel->select('date_coverage,basic_cover_si')->where('client_policy_id',$client_policy_id)->first();
$emp['dob'] = date('d/m/Y', strtotime($emp['dob']));
$emp['doj'] = date('d/m/Y', strtotime($emp['doj']));
$emp['date_of_inception'] = date('d/m/Y', strtotime($doi['date_coverage']));
$emp['basic_cover_si'] = $doi['basic_cover_si'];
}
}
if ($empData){
return $this->respond(['status' => true, 'minDate' => $policy_start_date,'empData'=> $empData], 200);
}else{
return $this->respond(['status' => false, 'message' => "Policy Not Found"]);
}
} else {
// dd($policy_start_date);
if ($policy_start_date) {
return $this->respond(['status' => true, 'minDate' => $policy_start_date], 200);
} else {
return $this->respond(['status' => false, 'message' => "Policy Not Found"]);
}
}
}
public function getPoliciesbyEmpID()
{
$received_data = $this->request->getPost();
$emp_id = $received_data['emp_id'];
// Get all client policy IDs for the given employee
$policies = $this->employeePolicyModel
->select('client_policy_id')
->where('employee_id', $emp_id)
->where('is_active', 1)
->where('status', 'active')
->findAll();
if (empty($policies)) {
return []; // Return empty if no policies found
}
// Extract client policy IDs into an array
$policy_ids = array_column($policies, 'client_policy_id');
// Fetch all policy names and IDs in one query
$policyNameandID = $this->clientPolicyModel
->select('
CONCAT(policy_type.policy_type, "-", client_policy.policy_no) as client_policy_name,
client_policy.id as client_policy_value,
client_policy.policy_type_id,
client_policy.policy_no,
insurers.id as insurer_id,
insurers.name as insurer_name,
tpa.name as tpa_name,
tpa.id as tpa_id,
')
->join('policy_type', 'policy_type.id = client_policy.policy_type_id AND policy_type.is_active = 1')
->join('insurers', 'insurers.id = client_policy.insurer_id AND insurers.is_active = 1', 'left')
->join('tpa', 'tpa.id = client_policy.tpa_id AND tpa.is_active = 1', 'left')
->where('client_policy.policy_status', 1)
->whereIn('client_policy.id', $policy_ids)
->findAll();
// dd($policyNameandID);
if ($policyNameandID){
return $this->respond(['status'=>true,'policy_data'=> $policyNameandID]);
}else{
return $this->respond(['status'=>false,'message'=> "Policy Not Found"]);
}
}
public function getCheckListAndConvertArrayToString($ticket_data)
{
$data = db_connect()->table('ticket_check_list')
->where('is_active', 1)
->where('ticket_type_id', $ticket_data['ticket_type_id'])
->get()->getResultArray();
$data = !empty($data) ? implode("", array_map(fn($doc) => "<p>{$doc['document']}</p>", $data)) : "";
// $data = !empty($data) ? implode(", ", array_column($data, 'document')) : "";
// print_r($data); die;
return $data;
}
public function downloadClaimForm($insurer_id)
{
$insurerModel = new InsurerModel();
$insurer_data = $insurerModel->where('MD5(id)', $insurer_id)->where('is_active', 1)->first();
if (!$insurer_data) {
$data['message'] = 'The Physical File Not Found';
echo view('errors/404', $data);
}
$fileName = $insurer_data['short_name'] . '.pdf';
$filePath = ROOTPATH . 'public/claim_sample_forms/' . $fileName;
try {
if (file_exists($filePath)) {
return $this->response->download($filePath, null);
} else {
$data['message'] = 'The Physical File Not Found';
echo view('errors/404', $data);
}
} catch (\Exception $e) {
$this->myLogger->logme('error', $e->getMessage());
return $this->response->setStatusCode(500)->setBody('An error occurred while downloading the file.');
}
}
// -------------------------------------------------------------------------------------------------------------------------
public function autoMessageInsertBasedOnMailResponse($mail_sent_status, $ticket_id)
{
if (gettype($mail_sent_status) == 'array') {
$this->myLogger->logme('error', "auto Message Insert Based On Mail Response Failed because is array :$ticket_id ");
} else {
$mail_sent_status = json_decode($mail_sent_status);
$this->myLogger->logme('error', "mail_sent_status is object :$ticket_id ");
}
if (!empty($mail_sent_status) && isset($mail_sent_status->status) && $mail_sent_status->status == 'success') {
$sent_message_data['ticket_id'] = $ticket_id;
$sent_message_data['sender'] = 'staff';
$sent_message_data['emp_mail'] = isset($mail_sent_status->data->params->mail[0]) ? $mail_sent_status->data->params->mail[0] ?? null : $mail_sent_status->data->params->mail ?? null;
$sent_message_data['mail_subject'] = $mail_sent_status->data->params->subject;
$sent_message_data['mail_content'] = $mail_sent_status->data->params->message;
$message_insert_status = $this->ticketMessageModel->insert($sent_message_data);
if ($message_insert_status) {
$this->myLogger->logme('error', "Claim initiated, Mail sent Successfully, successfully store message:$ticket_id ");
} else {
$this->myLogger->logme('error', "Claim initiated, Mail sent Successfully, Failed to store message:$ticket_id ");
}
return true;
} else {
$this->myLogger->logme('error', "Failed to send Mail :$ticket_id ");
return false;
}
}
public function putHistoryAfterInsert($ticket_data, $ticket_id)
{
$this->myLogger->logme('error', "Put History After Insert function called : $ticket_id");
if(!empty($ticket_data)){
$history_data = [
'ticket_id' => $ticket_id,
'field_name' => 'claim_status_id',
'display_name' => 'Ticket Created',
'old_value' => null,
'new_value' => $ticket_data['claim_status_id'],
'created_by' => get_session_userid(),
'is_active' => 1
];
$this->myLogger->logme('error', "Put History After Insert function called : " . json_encode($history_data));
$history_insert = $this->ticketHistoryModel->insert($history_data);
if($history_insert){
$this->myLogger->logme('error', "Put History After Insert Ticket Data Successfully");
}else{
$this->myLogger->logme('error', "Put History After Insert Ticket Data Failed");
}
}else{
$this->myLogger->logme('error', "Put History After Insert Ticket Data is empty");
}
return true;
}
public function viewClaimFeedbackForm($md5_ticket_id,$empView = null)
{
if ($this->request->is("get")){
$data['ticket_id'] = $md5_ticket_id;
$data['ticket_data'] = $this->ticketMasterModel->select('ticket_master.*,clients.client_name')->join('clients','clients.id = ticket_master.client_id')->where('MD5(ticket_master.id)',$md5_ticket_id)->where('ticket_master.is_active',1)->first();
$data['form_submitted'] = !empty($data['ticket_data']['feedback_json'])? 1 : 0;
$data['viewer'] = !empty($empView) ? $empView : 0;
// dd($data);
return view('ticket_feedback_form', $data);
}else{
$formDataJson = json_encode($this->request->getPost());
// log_message("error","Form data : ".$formDataJson);
$data_to_store = [
'feedback_json' => $formDataJson
];
if (!empty($formDataJson)){
// $this->ticketMasterModel->save($data_to_store);
$this->ticketMasterModel->where('MD5(id)', $md5_ticket_id)->set($data_to_store)->update();
return $this->respond(['status' => true,'id'=> $md5_ticket_id,'received_data' => $formDataJson], 200);
}else{
return $this->respond(['status' => false,'id'=> $md5_ticket_id,'received_data' => $formDataJson], 200);
}
}
}
public function feedbackList(){
$data['feedback_data'] = $this->ticketMasterModel->select("ticket_master.*,clients.client_name")->join("clients","clients.id = ticket_master.client_id")->where("ticket_master.is_active",1)->where("ticket_master.feedback_json IS NOT NULL", null, false)->where("ticket_master.feedback_json !=", "")->findAll();
// dd($data);
$this->loadLayout("ticket_feedback_list",$data);
}
public function getMoreInfo($requestFrom = null , $ticket_id = null) {
if($requestFrom == null){
$ticket_id = $this->request->getPost('ticket_id');
}
$this->myLogger->logme("error", "Ticket ID : " . $ticket_id);
$fields = $this->extraFields;
$displayFields = $this->extraFieldsDisplayForFrontend;
$data_to_send = [];
// Get ticket data
$ticket_data = $this->ticketMasterModel->where("id", $ticket_id)->where("is_active", 1)->first();
// Query previous status
$ticket_previous_status = $this->ticketMasterModel
->select("th.old_value, tcs.claim_status")
->join("ticket_history th", "th.ticket_id = ticket_master.id AND th.field_name = 'claim_status_id' AND th.is_active = 1")
->join("ticket_claim_status tcs", "tcs.id = th.old_value AND tcs.is_active = 1")
->where("ticket_master.is_active", 1)
->where("ticket_master.id", $ticket_id)
->groupBy("th.old_value, tcs.claim_status")
->get()
->getResultArray();
// dd($ticket_previous_status);
// Loop through previous status and gather the required data
foreach ($ticket_previous_status as $status) {
// $this->myLogger->logme("error", "Status : " . json_encode($status));
if (isset($fields[$status['old_value']])) {
$field = $fields[$status['old_value']];
// print_r($field);
// Ensure claim_status is a scalar value (string or int)
$claim_status = (string)$status['claim_status']; // Cast to string to avoid issues
// echo $claim_status;
// dd($displayFields[$status['old_value']]);
// Initialize claim_status if it doesn't exist in the array
if (!isset($data_to_send[$claim_status])) {
$data_to_send[$claim_status] = [];
}
// Handle case where $field is an array
if (is_array($field)) {
foreach ($field as $f) {
// dd($displayFields[$status['old_value']]);
// Check if the field exists in the ticket data
$data_to_send[$claim_status][$f] = ['display_name' => $displayFields[$status['old_value']][$f] ,'display_value' => isset($ticket_data[$f]) ? $ticket_data[$f] : null];
// dd($data_to_send);
// Check if the field contains a date and format it
if ($this->isDate($data_to_send[$claim_status][$f]['display_value'])) {
$data_to_send[$claim_status][$f] = ['display_name' => $displayFields[$status['old_value']][$f] ,'display_value' => date('d-m-Y', strtotime($data_to_send[$claim_status][$f]['display_value']))];
// $data_to_send[$claim_status][$f] = date('d-m-Y', strtotime($data_to_send[$claim_status][$f]));
}
// $this->myLogger->logme("error", "Data for field {$f}: " . json_encode($data_to_send[$claim_status][$f]));
}
} else {
// If field is not an array, handle it as a single field
// Check if the field exists in the ticket data
$data_to_send[$claim_status] = ['display_name' => $displayFields[$status['old_value']] ,'display_value' => isset($ticket_data) ? $ticket_data : null];
// Check if the field contains a date and format it
if ($this->isDate($data_to_send[$claim_status][$field])) {
// $data_to_send[$claim_status] = ['display_name' => $displayFields[$status['old_value']] ,'display_value' => date('d-m-Y', strtotime($data_to_send[$claim_status]['display_value']))];
}
// $this->myLogger->logme("error", "Data for field {$field}: " . json_encode($data_to_send[$claim_status][$field]));
}
}
}
// $this->myLogger->logme('error', "Total data: " . json_encode($data_to_send));
if($requestFrom == 'rest'){
return $data_to_send;
}
// Send response based on data availability
if (!empty($data_to_send)) {
return $this->respond(['status' => true, 'data' => $data_to_send], 200);
} else {
return $this->respond(['status' => false], 200);
}
}
private function isDate($value, $format = 'Y-m-d') {
// Check if the value is a valid date string (basic validation)
$date = \DateTime::createFromFormat($format, $value);
return $date && $date->format($format) === $value;
}
}