<?php
defined('BASEPATH') or exit('No direct script access allowed');
class SubActivityProducts extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method');
        header('Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE');
        // // avoiding preflight requests
        $method = $_SERVER['REQUEST_METHOD'];
        if ($method == "OPTIONS") {
            die();
        }

        $this->load->helper('form');
        $this->load->library('upload');
        $this->db->query("SET time_zone = '+03:00'");
    }
    
    
// public function create_product()
// {
//     // Get form data
//     $sub_activity_id = $this->input->post('sub_activity_id');
//     $name = $this->input->post('name');
//     $prod_type = $this->input->post('prod_type'); // ID from product_types
//     $status = $this->input->post('status');
//     $date_submitted = $this->input->post('date_submitted');
//     $last_updated = $this->input->post('last_updated');
//     $in_charge_ids = $this->input->post('in_charge_ids'); // Raw input, could be "[9]" or "9,10"
//     $user_id = $this->input->post('user_id'); // Assuming user_id is passed in the form
//     $group = $this->input->post('group') ?? 'general'; // Default to 'general'
//     $output_id = $this->input->post('output_id'); // Nullable for output products

//     // Validate required fields
//     if (empty($sub_activity_id) || empty($prod_type) || empty($user_id)) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_INPUT'
//             )));
//     }

//     // Validate group (must be 'general' or 'output')
//     if (!in_array($group, ['general', 'output'])) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_GROUP'
//             )));
//     }

//     // If group is 'output', output_id must be provided and valid
//     if ($group === 'output' && empty($output_id)) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'OUTPUT_ID_REQUIRED_FOR_OUTPUT_PRODUCT'
//             )));
//     }

//     // Validate output_id if provided
//     if ($output_id) {
//         $this->db->where('id', $output_id);
//         $output_exists = $this->db->get('sub_activity_outputs')->num_rows() > 0;
//         if (!$output_exists) {
//             return $this->output
//                 ->set_content_type('application/json')
//                 ->set_status_header(400) // Bad Request
//                 ->set_output(json_encode(array(
//                     'success' => false,
//                     'message' => 'INVALID_OUTPUT_ID'
//                 )));
//         }
//     }

//     // Validate prod_type exists and get its category
//     $this->db->where('id', $prod_type);
//     $product_type = $this->db->get('product_types')->row_array();
    
//     $name = empty($name) ? $product_type['name'] : $name;

//     if (empty($product_type)) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_PROD_TYPE'
//             )));
//     }

//     // Determine type based on product_type category
//     $type = ($product_type['category'] === 'folder') ? 'folder' : 'docx';

//     // Parse in_charge_ids (handle string like "[9]" or "9,10")
//     $in_charge_ids_array = [];
//     if (!empty($in_charge_ids)) {
//         // Try to decode as JSON (e.g., "[9]" -> [9])
//         $parsed_ids = json_decode($in_charge_ids, true);
//         if (is_array($parsed_ids)) {
//             $in_charge_ids_array = array_filter(array_map('intval', $parsed_ids)); // Convert to integers, remove empty
//         } else {
//             // If not JSON, split by comma (e.g., "9,10" -> [9, 10])
//             $ids = explode(',', str_replace(['[', ']', '"'], '', $in_charge_ids));
//             $in_charge_ids_array = array_filter(array_map('trim', $ids), 'strlen'); // Clean and filter empty values
//             $in_charge_ids_array = array_map('intval', $in_charge_ids_array); // Convert to integers
//         }
//     }

//     // Prepare data for insertion (initial setup)
//     $data = array(
//         'sub_activity_id' => $sub_activity_id,
//         'name' => $name,
//         'type' => $type, // Set to 'folder' or 'docx' based on category (will be updated for single files)
//         'url' => '', // Will be set for single files or left empty for folders
//         'status' => $status ? $status : 'Pending', // Default to 'Pending' if not specified
//         'date_submitted' => $date_submitted ? date('Y-m-d', strtotime($date_submitted)) : date('Y-m-d'),
//         'last_updated' => $last_updated ? date('Y-m-d', strtotime($last_updated)) : date('Y-m-d'),
//         'in_charge_ids' => !empty($in_charge_ids_array) ? json_encode($in_charge_ids_array) : json_encode([]),
//         'prod_type' => $prod_type,
//         'group' => $group,
//         'output_id' => $group === 'output' ? $output_id : NULL,
//         'created_by' => $user_id,
//         'updated_by' => $user_id
//     );

//     // Check if a file is uploaded and update status to 'Submitted' if status is 'Pending' or not specified
//     $has_file_upload = !empty($_FILES['file']['name']) || (!empty($_FILES['files']) && is_array($_FILES['files']['name']) && !empty($_FILES['files']['name'][0]));
//     if ($has_file_upload) {
//         if (!isset($status) || (isset($status) && $status === 'Pending')) {
//             $data['status'] = 'Submitted'; // Override status to 'Submitted' if no status is specified or if status is 'Pending'
//         }
//     }

//     // Validate status (must be 'Pending', 'Submitted', 'In Review', 'Declined', or 'Finalised')
//     if (!in_array($data['status'], ['Pending', 'Submitted', 'In Review', 'Declined', 'Finalised'])) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_STATUS'
//             )));
//     }

//     // Validate sub_activity_id exists in sub_activities table
//     $this->db->where('id', $data['sub_activity_id']);
//     $sub_activity_exists = $this->db->get('sub_activities')->num_rows() > 0;

//     if (!$sub_activity_exists) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_SUB_ACTIVITY_ID'
//             )));
//     }

//     // Validate in_charge_ids (ensure all user IDs exist)
//     if (!empty($in_charge_ids_array)) {
//         $this->db->where_in('id', $in_charge_ids_array);
//         $users_exist = $this->db->get('users')->num_rows() === count($in_charge_ids_array);

//         if (!$users_exist) {
//             return $this->output
//                 ->set_content_type('application/json')
//                 ->set_status_header(400) // Bad Request
//                 ->set_output(json_encode(array(
//                     'success' => false,
//                     'message' => 'INVALID_USER_IDS_IN_IN_CHARGE'
//                 )));
//         }
//     }

//     // Validate user_id exists in users table
//     $this->db->where('id', $user_id);
//     $user_exists = $this->db->get('users')->num_rows() > 0;

//     if (!$user_exists) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_USER_ID'
//             )));
//     }

//     // Start a transaction to ensure data consistency
//     $this->db->trans_start();

//     // Insert the product into the database first to get product_id
//     $insert = $this->db->insert('sub_activity_products', $data);
//     if (!$insert) {
//         $this->db->trans_rollback();
//         log_message('error', "Failed to insert product: " . $this->db->error()['message']);
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'PRODUCT_NOT_ADDED - ' . $this->db->error()['message']
//             )));
//     }

//     $product_id = $this->db->insert_id();

//     // Handle file uploads
//     $files = [];
//     $directory = "sub_activity_products";
//     if (!file_exists($directory)) {
//         mkdir($directory, 0777, true);
//     }

//     if ($product_type['category'] === 'folder') {
//         // Handle multiple file uploads for folder products
//         $result = $this->handle_multiple_file_uploads_for_sub_activity($product_id, 'files', $directory, $user_id);
//         if ($result['success'] === false) {
//             $this->db->trans_rollback();
//             return $this->output
//                 ->set_content_type('application/json')
//                 ->set_status_header(400) // Bad Request
//                 ->set_output(json_encode(array(
//                     'success' => false,
//                     'message' => $result['message']
//                 )));
//         }
//         $files = $result['files'];
//         $data['url'] = ''; // No URL for folders
//     } else {
//         // Handle single file upload for non-folder products
//         if (!empty($_FILES['file']['name'])) {
//             $result = $this->handle_single_file_upload_for_sub_activity('file', $directory);
//             if ($result['success'] === false) {
//                 $this->db->trans_rollback();
//                 return $this->output
//                     ->set_content_type('application/json')
//                     ->set_status_header(400) // Bad Request
//                     ->set_output(json_encode(array(
//                         'success' => false,
//                         'message' => $result['message']
//                     )));
//             }
//             $data['url'] = $result['file_url'];
//             $data['type'] = $result['file_extension']; // Set type as the file extension
//             $files = []; // No files array for single files
//         }
//     }

//     // Update sub_activity status to "In Progress" if a file is uploaded
//     if ($has_file_upload) {
//         $this->db->where('id', $sub_activity_id);
//         $sub_activity = $this->db->get('sub_activities')->row_array();
//         if ($sub_activity && $sub_activity['status'] !== 'Finalised') { // Avoid overriding "Finalised" status
//             $this->db->where('id', $sub_activity_id);
//             $this->db->update('sub_activities', ['status' => 'In Progress', 'updated_by' => $user_id, 'updated_at' => date('Y-m-d H:i:s')]);
//             if ($this->db->affected_rows() === 0) {
//                 log_message('error', "Failed to update sub_activity status to In Progress for sub_activity_id: $sub_activity_id");
//             }
//         }
//     }

//     // Commit the transaction if all operations succeed
//     $this->db->trans_complete();

//     if ($this->db->trans_status() === FALSE) {
//         log_message('error', "Transaction failed: " . $this->db->error()['message']);
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'TRANSACTION_FAILED - ' . $this->db->error()['message']
//             )));
//     }

//     // Fetch in_charge details and files for response
//     $in_charge_details = [];
//     if (!empty($in_charge_ids_array)) {
//         $this->db->select('id, first_name, image as avatar');
//         $this->db->where_in('id', $in_charge_ids_array);
//         $users = $this->db->get('users')->result_array();
//         foreach ($users as $user) {
//             $in_charge_details[] = [
//                 'id' => $user['id'],
//                 'first_name' => $user['first_name'],
//                 'avatar' => $user['avatar']
//             ];
//         }
//     }

//     $product_files = [];
//     if ($product_type['category'] === 'folder') {
//         $this->db->where('product_id', $product_id);
//         $files_data = $this->db->get('sub_activity_product_files')->result_array();
//         foreach ($files_data as $file) {
//             $product_files[] = [
//                 'id' => $file['id'],
//                 'name' => $file['name'],
//                 'type' => $file['type'],
//                 'url' => $file['url'],
//                 'date' => $file['date'],
//                 'size' => $file['size']
//             ];
//         }
//     }

//     $response_data = [
//         'success' => true,
//         'message' => 'PRODUCT_ADDED_SUCCESSFULLY',
//         'data' => [
//             'id' => $product_id,
//             'type' => $data['type'],
//             'name' => $data['name'],
//             'url' => $data['url'],
//             'inCharge' => $in_charge_details,
//             'status' => $data['status'],
//             'dateSubmitted' => $data['date_submitted'],
//             'lastUpdated' => $data['last_updated']
//         ]
//     ];

//     // Only include 'files' if category is 'folder'
//     if ($product_type['category'] === 'folder') {
//         $response_data['data']['files'] = $product_files;
//     }

//     return $this->output
//         ->set_content_type('application/json')
//         ->set_status_header(201) // Created
//         ->set_output(json_encode($response_data));
// }

//wereo
// public function create_product()
// {
//     // Get form data
//     $sub_activity_id = $this->input->post('sub_activity_id');
//     $name = $this->input->post('name');
//     $prod_type = $this->input->post('prod_type'); // ID from product_types
//     $status = $this->input->post('status');
//     $date_submitted = $this->input->post('date_submitted');
//     $last_updated = $this->input->post('last_updated');
//     $in_charge_ids = $this->input->post('in_charge_ids'); // Raw input, could be "[9]" or "9,10"
//     $user_id = $this->input->post('user_id'); // Assuming user_id is passed in the form
//     $group = $this->input->post('group') ?? 'general'; // Default to 'general'
//     $output_id = $this->input->post('output_id'); // Nullable for output products

//     // Validate required fields
//     if (empty($sub_activity_id) || empty($prod_type) || empty($user_id)) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_INPUT'
//             )));
//     }

//     // Validate group (must be 'general' or 'output')
//     if (!in_array($group, ['general', 'output'])) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_GROUP'
//             )));
//     }

//     // If group is 'output', output_id must be provided and valid
//     if ($group === 'output' && empty($output_id)) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'OUTPUT_ID_REQUIRED_FOR_OUTPUT_PRODUCT'
//             )));
//     }

//     // Validate output_id if provided
//     if ($output_id) {
//         $this->db->where('id', $output_id);
//         $output_exists = $this->db->get('sub_activity_outputs')->num_rows() > 0;
//         if (!$output_exists) {
//             return $this->output
//                 ->set_content_type('application/json')
//                 ->set_status_header(400) // Bad Request
//                 ->set_output(json_encode(array(
//                     'success' => false,
//                     'message' => 'INVALID_OUTPUT_ID'
//                 )));
//         }
//     }

//     // Validate prod_type exists and get its category
//     $this->db->where('id', $prod_type);
//     $product_type = $this->db->get('product_types')->row_array();
    
//     $name = empty($name) ? $product_type['name'] : $name;

//     if (empty($product_type)) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_PROD_TYPE'
//             )));
//     }

//     // Determine type based on product_type category
//     $type = ($product_type['category'] === 'folder') ? 'folder' : 'docx';

//     // Parse in_charge_ids (handle string like "[9]" or "9,10")
//     $in_charge_ids_array = [];
//     if (!empty($in_charge_ids)) {
//         // Try to decode as JSON (e.g., "[9]" -> [9])
//         $parsed_ids = json_decode($in_charge_ids, true);
//         if (is_array($parsed_ids)) {
//             $in_charge_ids_array = array_filter(array_map('intval', $parsed_ids)); // Convert to integers, remove empty
//         } else {
//             // If not JSON, split by comma (e.g., "9,10" -> [9, 10])
//             $ids = explode(',', str_replace(['[', ']', '"'], '', $in_charge_ids));
//             $in_charge_ids_array = array_filter(array_map('trim', $ids), 'strlen'); // Clean and filter empty values
//             $in_charge_ids_array = array_map('intval', $in_charge_ids_array); // Convert to integers
//         }
//     }

//     // Prepare data for insertion (initial setup)
//     $data = array(
//         'sub_activity_id' => $sub_activity_id,
//         'name' => $name,
//         'type' => $type, // Set to 'folder' or 'docx' based on category (will be updated for single files)
//         'url' => '', // Will be set for single files or left empty for folders
//         'status' => $status ? $status : 'Pending', // Default to 'Pending' if not specified
//         'date_submitted' => $date_submitted ? date('Y-m-d', strtotime($date_submitted)) : date('Y-m-d'),
//         'last_updated' => $last_updated ? date('Y-m-d', strtotime($last_updated)) : date('Y-m-d'),
//         'in_charge_ids' => !empty($in_charge_ids_array) ? json_encode($in_charge_ids_array) : json_encode([]),
//         'prod_type' => $prod_type,
//         'group' => $group,
//         'output_id' => $group === 'output' ? $output_id : NULL,
//         'created_by' => $user_id,
//         'updated_by' => $user_id
//     );

//     // Check if a file is uploaded and update status to 'Submitted' if status is 'Pending' or not specified
//     $has_file_upload = !empty($_FILES['file']['name']) || (!empty($_FILES['files']) && is_array($_FILES['files']['name']) && !empty($_FILES['files']['name'][0]));
//     if ($has_file_upload) {
//         if (!isset($status) || (isset($status) && $status === 'Pending')) {
//             $data['status'] = 'Submitted'; // Override status to 'Submitted' if no status is specified or if status is 'Pending'
//         }
//     }

//     // Validate status (must be 'Pending', 'Submitted', 'In Review', 'Declined', or 'Finalised')
//     if (!in_array($data['status'], ['Pending', 'Submitted', 'In Review', 'Declined', 'Finalised'])) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_STATUS'
//             )));
//     }

//     // Validate sub_activity_id exists in sub_activities table
//     $this->db->where('id', $data['sub_activity_id']);
//     $sub_activity_exists = $this->db->get('sub_activities')->num_rows() > 0;

//     if (!$sub_activity_exists) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_SUB_ACTIVITY_ID'
//             )));
//     }

//     // Validate in_charge_ids (ensure all user IDs exist)
//     if (!empty($in_charge_ids_array)) {
//         $this->db->where_in('id', $in_charge_ids_array);
//         $users_exist = $this->db->get('users')->num_rows() === count($in_charge_ids_array);

//         if (!$users_exist) {
//             return $this->output
//                 ->set_content_type('application/json')
//                 ->set_status_header(400) // Bad Request
//                 ->set_output(json_encode(array(
//                     'success' => false,
//                     'message' => 'INVALID_USER_IDS_IN_IN_CHARGE'
//                 )));
//         }
//     }

//     // Validate user_id exists in users table
//     $this->db->where('id', $user_id);
//     $user_exists = $this->db->get('users')->num_rows() > 0;

//     if (!$user_exists) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_USER_ID'
//             )));
//     }

//     // Start a transaction to ensure data consistency
//     $this->db->trans_start();

//     // Insert the product into the database first to get product_id
//     $insert = $this->db->insert('sub_activity_products', $data);
//     if (!$insert) {
//         $this->db->trans_rollback();
//         log_message('error', "Failed to insert product: " . $this->db->error()['message']);
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'PRODUCT_NOT_ADDED - ' . $this->db->error()['message']
//             )));
//     }

//     $product_id = $this->db->insert_id();

//     // Handle file uploads
//     $files = [];
//     $directory = "sub_activity_products";
//     if (!file_exists($directory)) {
//         mkdir($directory, 0777, true);
//     }

//     if ($product_type['category'] === 'folder') {
//         // Handle multiple file uploads for folder products
//         $result = $this->handle_multiple_file_uploads_for_sub_activity($product_id, 'files', $directory, $user_id);
//         if ($result['success'] === false) {
//             $this->db->trans_rollback();
//             return $this->output
//                 ->set_content_type('application/json')
//                 ->set_status_header(400)
//                 ->set_output(json_encode(array(
//                     'success' => false,
//                     'message' => $result['message']
//                 )));
//         }
//         $files = $result['files'];
//         $data['url'] = ''; // No URL for folders
//     } else {
//         // Handle single file upload for non-folder products
//         if (!empty($_FILES['file']['name'])) {
//             $result = $this->handle_single_file_upload_for_sub_activity('file', $directory);
//             if ($result['success'] === false) {
//                 $this->db->trans_rollback();
//                 return $this->output
//                     ->set_content_type('application/json')
//                     ->set_status_header(400)
//                     ->set_output(json_encode(array(
//                         'success' => false,
//                         'message' => $result['message']
//                     )));
//             }
//             // Update the product with the new URL and type
//             $update_data = [
//                 'url' => $result['file_url'],
//                 'type' => $result['file_extension'], // Set type as the file extension
//                 'updated_by' => $user_id,
//                 'updated_at' => date('Y-m-d H:i:s')
//             ];
//             $this->db->where('id', $product_id);
//             $this->db->update('sub_activity_products', $update_data);
//             if ($this->db->affected_rows() === 0 && $this->db->error()['code'] != 0) {
//                 $this->db->trans_rollback();
//                 log_message('error', "Failed to update product URL for product_id: $product_id");
//                 return $this->output
//                     ->set_content_type('application/json')
//                     ->set_status_header(400)
//                     ->set_output(json_encode(array(
//                         'success' => false,
//                         'message' => 'FAILED_TO_UPDATE_PRODUCT_URL'
//                     )));
//             }
//             // Update $data for response
//             $data['url'] = $result['file_url'];
//             $data['type'] = $result['file_extension'];
//             $files = []; // No files array for single files
//         }
//     }

//     // Update sub_activity status to "In Progress" if a file is uploaded
//     if ($has_file_upload) {
//         $this->db->where('id', $sub_activity_id);
//         $sub_activity = $this->db->get('sub_activities')->row_array();
//         if ($sub_activity && $sub_activity['status'] !== 'Finalised') { // Avoid overriding "Finalised" status
//             $this->db->where('id', $sub_activity_id);
//             $this->db->update('sub_activities', ['status' => 'In Progress', 'updated_by' => $user_id, 'updated_at' => date('Y-m-d H:i:s')]);
//             if ($this->db->affected_rows() === 0 && $this->db->error()['code'] != 0) {
//                 log_message('error', "Failed to update sub_activity status to In Progress for sub_activity_id: $sub_activity_id");
//             }
//         }
//     }

//     // Commit the transaction if all operations succeed
//     $this->db->trans_complete();

//     if ($this->db->trans_status() === FALSE) {
//         log_message('error', "Transaction failed: " . $this->db->error()['message']);
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'TRANSACTION_FAILED - ' . $this->db->error()['message']
//             )));
//     }

//     // Fetch in_charge details and files for response
//     $in_charge_details = [];
//     if (!empty($in_charge_ids_array)) {
//         $this->db->select('id, first_name, image as avatar');
//         $this->db->where_in('id', $in_charge_ids_array);
//         $users = $this->db->get('users')->result_array();
//         foreach ($users as $user) {
//             $in_charge_details[] = [
//                 'id' => $user['id'],
//                 'first_name' => $user['first_name'],
//                 'avatar' => $user['avatar']
//             ];
//         }
//     }

//     $product_files = [];
//     if ($product_type['category'] === 'folder') {
//         $this->db->where('product_id', $product_id);
//         $files_data = $this->db->get('sub_activity_product_files')->result_array();
//         foreach ($files_data as $file) {
//             $product_files[] = [
//                 'id' => $file['id'],
//                 'name' => $file['name'],
//                 'type' => $file['type'],
//                 'url' => $file['url'],
//                 'date' => $file['date'],
//                 'size' => $file['size']
//             ];
//         }
//     }

//     $response_data = [
//         'success' => true,
//         'message' => 'PRODUCT_ADDED_SUCCESSFULLY',
//         'data' => [
//             'id' => $product_id,
//             'type' => $data['type'],
//             'name' => $data['name'],
//             'url' => $data['url'],
//             'inCharge' => $in_charge_details,
//             'status' => $data['status'],
//             'dateSubmitted' => $data['date_submitted'],
//             'lastUpdated' => $data['last_updated']
//         ]
//     ];

//     // Only include 'files' if category is 'folder'
//     if ($product_type['category'] === 'folder') {
//         $response_data['data']['files'] = $product_files;
//     }

//     return $this->output
//         ->set_content_type('application/json')
//         ->set_status_header(201) // Created
//         ->set_output(json_encode($response_data));
// }

// public function create_product()
// {
//     // Get form data
//     $sub_activity_id = $this->input->post('sub_activity_id');
//     $name = $this->input->post('name');
//     $prod_type = $this->input->post('prod_type'); // ID from product_types
//     $status = $this->input->post('status');
//     $date_submitted = $this->input->post('date_submitted');
//     $last_updated = $this->input->post('last_updated');
//     $in_charge_ids = $this->input->post('in_charge_ids'); // Raw input, could be "[9]" or "9,10"
//     $user_id = $this->input->post('user_id'); // Assuming user_id is passed in the form
//     $group = $this->input->post('group') ?? 'general'; // Default to 'general'
//     $output_id = $this->input->post('output_id'); // Nullable for output products

//     // Validate required fields
//     if (empty($sub_activity_id) || empty($prod_type) || empty($user_id)) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_INPUT'
//             )));
//     }

//     // Validate group (must be 'general' or 'output')
//     if (!in_array($group, ['general', 'output'])) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_GROUP'
//             )));
//     }

//     // If group is 'output', output_id must be provided and valid
//     if ($group === 'output' && empty($output_id)) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'OUTPUT_ID_REQUIRED_FOR_OUTPUT_PRODUCT'
//             )));
//     }

//     // Validate output_id if provided
//     if ($output_id) {
//         $this->db->where('id', $output_id);
//         $output_exists = $this->db->get('sub_activity_outputs')->num_rows() > 0;
//         if (!$output_exists) {
//             return $this->output
//                 ->set_content_type('application/json')
//                 ->set_status_header(400) // Bad Request
//                 ->set_output(json_encode(array(
//                     'success' => false,
//                     'message' => 'INVALID_OUTPUT_ID'
//                 )));
//         }
//     }

//     // Validate prod_type exists and get its category
//     $this->db->where('id', $prod_type);
//     $product_type = $this->db->get('product_types')->row_array();
    
//     $name = empty($name) ? $product_type['name'] : $name;

//     if (empty($product_type)) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_PROD_TYPE'
//             )));
//     }

//     // Determine type based on product_type category
//     $type = ($product_type['category'] === 'folder') ? 'folder' : 'docx';

//     // Parse in_charge_ids (handle string like "[9]" or "9,10")
//     $in_charge_ids_array = [];
//     if (!empty($in_charge_ids)) {
//         // Try to decode as JSON (e.g., "[9]" -> [9])
//         $parsed_ids = json_decode($in_charge_ids, true);
//         if (is_array($parsed_ids)) {
//             $in_charge_ids_array = array_filter(array_map('intval', $parsed_ids)); // Convert to integers, remove empty
//         } else {
//             // If not JSON, split by comma (e.g., "9,10" -> [9, 10])
//             $ids = explode(',', str_replace(['[', ']', '"'], '', $in_charge_ids));
//             $in_charge_ids_array = array_filter(array_map('trim', $ids), 'strlen'); // Clean and filter empty values
//             $in_charge_ids_array = array_map('intval', $in_charge_ids_array); // Convert to integers
//         }
//     }

//     // Prepare data for insertion (initial setup)
//     $data = array(
//         'sub_activity_id' => $sub_activity_id,
//         'name' => $name,
//         'type' => $type, // Set to 'folder' or 'docx' based on category (will be updated for single files)
//         'url' => '', // Will be set for single files or left empty for folders
//         'status' => $status ? $status : 'Pending', // Default to 'Pending' if not specified
//         'date_submitted' => $date_submitted ? date('Y-m-d', strtotime($date_submitted)) : date('Y-m-d'),
//         'last_updated' => $last_updated ? date('Y-m-d', strtotime($last_updated)) : date('Y-m-d'),
//         'in_charge_ids' => !empty($in_charge_ids_array) ? json_encode($in_charge_ids_array) : json_encode([]),
//         'prod_type' => $prod_type,
//         'group' => $group,
//         'output_id' => $group === 'output' ? $output_id : NULL,
//         'created_by' => $user_id,
//         'updated_by' => $user_id
//     );

//     // Check if a file is uploaded and update status to 'Submitted' if status is 'Pending' or not specified
//     $has_file_upload = !empty($_FILES['file']['name']) || (!empty($_FILES['files']) && is_array($_FILES['files']['name']) && !empty($_FILES['files']['name'][0]));
//     if ($has_file_upload) {
//         if (!isset($status) || (isset($status) && $status === 'Pending')) {
//             $data['status'] = 'Submitted'; // Override status to 'Submitted' if no status is specified or if status is 'Pending'
//         }
//     }

//     // Validate status (must be 'Pending', 'Submitted', 'In Review', 'Declined', or 'Finalised')
//     if (!in_array($data['status'], ['Pending', 'Submitted', 'In Review', 'Declined', 'Finalised'])) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_STATUS'
//             )));
//     }

//     // Validate sub_activity_id exists in sub_activities table
//     $this->db->where('id', $data['sub_activity_id']);
//     $sub_activity_exists = $this->db->get('sub_activities')->num_rows() > 0;

//     if (!$sub_activity_exists) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_SUB_ACTIVITY_ID'
//             )));
//     }

//     // Validate in_charge_ids (ensure all user IDs exist)
//     if (!empty($in_charge_ids_array)) {
//         $this->db->where_in('id', $in_charge_ids_array);
//         $users_exist = $this->db->get('users')->num_rows() === count($in_charge_ids_array);

//         if (!$users_exist) {
//             return $this->output
//                 ->set_content_type('application/json')
//                 ->set_status_header(400) // Bad Request
//                 ->set_output(json_encode(array(
//                     'success' => false,
//                     'message' => 'INVALID_USER_IDS_IN_IN_CHARGE'
//                 )));
//         }
//     }

//     // Validate user_id exists in users table
//     $this->db->where('id', $user_id);
//     $user_exists = $this->db->get('users')->num_rows() > 0;

//     if (!$user_exists) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_USER_ID'
//             )));
//     }

//     // Start a transaction to ensure data consistency
//     $this->db->trans_start();

//     // Insert the product into the database first to get product_id
//     $insert = $this->db->insert('sub_activity_products', $data);
//     if (!$insert) {
//         $this->db->trans_rollback();
//         log_message('error', "Failed to insert product: " . $this->db->error()['message']);
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'PRODUCT_NOT_ADDED - ' . $this->db->error()['message']
//             )));
//     }

//     $product_id = $this->db->insert_id();

//     // Handle file uploads
//     $files = [];
//     $directory = "sub_activity_products";
//     if (!file_exists($directory)) {
//         mkdir($directory, 0777, true);
//     }

//     if ($product_type['category'] === 'folder') {
//         // Handle multiple file uploads for folder products
//         $result = $this->handle_multiple_file_uploads_for_sub_activity($product_id, 'files', $directory, $user_id);
//         if ($result['success'] === false) {
//             $this->db->trans_rollback();
//             log_message('error', "Multiple file upload failed: " . $result['message']);
//             return $this->output
//                 ->set_content_type('application/json')
//                 ->set_status_header(400)
//                 ->set_output(json_encode(array(
//                     'success' => false,
//                     'message' => $result['message']
//                 )));
//         }
//         $files = $result['files'];
//         $data['url'] = ''; // No URL for folders
//     } else {
//         // Handle single file upload for non-folder products
//         if (!empty($_FILES['file']['name'])) {
//             $result = $this->handle_single_file_upload_for_sub_activity('file', $directory);
//             if ($result['success'] === false) {
//                 $this->db->trans_rollback();
//                 return $this->output
//                     ->set_content_type('application/json')
//                     ->set_status_header(400)
//                     ->set_output(json_encode(array(
//                         'success' => false,
//                         'message' => $result['message']
//                     )));
//             }
//             // Update the product with the new URL and type
//             $update_data = [
//                 'url' => $result['file_url'],
//                 'type' => $result['file_extension'], // Set type as the file extension
//                 'updated_by' => $user_id,
//                 'updated_at' => date('Y-m-d H:i:s')
//             ];
//             $this->db->where('id', $product_id);
//             $this->db->update('sub_activity_products', $update_data);
//             if ($this->db->affected_rows() === 0 && $this->db->error()['code'] != 0) {
//                 $this->db->trans_rollback();
//                 log_message('error', "Failed to update product URL for product_id: $product_id");
//                 return $this->output
//                     ->set_content_type('application/json')
//                     ->set_status_header(400)
//                     ->set_output(json_encode(array(
//                         'success' => false,
//                         'message' => 'FAILED_TO_UPDATE_PRODUCT_URL'
//                     )));
//             }
//             // Update $data for response
//             $data['url'] = $result['file_url'];
//             $data['type'] = $result['file_extension'];
//             $files = []; // No files array for single files
//         }
//     }

//     // Update sub_activity status to "In Progress" if a file is uploaded
//     if ($has_file_upload) {
//         $this->db->where('id', $sub_activity_id);
//         $sub_activity = $this->db->get('sub_activities')->row_array();
//         if ($sub_activity && $sub_activity['status'] !== 'Finalised') { // Avoid overriding "Finalised" status
//             $this->db->where('id', $sub_activity_id);
//             $this->db->update('sub_activities', ['status' => 'In Progress', 'updated_by' => $user_id, 'updated_at' => date('Y-m-d H:i:s')]);
//             if ($this->db->affected_rows() === 0 && $this->db->error()['code'] != 0) {
//                 log_message('error', "Failed to update sub_activity status to In Progress for sub_activity_id: $sub_activity_id");
//             }
//         }
//     }

//     // Commit the transaction if all operations succeed
//     $this->db->trans_complete();

//     if ($this->db->trans_status() === FALSE) {
//         log_message('error', "Transaction failed: " . $this->db->error()['message']);
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'TRANSACTION_FAILED - ' . $this->db->error()['message']
//             )));
//     }

//     // Fetch in_charge details and files for response
//     $in_charge_details = [];
//     if (!empty($in_charge_ids_array)) {
//         $this->db->select('id, first_name, image as avatar');
//         $this->db->where_in('id', $in_charge_ids_array);
//         $users = $this->db->get('users')->result_array();
//         foreach ($users as $user) {
//             $in_charge_details[] = [
//                 'id' => $user['id'],
//                 'first_name' => $user['first_name'],
//                 'avatar' => $user['avatar']
//             ];
//         }
//     }

//     $product_files = [];
//     if ($product_type['category'] === 'folder') {
//         $this->db->where('product_id', $product_id);
//         $files_data = $this->db->get('sub_activity_product_files')->result_array();
//         foreach ($files_data as $file) {
//             $product_files[] = [
//                 'id' => $file['id'],
//                 'name' => $file['name'],
//                 'type' => $file['type'],
//                 'url' => $file['url'],
//                 'date' => $file['date'],
//                 'size' => $file['size']
//             ];
//         }
//     }

//     $response_data = [
//         'success' => true,
//         'message' => 'PRODUCT_ADDED_SUCCESSFULLY',
//         'data' => [
//             'id' => $product_id,
//             'type' => $data['type'],
//             'name' => $data['name'],
//             'url' => $data['url'],
//             'inCharge' => $in_charge_details,
//             'status' => $data['status'],
//             'dateSubmitted' => $data['date_submitted'],
//             'lastUpdated' => $data['last_updated']
//         ]
//     ];

//     // Only include 'files' if category is 'folder'
//     if ($product_type['category'] === 'folder') {
//         $response_data['data']['files'] = $product_files;
//     }

//     return $this->output
//         ->set_content_type('application/json')
//         ->set_status_header(201) // Created
//         ->set_output(json_encode($response_data));
// }


//fdfadf

// public function create_product()
// {
//     // Get form data
//     $sub_activity_id = $this->input->post('sub_activity_id');
//     $name = $this->input->post('name');
//     $prod_type = $this->input->post('prod_type'); // ID from product_types
//     $status = $this->input->post('status');
//     $date_submitted = $this->input->post('date_submitted');
//     $last_updated = $this->input->post('last_updated');
//     $in_charge_ids = $this->input->post('in_charge_ids'); // Raw input, could be "[9]" or "9,10"
//     $user_id = $this->input->post('user_id'); // Assuming user_id is passed in the form
//     $group = $this->input->post('group') ?? 'general'; // Default to 'general'
//     $output_id = $this->input->post('output_id'); // Nullable for output products

//     // Validate required fields
//     if (empty($sub_activity_id) || empty($prod_type) || empty($user_id)) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_INPUT'
//             )));
//     }

//     // Validate group (must be 'general' or 'output')
//     if (!in_array($group, ['general', 'output'])) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_GROUP'
//             )));
//     }

//     // If group is 'output', output_id must be provided and valid
//     if ($group === 'output' && empty($output_id)) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'OUTPUT_ID_REQUIRED_FOR_OUTPUT_PRODUCT'
//             )));
//     }

//     // Validate output_id if provided
//     if ($output_id) {
//         $this->db->where('id', $output_id);
//         $output_exists = $this->db->get('sub_activity_outputs')->num_rows() > 0;
//         if (!$output_exists) {
//             return $this->output
//                 ->set_content_type('application/json')
//                 ->set_status_header(400) // Bad Request
//                 ->set_output(json_encode(array(
//                     'success' => false,
//                     'message' => 'INVALID_OUTPUT_ID'
//                 )));
//         }
//     }

//     // Validate prod_type exists and get its category
//     $this->db->where('id', $prod_type);
//     $product_type = $this->db->get('product_types')->row_array();
    
//     $name = empty($name) ? $product_type['name'] : $name;

//     if (empty($product_type)) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_PROD_TYPE'
//             )));
//     }

//     // Determine type based on product_type category
//     $type = ($product_type['category'] === 'folder') ? 'folder' : 'docx';

//     // Parse in_charge_ids (handle string like "[9]" or "9,10")
//     $in_charge_ids_array = [];
//     if (!empty($in_charge_ids)) {
//         // Try to decode as JSON (e.g., "[9]" -> [9])
//         $parsed_ids = json_decode($in_charge_ids, true);
//         if (is_array($parsed_ids)) {
//             $in_charge_ids_array = array_filter(array_map('intval', $parsed_ids)); // Convert to integers, remove empty
//         } else {
//             // If not JSON, split by comma (e.g., "9,10" -> [9, 10])
//             $ids = explode(',', str_replace(['[', ']', '"'], '', $in_charge_ids));
//             $in_charge_ids_array = array_filter(array_map('trim', $ids), 'strlen'); // Clean and filter empty values
//             $in_charge_ids_array = array_map('intval', $in_charge_ids_array); // Convert to integers
//         }
//     }

//     // Prepare data for insertion (initial setup)
//     $data = array(
//         'sub_activity_id' => $sub_activity_id,
//         'name' => $name,
//         'type' => $type, // Set to 'folder' or 'docx' based on category (will be updated for single files)
//         'url' => '', // Will be set for single files or left empty for folders
//         'status' => $status ? $status : 'Pending', // Default to 'Pending' if not specified
//         'date_submitted' => $date_submitted ? date('Y-m-d', strtotime($date_submitted)) : date('Y-m-d'),
//         'last_updated' => $last_updated ? date('Y-m-d', strtotime($last_updated)) : date('Y-m-d'),
//         'in_charge_ids' => !empty($in_charge_ids_array) ? json_encode($in_charge_ids_array) : json_encode([]),
//         'prod_type' => $prod_type,
//         'group' => $group,
//         'output_id' => $group === 'output' ? $output_id : NULL,
//         'created_by' => $user_id,
//         'updated_by' => $user_id
//     );

//     // Check if a file is uploaded and update status to 'Submitted' if status is 'Pending' or not specified
//     $has_file_upload = !empty($_FILES['file']['name']) || (!empty($_FILES['files']) && is_array($_FILES['files']['name']) && !empty($_FILES['files']['name'][0]));
//     if ($has_file_upload) {
//         if (!isset($status) || (isset($status) && $status === 'Pending')) {
//             $data['status'] = 'Submitted'; // Override status to 'Submitted' if no status is specified or if status is 'Pending'
//         }
//     }

//     // Validate status (must be 'Pending', 'Submitted', 'In Review', 'Declined', or 'Finalised')
//     if (!in_array($data['status'], ['Pending', 'Submitted', 'In Review', 'Declined', 'Finalised'])) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_STATUS'
//             )));
//     }

//     // Validate sub_activity_id exists in sub_activities table
//     $this->db->where('id', $data['sub_activity_id']);
//     $sub_activity_exists = $this->db->get('sub_activities')->num_rows() > 0;

//     if (!$sub_activity_exists) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_SUB_ACTIVITY_ID'
//             )));
//     }

//     // Validate in_charge_ids (ensure all user IDs exist)
//     if (!empty($in_charge_ids_array)) {
//         $this->db->where_in('id', $in_charge_ids_array);
//         $users_exist = $this->db->get('users')->num_rows() === count($in_charge_ids_array);

//         if (!$users_exist) {
//             return $this->output
//                 ->set_content_type('application/json')
//                 ->set_status_header(400) // Bad Request
//                 ->set_output(json_encode(array(
//                     'success' => false,
//                     'message' => 'INVALID_USER_IDS_IN_IN_CHARGE'
//                 )));
//         }
//     }

//     // Validate user_id exists in users table
//     $this->db->where('id', $user_id);
//     $user_exists = $this->db->get('users')->num_rows() > 0;

//     if (!$user_exists) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_USER_ID'
//             )));
//     }

//     // Start a transaction to ensure data consistency
//     $this->db->trans_start();

//     // Insert the product into the database first to get product_id
//     $insert = $this->db->insert('sub_activity_products', $data);
//     if (!$insert) {
//         $this->db->trans_rollback();
//         log_message('error', "Failed to insert product: " . $this->db->error()['message']);
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'PRODUCT_NOT_ADDED - ' . $this->db->error()['message']
//             )));
//     }

//     $product_id = $this->db->insert_id();

//     // Handle file uploads
//     $files = [];
//     $directory = "sub_activity_products";
//     if (!file_exists($directory)) {
//         mkdir($directory, 0777, true);
//     }

//     if ($product_type['category'] === 'folder') {
//         // Handle multiple file uploads for folder products (even if no files are uploaded)
//         $result = $this->handle_multiple_file_uploads_for_sub_activity($product_id, 'files', $directory, $user_id);
//         if ($result['success'] === false) {
//             $this->db->trans_rollback();
//             log_message('error', "Multiple file upload failed: " . $result['message']);
//             return $this->output
//                 ->set_content_type('application/json')
//                 ->set_status_header(400)
//                 ->set_output(json_encode(array(
//                     'success' => false,
//                     'message' => $result['message']
//                 )));
//         }
//         $files = $result['files'];
//         $data['url'] = ''; // No URL for folders
//     } else {
//         // Handle single file upload for non-folder products
//         if (!empty($_FILES['file']['name'])) {
//             $result = $this->handle_single_file_upload_for_sub_activity('file', $directory);
//             if ($result['success'] === false) {
//                 $this->db->trans_rollback();
//                 return $this->output
//                     ->set_content_type('application/json')
//                     ->set_status_header(400)
//                     ->set_output(json_encode(array(
//                         'success' => false,
//                         'message' => $result['message']
//                     )));
//             }
//             // Update the product with the new URL and type
//             $update_data = [
//                 'url' => $result['file_url'],
//                 'type' => $result['file_extension'], // Set type as the file extension
//                 'updated_by' => $user_id,
//                 'updated_at' => date('Y-m-d H:i:s')
//             ];
//             $this->db->where('id', $product_id);
//             $this->db->update('sub_activity_products', $update_data);
//             if ($this->db->affected_rows() === 0 && $this->db->error()['code'] != 0) {
//                 $this->db->trans_rollback();
//                 log_message('error', "Failed to update product URL for product_id: $product_id");
//                 return $this->output
//                     ->set_content_type('application/json')
//                     ->set_status_header(400)
//                     ->set_output(json_encode(array(
//                         'success' => false,
//                         'message' => 'FAILED_TO_UPDATE_PRODUCT_URL'
//                     )));
//             }
//             // Update $data for response
//             $data['url'] = $result['file_url'];
//             $data['type'] = $result['file_extension'];
//             $files = []; // No files array for single files
//         }
//     }

//     // Update sub_activity status to "In Progress" if a file is uploaded
//     if ($has_file_upload) {
//         $this->db->where('id', $sub_activity_id);
//         $sub_activity = $this->db->get('sub_activities')->row_array();
//         if ($sub_activity && $sub_activity['status'] !== 'Finalised') { // Avoid overriding "Finalised" status
//             $this->db->where('id', $sub_activity_id);
//             $this->db->update('sub_activities', ['status' => 'In Progress', 'updated_by' => $user_id, 'updated_at' => date('Y-m-d H:i:s')]);
//             if ($this->db->affected_rows() === 0 && $this->db->error()['code'] != 0) {
//                 log_message('error', "Failed to update sub_activity status to In Progress for sub_activity_id: $sub_activity_id");
//             }
//         }
//     }

//     // Commit the transaction if all operations succeed
//     $this->db->trans_complete();

//     if ($this->db->trans_status() === FALSE) {
//         log_message('error', "Transaction failed: " . $this->db->error()['message']);
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'TRANSACTION_FAILED - ' . $this->db->error()['message']
//             )));
//     }
    
//     // Notification logic
//     $send_notifications = in_array($data['status'], ['Submitted', 'In Review', 'Finalised', 'Declined']);
//     if ($send_notifications && !empty($in_charge_ids_array)) {
//         $this->load->library('phpmailer_lib');
//         $mail = $this->phpmailer_lib->load();
//         $mail->isSMTP();
//         $mail->Host = 'smarthub.ovalspace.co';
//         $mail->SMTPAuth = true;
//         $mail->Username = 'notifications@smarthub.ovalspace.co';
//         $mail->Password = 'wgw6.)O7sCTy';
//         $mail->SMTPSecure = 'ssl';
//         $mail->Port = 465;
//         $mail->setFrom('notifications@smarthub.ovalspace.co', 'SmartHub Notification');
//         $mail->isHTML(true);

//         // Fetch sub-activity and parent activity details
//         $this->db->select('sa.name as sub_activity_name, sa.parent_activity_id, a.name as activity_name, o.quarter_id, q.quarter, q.year_id, y.year, p.code as programme_code');
//         $this->db->from('sub_activities sa');
//         $this->db->join('activities a', 'sa.parent_activity_id = a.id', 'left');
//         $this->db->join('outcomes o', 'a.outcome_id = o.id', 'left');
//         $this->db->join('quarters q', 'o.quarter_id = q.id', 'left');
//         $this->db->join('years y', 'q.year_id = y.id', 'left');
//         $this->db->join('programmes p', 'y.programme_id = p.id', 'left');
//         $this->db->where('sa.id', $sub_activity_id);
//         $activity_data = $this->db->get()->row_array();

//       $sub_activity_name = $activity_data['sub_activity_name'] ?? 'Unknown Sub-Activity';
// $target_activity_id = $activity_data['parent_activity_id'] ?? null;
// $app_link = "https://www.smarthub.ovalspace.co/ug/programmes";
// $entity_link = $target_activity_id ? $app_link . '/' . ($activity_data['programme_code'] ?? 'SDLG') . '/activities/' . ($activity_data['quarter'] ?? 'Q1') . '/' . ($activity_data['year'] ?? '2025') . '/' . $target_activity_id : $app_link;
    
//         // Fetch creator details
//         $this->db->select('first_name');
//         $this->db->where('id', $user_id);
//         $creator = $this->db->get('users')->row_array();
//         $creator_name = $creator['first_name'] ?? 'Unknown';

//         // Common email template components
//         $header = '<div style="background-color: #00A1E5; height: 15px; width: 100%;"></div>'
//             . '<div style="background-color: #FDB913; height: 5px; width: 100%;"></div>'
//             . '<div style="background-color: #ffffff; text-align: center; padding: 10px 0;">'
//             . '<img src="https://api.smarthub.ovalspace.co/files/smart-hub.png" style="height: 150px; width: auto;" alt="SmartHub Logo" />'
//             . '</div>';
//         $footer = '<div style="font-size: 10px; color: #666; text-align: center; padding: 10px; background-color: #ffffff;">'
//             . '&copy; 2025 VNG International | SmartHub<br>'
//             . '<a href="https://smarthub.ovalspace.co" style="color: #00A1E5; text-decoration: underline;">Visit SmartHub</a>'
//             . '</div>';

//         // In-charge team notification
//         $this->db->select('id, email');
//         $this->db->where_in('id', $in_charge_ids_array);
//         $team_members = $this->db->get('users')->result_array();
//         $team_emails = array_column($team_members, 'email');
//         $team_user_ids = array_column($team_members, 'id');

//         if (!empty($team_emails)) {
//             foreach ($team_emails as $email) {
//                 $mail->addAddress($email);
//             }

//             $notification_type = 'SUB_ACTIVITY_PRODUCT_CREATION';
//             $notification_title = '';
//             $notification_message = '';
//             $email_subject = '';
//             $email_body = '';
//             $email_alt_body = '';

//             switch ($data['status']) {
//                 case 'Submitted':
//                     $notification_title = 'New Sub-Activity Product Submitted';
//                     $notification_message = "A new product \"{$name}\" on sub-activity: {$sub_activity_name} has been submitted by {$creator_name}.";
//                     $email_subject = 'New Sub-Activity Product Submitted for Review';
//                     $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
//                         . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
//                         . "<tr><td>$header</td></tr>"
//                         . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
//                         . "<h2 style='color: #333; margin: 0 0 20px;'>New Sub-Activity Product Submitted for Review</h2>"
//                         . "<p style='margin: 0 0 15px;'>Dear Team,</p>"
//                         . "<p style='margin: 0 0 15px;'>A new product, \"<strong>" . htmlspecialchars($name) . "</strong>\" on sub-activity: "
//                         . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($sub_activity_name) . "</a>, "
//                         . "has been submitted by <strong>" . htmlspecialchars($creator_name) . "</strong>.</p>"
//                         . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
//                         . "</td></tr>"
//                         . "<tr><td align='center'>$footer</td></tr>"
//                         . "</table></body></html>";
//                     $email_alt_body = "Dear Team,\n\nA new product, \"{$name}\", on sub-activity: {$sub_activity_name} ($entity_link) has been submitted by {$creator_name}.\n\nRegards,\nSmartHub";
//                     break;

//                 case 'In Review':
//                     $notification_title = 'New Sub-Activity Product In Review';
//                     $notification_message = "A new product \"{$name}\" on sub-activity: {$sub_activity_name} is in review by {$creator_name}.";
//                     $email_subject = 'New Sub-Activity Product In Review';
//                     $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
//                         . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
//                         . "<tr><td>$header</td></tr>"
//                         . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
//                         . "<h2 style='color: #333; margin: 0 0 20px;'>New Sub-Activity Product In Review</h2>"
//                         . "<p style='margin: 0 0 15px;'>Dear Team,</p>"
//                         . "<p style='margin: 0 0 15px;'>A new product, \"<strong>" . htmlspecialchars($name) . "</strong>\" on sub-activity: "
//                         . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($sub_activity_name) . "</a>, "
//                         . "is in review by <strong>" . htmlspecialchars($creator_name) . "</strong>.</p>"
//                         . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
//                         . "</td></tr>"
//                         . "<tr><td align='center'>$footer</td></tr>"
//                         . "</table></body></html>";
//                     $email_alt_body = "Dear Team,\n\nA new product, \"{$name}\", on sub-activity: {$sub_activity_name} ($entity_link) is in review by {$creator_name}.\n\nRegards,\nSmartHub";
//                     break;

//                 case 'Finalised':
//                     $notification_title = 'New Sub-Activity Product Finalised';
//                     $notification_message = "A new product \"{$name}\" on sub-activity: {$sub_activity_name} has been finalised by {$creator_name}.";
//                     $email_subject = 'New Sub-Activity Product Finalised';
//                     $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
//                         . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
//                         . "<tr><td>$header</td></tr>"
//                         . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
//                         . "<h2 style='color: #333; margin: 0 0 20px;'>New Sub-Activity Product Finalised</h2>"
//                         . "<p style='margin: 0 0 15px;'>Dear Team,</p>"
//                         . "<p style='margin: 0 0 15px;'>A new product, \"<strong>" . htmlspecialchars($name) . "</strong>\" on sub-activity: "
//                         . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($sub_activity_name) . "</a>, "
//                         . "has been finalised by <strong>" . htmlspecialchars($creator_name) . "</strong>.</p>"
//                         . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
//                         . "</td></tr>"
//                         . "<tr><td align='center'>$footer</td></tr>"
//                         . "</table></body></html>";
//                     $email_alt_body = "Dear Team,\n\nA new product, \"{$name}\", on sub-activity: {$sub_activity_name} ($entity_link) has been finalised by {$creator_name}.\n\nRegards,\nSmartHub";
//                     break;

//                 case 'Declined':
//                 $decline_reason = $this->input->post('decline_reason') ?? 'No reason provided';
//                 $notification_title = 'Sub-Activity Product Declined';
//                 $notification_message = "The product \"" . ($data['name'] ?? $product['name']) . "\" on sub-activity: " . $sub_activity_name . " has been declined by " . $updater_name . ". Reason: " . $decline_reason;
//                 $email_subject = 'Sub-Activity Product Declined';
//                 $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
//                     . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
//                     . "<tr><td>$header</td></tr>"
//                     . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
//                     . "<h2 style='color: #333; margin: 0 0 20px;'>Sub-Activity Product Declined</h2>"
//                     . "<p style='margin: 0 0 15px;'>Dear Sam and Racheal,</p>"
//                     . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($data['name'] ?? $product['name']) . "</strong>\" on sub-activity: "
//                     . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($sub_activity_name) . "</a>, "
//                     . "has been declined by <strong>" . htmlspecialchars($updater_name) . "</strong>.</p>"
//                     . "<div style='background-color: #f8f8f8; border-left: 4px solid #FDB913; padding: 15px; margin: 20px 0; border-radius: 4px;'>"
//                     . "<p style='color: #333; margin: 0; font-weight: bold;'>Reason for Decline:</p>"
//                     . "<p style='color: #333; line-height: 1.6; margin: 10px 0 0;'>" . $decline_reason . "</p>"
//                     . "</div>"
//                     . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
//                     . "</td></tr>"
//                     . "<tr><td align='center'>$footer</td></tr>"
//                     . "</table></body></html>";
//                 $email_alt_body = "Dear Sam and Racheal,\n\nThe product, \"" . ($data['name'] ?? $product['name']) . "\", on sub-activity: " . $sub_activity_name . " (" . $entity_link . ") has been declined by " . $updater_name . ".\n\nReason: " . strip_tags($decline_reason) . "\n\nRegards,\nSmartHub";
//                 break;
//             }

//             // Store notifications for team
//             foreach ($team_user_ids as $team_user_id) {
//                 $this->db->insert('notifications', [
//                     'user_id' => $team_user_id,
//                     'type' => $notification_type,
//                     'title' => $notification_title,
//                     'message' => $notification_message,
//                     'link' => $entity_link,
//                     'is_read' => 0,
//                     'created_by' => $user_id
//                 ]);
//             }

//             // Send email to team
//             $mail->Subject = $email_subject;
//             $mail->Body = $email_body;
//             $mail->AltBody = $email_alt_body;
//             if (!$mail->send()) {
//                 log_message('error', 'Failed to send email to in-charge team: ' . $mail->ErrorInfo);
//             }
//             $mail->clearAddresses();
//         }

//         // Admin notification
//          $admin_emails = ['sam.ejibua@vng.nl','racheal.atukwase@vngi.org']; // Replace with actual admin emails
//         $this->db->select('id')->where_in('email', $admin_emails);
//         $admin_users = $this->db->get('users')->result_array();
//         $admin_user_ids = array_column($admin_users, 'id');

//         foreach ($admin_emails as $email) {
//             $mail->addAddress($email);
//         }

//         $notification_type = 'SUB_ACTIVITY_PRODUCT_CREATION';
//         $notification_title = '';
//         $notification_message = '';
//         $email_subject = '';
//         $email_body = '';
//         $email_alt_body = '';

//         switch ($data['status']) {
//             case 'Submitted':
//                 $notification_title = 'New Sub-Activity Product Submitted';
//                 $notification_message = "A new product \"{$name}\" on sub-activity: {$sub_activity_name} has been submitted by {$creator_name} for review.";
//                 $email_subject = 'New Sub-Activity Product Submitted for Review/Approval';
//                 $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
//                     . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
//                     . "<tr><td>$header</td></tr>"
//                     . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
//                     . "<h2 style='color: #333; margin: 0 0 20px;'>New Sub-Activity Product Submitted for Review/Approval</h2>"
//                     . "<p style='margin: 0 0 15px;'>Dear Sam and Racheal,</p>"
//                     . "<p style='margin: 0 0 15px;'>A new product, \"<strong>" . htmlspecialchars($name) . "</strong>\" on sub-activity: "
//                     . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($sub_activity_name) . "</a>, "
//                     . "has been submitted by <strong>" . htmlspecialchars($creator_name) . "</strong> for review/approval.</p>"
//                     . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
//                     . "</td></tr>"
//                     . "<tr><td align='center'>$footer</td></tr>"
//                     . "</table></body></html>";
//                 $email_alt_body = "Dear Sam and Racheal,\n\nA new product, \"{$name}\", on sub-activity: {$sub_activity_name} ($entity_link) has been submitted by {$creator_name} for review/approval.\n\nRegards,\nSmartHub";
//                 break;

//             case 'In Review':
//                 $notification_title = 'New Sub-Activity Product In Review';
//                 $notification_message = "A new product \"{$name}\" on sub-activity: {$sub_activity_name} is in review by {$creator_name}.";
//                 $email_subject = 'New Sub-Activity Product In Review';
//                 $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
//                     . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
//                     . "<tr><td>$header</td></tr>"
//                     . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
//                     . "<h2 style='color: #333; margin: 0 0 20px;'>New Sub-Activity Product In Review</h2>"
//                     . "<p style='margin: 0 0 15px;'>Dear Sam and Racheal,</p>"
//                     . "<p style='margin: 0 0 15px;'>A new product, \"<strong>" . htmlspecialchars($name) . "</strong>\" on sub-activity: "
//                     . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($sub_activity_name) . "</a>, "
//                     . "is in review by <strong>" . htmlspecialchars($creator_name) . "</strong>.</p>"
//                     . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
//                     . "</td></tr>"
//                     . "<tr><td align='center'>$footer</td></tr>"
//                     . "</table></body></html>";
//                 $email_alt_body = "Dear Sam and Racheal,\n\nA new product, \"{$name}\", on sub-activity: {$sub_activity_name} ($entity_link) is in review by {$creator_name}.\n\nRegards,\nSmartHub";
//                 break;

//             case 'Finalised':
//                 $notification_title = 'New Sub-Activity Product Finalised';
//                 $notification_message = "A new product \"{$name}\" on sub-activity: {$sub_activity_name} has been finalised by {$creator_name}.";
//                 $email_subject = 'New Sub-Activity Product Finalised';
//                 $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
//                     . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
//                     . "<tr><td>$header</td></tr>"
//                     . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
//                     . "<h2 style='color: #333; margin: 0 0 20px;'>New Sub-Activity Product Finalised</h2>"
//                     . "<p style='margin: 0 0 15px;'>Dear Sam and Racheal,</p>"
//                     . "<p style='margin: 0 0 15px;'>A new product, \"<strong>" . htmlspecialchars($name) . "</strong>\" on sub-activity: "
//                     . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($sub_activity_name) . "</a>, "
//                     . "has been finalised by <strong>" . htmlspecialchars($creator_name) . "</strong>.</p>"
//                     . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
//                     . "</td></tr>"
//                     . "<tr><td align='center'>$footer</td></tr>"
//                     . "</table></body></html>";
//                 $email_alt_body = "Dear Sam and Racheal,\n\nA new product, \"{$name}\", on sub-activity: {$sub_activity_name} ($entity_link) has been finalised by {$creator_name}.\n\nRegards,\nSmartHub";
//                 break;

//             case 'Declined':
//                 $decline_reason = $this->input->post('decline_reason') ?? 'No reason provided';
//                 $notification_title = 'New Sub-Activity Product Declined';
//                 $notification_message = "A new product \"{$name}\" on sub-activity: {$sub_activity_name} has been declined by {$creator_name}. Reason: " . strip_tags($decline_reason);
//                 $email_subject = 'New Sub-Activity Product Declined';
//                 $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
//                     . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
//                     . "<tr><td>$header</td></tr>"
//                     . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
//                     . "<h2 style='color: #333; margin: 0 0 20px;'>New Sub-Activity Product Declined</h2>"
//                     . "<p style='margin: 0 0 15px;'>Dear Sam and Racheal,</p>"
//                     . "<p style='margin: 0 0 15px;'>A new product, \"<strong>" . htmlspecialchars($name) . "</strong>\" on sub-activity: "
//                     . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($sub_activity_name) . "</a>, "
//                     . "has been declined by <strong>" . htmlspecialchars($creator_name) . "</strong>.</p>"
//                     . "<div style='background-color: #f8f8f8; border-left: 4px solid #FDB913; padding: 15px; margin: 20px 0; border-radius: 4px;'>"
//                     . "<p style='color: #333; margin: 0; font-weight: bold;'>Reason for Decline:</p>"
//                     . "<p style='color: #333; line-height: 1.6; margin: 10px 0 0;'>" . htmlspecialchars($decline_reason) . "</p>"
//                     . "</div>"
//                     . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
//                     . "</td></tr>"
//                     . "<tr><td align='center'>$footer</td></tr>"
//                     . "</table></body></html>";
//                 $email_alt_body = "Dear Sam and Racheal,\n\nA new product, \"{$name}\", on sub-activity: {$sub_activity_name} ($entity_link) has been declined by {$creator_name}.\n\nReason: " . strip_tags($decline_reason) . "\n\nRegards,\nSmartHub";
//                 break;
//         }

//         // Store notifications for admins
//         foreach ($admin_user_ids as $admin_user_id) {
//             $this->db->insert('notifications', [
//                 'user_id' => $admin_user_id,
//                 'type' => $notification_type,
//                 'title' => $notification_title,
//                 'message' => $notification_message,
//                 'link' => $entity_link,
//                 'is_read' => 0,
//                 'created_by' => $user_id
//             ]);
//         }

//         // Send email to admins
//         $mail->Subject = $email_subject;
//         $mail->Body = $email_body;
//         $mail->AltBody = $email_alt_body;
//         if (!$mail->send()) {
//             log_message('error', 'Failed to send email to admins: ' . $mail->ErrorInfo);
//         }
//     }

//     // Fetch in_charge details and files for response
//     $in_charge_details = [];
//     if (!empty($in_charge_ids_array)) {
//         $this->db->select('id, first_name, image as avatar');
//         $this->db->where_in('id', $in_charge_ids_array);
//         $users = $this->db->get('users')->result_array();
//         foreach ($users as $user) {
//             $in_charge_details[] = [
//                 'id' => $user['id'],
//                 'first_name' => $user['first_name'],
//                 'avatar' => $user['avatar']
//             ];
//         }
//     }

//     $product_files = [];
//     if ($product_type['category'] === 'folder') {
//         $this->db->where('product_id', $product_id);
//         $files_data = $this->db->get('sub_activity_product_files')->result_array();
//         foreach ($files_data as $file) {
//             $product_files[] = [
//                 'id' => $file['id'],
//                 'name' => $file['name'],
//                 'type' => $file['type'],
//                 'url' => $file['url'],
//                 'date' => $file['date'],
//                 'size' => $file['size']
//             ];
//         }
//     }

//     $response_data = [
//         'success' => true,
//         'message' => 'PRODUCT_ADDED_SUCCESSFULLY',
//         'data' => [
//             'id' => $product_id,
//             'type' => $data['type'],
//             'name' => $data['name'],
//             'url' => $data['url'],
//             'inCharge' => $in_charge_details,
//             'status' => $data['status'],
//             'dateSubmitted' => $data['date_submitted'],
//             'lastUpdated' => $data['last_updated']
//         ]
//     ];

//     // Only include 'files' if category is 'folder'
//     if ($product_type['category'] === 'folder') {
//         $response_data['data']['files'] = $product_files;
//     }

//     return $this->output
//         ->set_content_type('application/json')
//         ->set_status_header(201) // Created
//         ->set_output(json_encode($response_data));
// }

// updates the parent activity's status on file upload
public function create_product()
{
    // Get form data
    $sub_activity_id = $this->input->post('sub_activity_id');
    $name = $this->input->post('name');
    $prod_type = $this->input->post('prod_type'); // ID from product_types
    $status = $this->input->post('status');
    $date_submitted = $this->input->post('date_submitted');
    $last_updated = $this->input->post('last_updated');
    $in_charge_ids = $this->input->post('in_charge_ids'); // Raw input, could be "[9]" or "9,10"
    $user_id = $this->input->post('user_id'); // Assuming user_id is passed in the form
    $group = $this->input->post('group') ?? 'general'; // Default to 'general'
    $output_id = $this->input->post('output_id'); // Nullable for output products
    $is_urgent = $this->input->post('isUrgent');

    // Validate required fields
    if (empty($sub_activity_id) || empty($prod_type) || empty($user_id)) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400) // Bad Request
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'INVALID_INPUT'
            )));
    }

    // Validate group (must be 'general' or 'output')
    if (!in_array($group, ['general', 'output'])) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400) // Bad Request
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'INVALID_GROUP'
            )));
    }

    // If group is 'output', output_id must be provided and valid
    if ($group === 'output' && empty($output_id)) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400) // Bad Request
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'OUTPUT_ID_REQUIRED_FOR_OUTPUT_PRODUCT'
            )));
    }

    // Validate output_id if provided
    if ($output_id) {
        $this->db->where('id', $output_id);
        $output_exists = $this->db->get('sub_activity_outputs')->num_rows() > 0;
        if (!$output_exists) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(400) // Bad Request
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => 'INVALID_OUTPUT_ID'
                )));
        }
    }

    // Validate prod_type exists and get its category
    $this->db->where('id', $prod_type);
    $product_type = $this->db->get('product_types')->row_array();
    
    $name = empty($name) ? $product_type['name'] : $name;

    if (empty($product_type)) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400) // Bad Request
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'INVALID_PROD_TYPE'
            )));
    }

    // Determine type based on product_type category
    $type = ($product_type['category'] === 'folder') ? 'folder' : 'docx';

    // Parse in_charge_ids (handle string like "[9]" or "9,10")
    $in_charge_ids_array = [];
    if (!empty($in_charge_ids)) {
        // Try to decode as JSON (e.g., "[9]" -> [9])
        $parsed_ids = json_decode($in_charge_ids, true);
        if (is_array($parsed_ids)) {
            $in_charge_ids_array = array_filter(array_map('intval', $parsed_ids)); // Convert to integers, remove empty
        } else {
            // If not JSON, split by comma (e.g., "9,10" -> [9, 10])
            $ids = explode(',', str_replace(['[', ']', '"'], '', $in_charge_ids));
            $in_charge_ids_array = array_filter(array_map('trim', $ids), 'strlen'); // Clean and filter empty values
            $in_charge_ids_array = array_map('intval', $in_charge_ids_array); // Convert to integers
        }
    }

    // Prepare data for insertion (initial setup)
    $data = array(
        'sub_activity_id' => $sub_activity_id,
        'name' => $name,
        'type' => $type, // Set to 'folder' or 'docx' based on category (will be updated for single files)
        'url' => '', // Will be set for single files or left empty for folders
        'status' => $status ? $status : 'Pending', // Default to 'Pending' if not specified
        'isUrgent'=>$is_urgent,
        'date_submitted' => $date_submitted ? date('Y-m-d', strtotime($date_submitted)) : date('Y-m-d'),
        'last_updated' => $last_updated ? date('Y-m-d', strtotime($last_updated)) : date('Y-m-d'),
        'in_charge_ids' => !empty($in_charge_ids_array) ? json_encode($in_charge_ids_array) : json_encode([]),
        'prod_type' => $prod_type,
        'group' => $group,
        'output_id' => $group === 'output' ? $output_id : NULL,
        'created_by' => $user_id,
        'updated_by' => $user_id
    );

    // Check if a file is uploaded and update status to 'Submitted' if status is 'Pending' or not specified
    $has_file_upload = !empty($_FILES['file']['name']) || (!empty($_FILES['files']) && is_array($_FILES['files']['name']) && !empty($_FILES['files']['name'][0]));
    if ($has_file_upload) {
        if (!isset($status) || (isset($status) && $status === 'Pending')) {
            $data['status'] = 'Submitted'; // Override status to 'Submitted' if no status is specified or if status is 'Pending'
        }
    }

    // Validate status (must be 'Pending', 'Submitted', 'In Review', 'Declined', or 'Finalised')
    if (!in_array($data['status'], ['Pending', 'Submitted', 'In Review', 'Declined', 'Finalised'])) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400) // Bad Request
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'INVALID_STATUS'
            )));
    }

    // Validate sub_activity_id exists in sub_activities table
    $this->db->where('id', $data['sub_activity_id']);
    $sub_activity_exists = $this->db->get('sub_activities')->num_rows() > 0;

    if (!$sub_activity_exists) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400) // Bad Request
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'INVALID_SUB_ACTIVITY_ID'
            )));
    }

    // Validate in_charge_ids (ensure all user IDs exist)
    if (!empty($in_charge_ids_array)) {
        $this->db->where_in('id', $in_charge_ids_array);
        $users_exist = $this->db->get('users')->num_rows() === count($in_charge_ids_array);

        if (!$users_exist) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(400) // Bad Request
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => 'INVALID_USER_IDS_IN_IN_CHARGE'
                )));
        }
    }

    // Validate user_id exists in users table
    $this->db->where('id', $user_id);
    $user_exists = $this->db->get('users')->num_rows() > 0;

    if (!$user_exists) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400) // Bad Request
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'INVALID_USER_ID'
            )));
    }

    // Start a transaction to ensure data consistency
    $this->db->trans_start();

    // Insert the product into the database first to get product_id
    $insert = $this->db->insert('sub_activity_products', $data);
    if (!$insert) {
        $this->db->trans_rollback();
        log_message('error', "Failed to insert product: " . $this->db->error()['message']);
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400) // Bad Request
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'PRODUCT_NOT_ADDED - ' . $this->db->error()['message']
            )));
    }

    $product_id = $this->db->insert_id();

    // Handle file uploads
    $files = [];
    $directory = "sub_activity_products";
    if (!file_exists($directory)) {
        mkdir($directory, 0777, true);
    }

    if ($product_type['category'] === 'folder') {
        // Handle multiple file uploads for folder products (even if no files are uploaded)
        $result = $this->handle_multiple_file_uploads_for_sub_activity($product_id, 'files', $directory, $user_id);
        if ($result['success'] === false) {
            $this->db->trans_rollback();
            log_message('error', "Multiple file upload failed: " . $result['message']);
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(400)
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => $result['message']
                )));
        }
        $files = $result['files'];
        $data['url'] = ''; // No URL for folders
    } else {
        // Handle single file upload for non-folder products
        if (!empty($_FILES['file']['name'])) {
            $result = $this->handle_single_file_upload_for_sub_activity('file', $directory);
            if ($result['success'] === false) {
                $this->db->trans_rollback();
                return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(400)
                    ->set_output(json_encode(array(
                        'success' => false,
                        'message' => $result['message']
                    )));
            }
            // Update the product with the new URL and type
            $update_data = [
                'url' => $result['file_url'],
                'type' => $result['file_extension'], // Set type as the file extension
                'updated_by' => $user_id,
                'updated_at' => date('Y-m-d H:i:s')
            ];
            $this->db->where('id', $product_id);
            $this->db->update('sub_activity_products', $update_data);
            if ($this->db->affected_rows() === 0 && $this->db->error()['code'] != 0) {
                $this->db->trans_rollback();
                log_message('error', "Failed to update product URL for product_id: $product_id");
                return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(400)
                    ->set_output(json_encode(array(
                        'success' => false,
                        'message' => 'FAILED_TO_UPDATE_PRODUCT_URL'
                    )));
            }
            // Update $data for response
            $data['url'] = $result['file_url'];
            $data['type'] = $result['file_extension'];
            $files = []; // No files array for single files
        }
    }

    // Update sub_activity and parent activity status to "In Progress" if a file is uploaded
    if ($has_file_upload) {
        // Update sub-activity status
        $this->db->where('id', $sub_activity_id);
        $sub_activity = $this->db->get('sub_activities')->row_array();
        if ($sub_activity && $sub_activity['status'] !== 'Finalised') { // Avoid overriding "Finalised" status
            $this->db->where('id', $sub_activity_id);
            $this->db->update('sub_activities', [
                'status' => 'In Progress',
                'updated_by' => $user_id,
                'updated_at' => date('Y-m-d H:i:s')
            ]);
            if ($this->db->affected_rows() === 0 && $this->db->error()['code'] != 0) {
                log_message('error', "Failed to update sub_activity status to In Progress for sub_activity_id: $sub_activity_id");
            }
        }

        // Update parent activity status
        if ($sub_activity && !empty($sub_activity['parent_activity_id'])) {
            $parent_activity_id = $sub_activity['parent_activity_id'];
            $this->db->where('id', $parent_activity_id);
            $parent_activity = $this->db->get('activities')->row_array();
            if ($parent_activity && $parent_activity['status'] !== 'Finalised') { // Avoid overriding "Finalised" status
                $this->db->where('id', $parent_activity_id);
                $this->db->update('activities', [
                    'status' => 'In Progress',
                    'updated_by' => $user_id,
                    'updated_at' => date('Y-m-d H:i:s')
                ]);
                if ($this->db->affected_rows() === 0 && $this->db->error()['code'] != 0) {
                    log_message('error', "Failed to update parent activity status to In Progress for activity_id: $parent_activity_id");
                }
            }
        }
    }

    // Commit the transaction if all operations succeed
    $this->db->trans_complete();

    if ($this->db->trans_status() === FALSE) {
        log_message('error', "Transaction failed: " . $this->db->error()['message']);
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400) // Bad Request
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'TRANSACTION_FAILED - ' . $this->db->error()['message']
            )));
    }
    
    // Notification logic
    $send_notifications = in_array($data['status'], ['Submitted', 'In Review', 'Finalised', 'Declined']);
    if ($send_notifications && !empty($in_charge_ids_array)) {
        $this->load->library('phpmailer_lib');
        $mail = $this->phpmailer_lib->load();
        $mail->isSMTP();
        $mail->Host = 'smarthub.ovalspace.co';
        $mail->SMTPAuth = true;
        $mail->Username = 'notifications@smarthub.ovalspace.co';
        $mail->Password = 'wgw6.)O7sCTy';
        $mail->SMTPSecure = 'ssl';
        $mail->Port = 465;
        $mail->setFrom('notifications@smarthub.ovalspace.co', 'SmartHub Notification');
        $mail->isHTML(true);

        // Fetch sub-activity and parent activity details
        $this->db->select('sa.name as sub_activity_name, sa.parent_activity_id, a.name as activity_name, o.quarter_id, q.quarter, q.year_id, y.year, p.code as programme_code');
        $this->db->from('sub_activities sa');
        $this->db->join('activities a', 'sa.parent_activity_id = a.id', 'left');
        $this->db->join('outcomes o', 'a.outcome_id = o.id', 'left');
        $this->db->join('quarters q', 'o.quarter_id = q.id', 'left');
        $this->db->join('years y', 'q.year_id = y.id', 'left');
        $this->db->join('programmes p', 'y.programme_id = p.id', 'left');
        $this->db->where('sa.id', $sub_activity_id);
        $activity_data = $this->db->get()->row_array();

        $sub_activity_name = $activity_data['sub_activity_name'] ?? 'Unknown Sub-Activity';
        $target_activity_id = $activity_data['parent_activity_id'] ?? null;
        $app_link = "https://www.smarthub.ovalspace.co/ug/programmes";
        $entity_link = $target_activity_id ? $app_link . '/' . ($activity_data['programme_code'] ?? 'SDLG') . '/activities/' . ($activity_data['quarter'] ?? 'Q1') . '/' . ($activity_data['year'] ?? '2025') . '/' . $target_activity_id : $app_link;
    
        // Fetch creator details
        $this->db->select('first_name');
        $this->db->where('id', $user_id);
        $creator = $this->db->get('users')->row_array();
        $creator_name = $creator['first_name'] ?? 'Unknown';

        // Common email template components
        $header = '<div style="background-color: #00A1E5; height: 15px; width: 100%;"></div>'
            . '<div style="background-color: #FDB913; height: 5px; width: 100%;"></div>'
            . '<div style="background-color: #ffffff; text-align: center; padding: 10px 0;">'
            . '<img src="https://api.smarthub.ovalspace.co/files/smart-hub.png" style="height: 150px; width: auto;" alt="SmartHub Logo" />'
            . '</div>';
        $footer = '<div style="font-size: 10px; color: #666; text-align: center; padding: 10px; background-color: #ffffff;">'
            . '&copy; 2025 VNG International | SmartHub<br>'
            . '<a href="https://smarthub.ovalspace.co" style="color: #00A1E5; text-decoration: underline;">Visit SmartHub</a>'
            . '</div>';

        // In-charge team notification
        $this->db->select('id, email');
        $this->db->where_in('id', $in_charge_ids_array);
        $team_members = $this->db->get('users')->result_array();
        $team_emails = array_column($team_members, 'email');
        $team_user_ids = array_column($team_members, 'id');

        if (!empty($team_emails)) {
            foreach ($team_emails as $email) {
                // $mail->addAddress($email);
                $mail->addAddress('kimbowaandrew@gmail.com');
            }

            $notification_type = 'SUB_ACTIVITY_PRODUCT_CREATION';
            $notification_title = '';
            $notification_message = '';
            $email_subject = '';
            $email_body = '';
            $email_alt_body = '';

            switch ($data['status']) {
                case 'Submitted':
                    $notification_title = 'New Sub-Activity Product Submitted';
                    $notification_message = "A new product \"{$name}\" on sub-activity: {$sub_activity_name} has been submitted by {$creator_name}.";
                    $email_subject = 'New Sub-Activity Product Submitted for Review';
                    $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
                        . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
                        . "<tr><td>$header</td></tr>"
                        . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
                        . "<h2 style='color: #333; margin: 0 0 20px;'>New Sub-Activity Product Submitted for Review</h2>"
                        . "<p style='margin: 0 0 15px;'>Dear Team,</p>"
                        . "<p style='margin: 0 0 15px;'>A new product, \"<strong>" . htmlspecialchars($name) . "</strong>\" on sub-activity: "
                        . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($sub_activity_name) . "</a>, "
                        . "has been submitted by <strong>" . htmlspecialchars($creator_name) . "</strong>.</p>"
                        . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
                        . "</td></tr>"
                        . "<tr><td align='center'>$footer</td></tr>"
                        . "</table></body></html>";
                    $email_alt_body = "Dear Team,\n\nA new product, \"{$name}\", on sub-activity: {$sub_activity_name} ($entity_link) has been submitted by {$creator_name}.\n\nRegards,\nSmartHub";
                    break;

                case 'In Review':
                    $notification_title = 'New Sub-Activity Product In Review';
                    $notification_message = "A new product \"{$name}\" on sub-activity: {$sub_activity_name} is in review by {$creator_name}.";
                    $email_subject = 'New Sub-Activity Product In Review';
                    $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
                        . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
                        . "<tr><td>$header</td></tr>"
                        . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
                        . "<h2 style='color: #333; margin: 0 0 20px;'>New Sub-Activity Product In Review</h2>"
                        . "<p style='margin: 0 0 15px;'>Dear Team,</p>"
                        . "<p style='margin: 0 0 15px;'>A new product, \"<strong>" . htmlspecialchars($name) . "</strong>\" on sub-activity: "
                        . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($sub_activity_name) . "</a>, "
                        . "is in review by <strong>" . htmlspecialchars($creator_name) . "</strong>.</p>"
                        . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
                        . "</td></tr>"
                        . "<tr><td align='center'>$footer</td></tr>"
                        . "</table></body></html>";
                    $email_alt_body = "Dear Team,\n\nA new product, \"{$name}\", on sub-activity: {$sub_activity_name} ($entity_link) is in review by {$creator_name}.\n\nRegards,\nSmartHub";
                    break;

                case 'Finalised':
                    $notification_title = 'New Sub-Activity Product Finalised';
                    $notification_message = "A new product \"{$name}\" on sub-activity: {$sub_activity_name} has been finalised by {$creator_name}.";
                    $email_subject = 'New Sub-Activity Product Finalised';
                    $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
                        . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
                        . "<tr><td>$header</td></tr>"
                        . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
                        . "<h2 style='color: #333; margin: 0 0 20px;'>New Sub-Activity Product Finalised</h2>"
                        . "<p style='margin: 0 0 15px;'>Dear Team,</p>"
                        . "<p style='margin: 0 0 15px;'>A new product, \"<strong>" . htmlspecialchars($name) . "</strong>\" on sub-activity: "
                        . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($sub_activity_name) . "</a>, "
                        . "has been finalised by <strong>" . htmlspecialchars($creator_name) . "</strong>.</p>"
                        . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
                        . "</td></tr>"
                        . "<tr><td align='center'>$footer</td></tr>"
                        . "</table></body></html>";
                    $email_alt_body = "Dear Team,\n\nA new product, \"{$name}\", on sub-activity: {$sub_activity_name} ($entity_link) has been finalised by {$creator_name}.\n\nRegards,\nSmartHub";
                    break;

                case 'Declined':
                    $decline_reason = $this->input->post('decline_reason') ?? 'No reason provided';
                    $notification_title = 'Sub-Activity Product Declined';
                    $notification_message = "The product \"" . ($data['name'] ?? $product['name']) . "\" on sub-activity: " . $sub_activity_name . " has been declined by " . $updater_name . ". Reason: " . $decline_reason;
                    $email_subject = 'Sub-Activity Product Declined';
                    $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
                        . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
                        . "<tr><td>$header</td></tr>"
                        . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
                        . "<h2 style='color: #333; margin: 0 0 20px;'>Sub-Activity Product Declined</h2>"
                        . "<p style='margin: 0 0 15px;'>Dear Sam and Racheal,</p>"
                        . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($data['name'] ?? $product['name']) . "</strong>\" on sub-activity: "
                        . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($sub_activity_name) . "</a>, "
                        . "has been declined by <strong>" . htmlspecialchars($updater_name) . "</strong>.</p>"
                        . "<div style='background-color: #f8f8f8; border-left: 4px solid #FDB913; padding: 15px; margin: 20px 0; border-radius: 4px;'>"
                        . "<p style='color: #333; margin: 0; font-weight: bold;'>Reason for Decline:</p>"
                        . "<p style='color: #333; line-height: 1.6; margin: 10px 0 0;'>" . $decline_reason . "</p>"
                        . "</div>"
                        . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
                        . "</td></tr>"
                        . "<tr><td align='center'>$footer</td></tr>"
                        . "</table></body></html>";
                    $email_alt_body = "Dear Sam and Racheal,\n\nThe product, \"" . ($data['name'] ?? $product['name']) . "\", on sub-activity: " . $sub_activity_name . " (" . $entity_link . ") has been declined by " . $updater_name . ".\n\nReason: " . strip_tags($decline_reason) . "\n\nRegards,\nSmartHub";
                    break;
            }

            // Store notifications for team
            foreach ($team_user_ids as $team_user_id) {
                $this->db->insert('notifications', [
                    'user_id' => $team_user_id,
                    'type' => $notification_type,
                    'title' => $notification_title,
                    'message' => $notification_message,
                    'link' => $entity_link,
                    'is_read' => 0,
                    'created_by' => $user_id
                ]);
            }

            // Send email to team
            $mail->Subject = $email_subject;
            $mail->Body = $email_body;
            $mail->AltBody = $email_alt_body;
            if (!$mail->send()) {
                log_message('error', 'Failed to send email to in-charge team: ' . $mail->ErrorInfo);
            }
            $mail->clearAddresses();
        }

        // Admin notification
        $admin_emails = ['sam.ejibua@vng.nl','racheal.atukwase@vngi.org']; // Replace with actual admin emails
        // $admin_emails = ['kimbowaandrew@gmail.com']; 
        $this->db->select('id')->where_in('email', $admin_emails);
        $admin_users = $this->db->get('users')->result_array();
        $admin_user_ids = array_column($admin_users, 'id');

        foreach ($admin_emails as $email) {
            $mail->addAddress($email);
        }

        $notification_type = 'SUB_ACTIVITY_PRODUCT_CREATION';
        $notification_title = '';
        $notification_message = '';
        $email_subject = '';
        $email_body = '';
        $email_alt_body = '';

        switch ($data['status']) {
            case 'Submitted':
                $notification_title = 'New Sub-Activity Product Submitted';
                $notification_message = "A new product \"{$name}\" on sub-activity: {$sub_activity_name} has been submitted by {$creator_name} for review.";
                $email_subject = 'New Sub-Activity Product Submitted for Review/Approval';
                $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
                    . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
                    . "<tr><td>$header</td></tr>"
                    . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
                    . "<h2 style='color: #333; margin: 0 0 20px;'>New Sub-Activity Product Submitted for Review/Approval</h2>"
                    . "<p style='margin: 0 0 15px;'>Dear Sam and Racheal,</p>"
                    . "<p style='margin: 0 0 15px;'>A new product, \"<strong>" . htmlspecialchars($name) . "</strong>\" on sub-activity: "
                    . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($sub_activity_name) . "</a>, "
                    . "has been submitted by <strong>" . htmlspecialchars($creator_name) . "</strong> for review/approval.</p>"
                    . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
                    . "</td></tr>"
                    . "<tr><td align='center'>$footer</td></tr>"
                    . "</table></body></html>";
                $email_alt_body = "Dear Sam and Racheal,\n\nA new product, \"{$name}\", on sub-activity: {$sub_activity_name} ($entity_link) has been submitted by {$creator_name} for review/approval.\n\nRegards,\nSmartHub";
                break;

            case 'In Review':
                $notification_title = 'New Sub-Activity Product In Review';
                $notification_message = "A new product \"{$name}\" on sub-activity: {$sub_activity_name} is in review by {$creator_name}.";
                $email_subject = 'New Sub-Activity Product In Review';
                $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
                    . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
                    . "<tr><td>$header</td></tr>"
                    . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
                    . "<h2 style='color: #333; margin: 0 0 20px;'>New Sub-Activity Product In Review</h2>"
                    . "<p style='margin: 0 0 15px;'>Dear Sam and Racheal,</p>"
                    . "<p style='margin: 0 0 15px;'>A new product, \"<strong>" . htmlspecialchars($name) . "</strong>\" on sub-activity: "
                    . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($sub_activity_name) . "</a>, "
                    . "is in review by <strong>" . htmlspecialchars($creator_name) . "</strong>.</p>"
                    . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
                    . "</td></tr>"
                    . "<tr><td align='center'>$footer</td></tr>"
                    . "</table></body></html>";
                $email_alt_body = "Dear Sam and Racheal,\n\nA new product, \"{$name}\", on sub-activity: {$sub_activity_name} ($entity_link) is in review by {$creator_name}.\n\nRegards,\nSmartHub";
                break;

            case 'Finalised':
                $notification_title = 'New Sub-Activity Product Finalised';
                $notification_message = "A new product \"{$name}\" on sub-activity: {$sub_activity_name} has been finalised by {$creator_name}.";
                $email_subject = 'New Sub-Activity Product Finalised';
                $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
                    . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
                    . "<tr><td>$header</td></tr>"
                    . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
                    . "<h2 style='color: #333; margin: 0 0 20px;'>New Sub-Activity Product Finalised</h2>"
                    . "<p style='margin: 0 0 15px;'>Dear Sam and Racheal,</p>"
                    . "<p style='margin: 0 0 15px;'>A new product, \"<strong>" . htmlspecialchars($name) . "</strong>\" on sub-activity: "
                    . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($sub_activity_name) . "</a>, "
                    . "has been finalised by <strong>" . htmlspecialchars($creator_name) . "</strong>.</p>"
                    . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
                    . "</td></tr>"
                    . "<tr><td align='center'>$footer</td></tr>"
                    . "</table></body></html>";
                $email_alt_body = "Dear Sam and Racheal,\n\nA new product, \"{$name}\", on sub-activity: {$sub_activity_name} ($entity_link) has been finalised by {$creator_name}.\n\nRegards,\nSmartHub";
                break;

            case 'Declined':
                $decline_reason = $this->input->post('decline_reason') ?? 'No reason provided';
                $notification_title = 'New Sub-Activity Product Declined';
                $notification_message = "A new product \"{$name}\" on sub-activity: {$sub_activity_name} has been declined by {$creator_name}. Reason: " . strip_tags($decline_reason);
                $email_subject = 'New Sub-Activity Product Declined';
                $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
                    . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
                    . "<tr><td>$header</td></tr>"
                    . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
                    . "<h2 style='color: #333; margin: 0 0 20px;'>New Sub-Activity Product Declined</h2>"
                    . "<p style='margin: 0 0 15px;'>Dear Sam and Racheal,</p>"
                    . "<p style='margin: 0 0 15px;'>A new product, \"<strong>" . htmlspecialchars($name) . "</strong>\" on sub-activity: "
                    . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($sub_activity_name) . "</a>, "
                    . "has been declined by <strong>" . htmlspecialchars($creator_name) . "</strong>.</p>"
                    . "<div style='background-color: #f8f8f8; border-left: 4px solid #FDB913; padding: 15px; margin: 20px 0; border-radius: 4px;'>"
                    . "<p style='color: #333; margin: 0; font-weight: bold;'>Reason for Decline:</p>"
                    . "<p style='color: #333; line-height: 1.6; margin: 10px 0 0;'>" . htmlspecialchars($decline_reason) . "</p>"
                    . "</div>"
                    . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
                    . "</td></tr>"
                    . "<tr><td align='center'>$footer</td></tr>"
                    . "</table></body></html>";
                $email_alt_body = "Dear Sam and Racheal,\n\nA new product, \"{$name}\", on sub-activity: {$sub_activity_name} ($entity_link) has been declined by {$creator_name}.\n\nReason: " . strip_tags($decline_reason) . "\n\nRegards,\nSmartHub";
                break;
        }

        // Store notifications for admins
        foreach ($admin_user_ids as $admin_user_id) {
            $this->db->insert('notifications', [
                'user_id' => $admin_user_id,
                'type' => $notification_type,
                'title' => $notification_title,
                'message' => $notification_message,
                'link' => $entity_link,
                'is_read' => 0,
                'created_by' => $user_id
            ]);
        }

        // Send email to admins
        $mail->Subject = $email_subject;
        $mail->Body = $email_body;
        $mail->AltBody = $email_alt_body;
        if (!$mail->send()) {
            log_message('error', 'Failed to send email to admins: ' . $mail->ErrorInfo);
        }
    }

    // Fetch in_charge details and files for response
    $in_charge_details = [];
    if (!empty($in_charge_ids_array)) {
        $this->db->select('id, first_name, image as avatar');
        $this->db->where_in('id', $in_charge_ids_array);
        $users = $this->db->get('users')->result_array();
        foreach ($users as $user) {
            $in_charge_details[] = [
                'id' => $user['id'],
                'first_name' => $user['first_name'],
                'avatar' => $user['avatar']
            ];
        }
    }

    $product_files = [];
    if ($product_type['category'] === 'folder') {
        $this->db->where('product_id', $product_id);
        $files_data = $this->db->get('sub_activity_product_files')->result_array();
        foreach ($files_data as $file) {
            $product_files[] = [
                'id' => $file['id'],
                'name' => $file['name'],
                'type' => $file['type'],
                'url' => $file['url'],
                'date' => $file['date'],
                'size' => $file['size']
            ];
        }
    }

    $response_data = [
        'success' => true,
        'message' => 'PRODUCT_ADDED_SUCCESSFULLY',
        'data' => [
            'id' => $product_id,
            'type' => $data['type'],
            'name' => $data['name'],
            'url' => $data['url'],
            'inCharge' => $in_charge_details,
            'status' => $data['status'],
            'dateSubmitted' => $data['date_submitted'],
            'lastUpdated' => $data['last_updated']
        ]
    ];

    // Only include 'files' if category is 'folder'
    if ($product_type['category'] === 'folder') {
        $response_data['data']['files'] = $product_files;
    }

    return $this->output
        ->set_content_type('application/json')
        ->set_status_header(201) // Created
        ->set_output(json_encode($response_data));
}

public function edit_product($id)
{
  
    // Get form data
    $sub_activity_id = $this->input->post('sub_activity_id');
    $name = $this->input->post('name');
    $prod_type = $this->input->post('prod_type'); // ID from product_types
    $status = $this->input->post('status');
    $date_submitted = $this->input->post('date_submitted');
    $last_updated = $this->input->post('last_updated');
    $in_charge_ids = $this->input->post('in_charge_ids'); // Raw input, could be "[9]" or "9,10"
    $user_id = $this->input->post('user_id'); // Assuming user_id is passed in the form
    $group = $this->input->post('group'); // Optional, defaults to existing value
    $output_id = $this->input->post('output_id'); // Nullable for output products
 $is_urgent = $this->input->post('isUrgent');
 


    // Validate required fields
    if (empty($user_id)) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400) // Bad Request
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'INVALID_INPUT'
            )));
    }

    // Validate product exists
    $this->db->where('id', $id);
    $this->db->where('is_active', 1); // Ensure the product is active
    $product = $this->db->get('sub_activity_products')->row_array();

    if (empty($product)) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400) // Bad Request
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'PRODUCT_NOT_FOUND_OR_ALREADY_DELETED'
            )));
    }

    // Validate prod_type if provided
    if (isset($prod_type)) { // Only validate if prod_type is submitted
        $this->db->where('id', $prod_type);
        $product_type = $this->db->get('product_types')->row_array();
        if (empty($product_type)) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(400) // Bad Request
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => 'INVALID_PROD_TYPE'
                )));
        }
    } else {
        // Use existing prod_type and determine type from the existing product if not provided
        $prod_type = $product['prod_type'];
        $this->db->where('id', $prod_type);
        $product_type = $this->db->get('product_types')->row_array();
    }

    // Determine type based on product_type category, preserving existing type if prod_type isn’t submitted
    $type = isset($prod_type) && $product_type['category'] === 'folder' ? 'folder' : ($product['type'] ?? '');

    // Parse in_charge_ids (handle string like "[9]" or "9,10")
    $in_charge_ids_array = [];
    if (!empty($in_charge_ids)) {
        // Try to decode as JSON (e.g., "[9]" -> [9])
        $parsed_ids = json_decode($in_charge_ids, true);
        if (is_array($parsed_ids)) {
            $in_charge_ids_array = array_filter(array_map('intval', $parsed_ids)); // Convert to integers, remove empty
        } else {
            // If not JSON, split by comma (e.g., "9,10" -> [9, 10])
            $ids = explode(',', str_replace(['[', ']', '"'], '', $in_charge_ids));
            $in_charge_ids_array = array_filter(array_map('trim', $ids), 'strlen'); // Clean and filter empty values
            $in_charge_ids_array = array_map('intval', $in_charge_ids_array); // Convert to integers
        }
    }

    // Prepare data for update (only include provided fields, explicitly checking each)
    $data = array();
    if (isset($sub_activity_id)) $data['sub_activity_id'] = $sub_activity_id; // Use isset to check if submitted
    if (isset($name)) $data['name'] = $name;
    if (isset($prod_type)) {
        $data['type'] = $type;
        $data['prod_type'] = $prod_type;
    }
    if (isset($status)) $data['status'] = $status;
    if (isset($date_submitted)) $data['date_submitted'] = date('Y-m-d', strtotime($date_submitted));
    if (isset($last_updated)) $data['last_updated'] = date('Y-m-d', strtotime($last_updated));
    if (!empty($in_charge_ids_array)) $data['in_charge_ids'] = json_encode($in_charge_ids_array);
    if (isset($is_urgent)) $data['isUrgent'] = $is_urgent;

    // Handle group and output_id only if provided
    if (isset($group)) {
        if (!in_array($group, ['general', 'output'])) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(400) // Bad Request
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => 'INVALID_GROUP'
                )));
        }
        $data['group'] = $group;

        if ($group === 'output') {
            if (!isset($output_id) || empty($output_id)) {
                return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(400) // Bad Request
                    ->set_output(json_encode(array(
                        'success' => false,
                        'message' => 'OUTPUT_ID_REQUIRED_FOR_OUTPUT_PRODUCT'
                    )));
            }
            $this->db->where('id', $output_id);
            $output_exists = $this->db->get('sub_activity_outputs')->num_rows() > 0; // Adjusted for sub_activity_outputs
            if (!$output_exists) {
                return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(400) // Bad Request
                    ->set_output(json_encode(array(
                        'success' => false,
                        'message' => 'INVALID_OUTPUT_ID'
                    )));
            }
            $data['output_id'] = $output_id;
        } else {
            $data['output_id'] = NULL; // Reset output_id for general products
        }
    }

    // Add audit fields (always updated, as they track the modification)
    $data['updated_by'] = $user_id;
    $data['last_updated'] = date('Y-m-d'); // Use current date if not provided

    // Check if a file is uploaded and update status to 'Submitted' if current status is 'Pending' and no status is specified
    $has_file_upload = !empty($_FILES['file']['name']) || (!empty($_FILES['files']) && is_array($_FILES['files']['name']) && !empty($_FILES['files']['name'][0]));
    if ($has_file_upload && (!isset($status) || $status === 'Pending') && $product['status'] === 'Pending') {
        $data['status'] = 'Submitted';
    }

    // Validate status if provided or set (must be 'Pending', 'Submitted', 'In Review', 'Declined', or 'Finalised')
    if (isset($data['status']) && !in_array($data['status'], ['Pending', 'Submitted', 'In Review', 'Declined', 'Finalised'])) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400) // Bad Request
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'INVALID_STATUS'
            )));
    }

    // Validate sub_activity_id if provided
    if (isset($data['sub_activity_id'])) {
        $this->db->where('id', $data['sub_activity_id']);
        $sub_activity_exists = $this->db->get('sub_activities')->num_rows() > 0;

        if (!$sub_activity_exists) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(400) // Bad Request
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => 'INVALID_SUB_ACTIVITY_ID'
                )));
        }
    }

    // Validate in_charge_ids if provided (ensure all user IDs exist)
    if (isset($data['in_charge_ids'])) {
        $this->db->where_in('id', $in_charge_ids_array);
        $users_exist = $this->db->get('users')->num_rows() === count($in_charge_ids_array);

        if (!$users_exist) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(400) // Bad Request
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => 'INVALID_USER_IDS_IN_IN_CHARGE'
                )));
        }
    }

    // Validate user_id exists in users table
    $this->db->where('id', $user_id);
    $user_exists = $this->db->get('users')->num_rows() > 0;

    if (!$user_exists) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400) // Bad Request
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'INVALID_USER_ID'
            )));
    }

    // Start a transaction to ensure data consistency
    $this->db->trans_start();

    // Handle file uploads
    $files = [];
    $directory = "sub_activity_products";
    if (!file_exists($directory)) {
        mkdir($directory, 0777, true);
    }

    if ($product_type['category'] === 'folder') {
        // Handle multiple file uploads for folder products
        $result = $this->handle_multiple_file_uploads_for_sub_activity($id, 'files', $directory, $user_id); // Adjusted helper
        if ($result['success'] === false) {
            $this->db->trans_rollback();
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(400) // Bad Request
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => $result['message']
                )));
        }
        $files = $result['files'];
        $data['url'] = ''; // No URL for folders
    } else {
        // Handle single file upload for non-folder products
        if (!empty($_FILES['file']['name'])) {
            $result = $this->handle_single_file_upload_for_sub_activity('file', $directory); // Adjusted helper
            if ($result['success'] === false) {
                $this->db->trans_rollback();
                return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(400) // Bad Request
                    ->set_output(json_encode(array(
                        'success' => false,
                        'message' => $result['message']
                    )));
            }
            $data['url'] = $result['file_url'];
            $data['type'] = $result['file_extension']; // Set type as the file extension
            $files = []; // No files array for single files
        }
    }

    // Update sub_activity status to "In Progress" if a file is uploaded
    $sub_activity_id_to_update = $data['sub_activity_id'] ?? $product['sub_activity_id']; // Use updated or existing sub_activity_id
    if ($has_file_upload) {
        $this->db->where('id', $sub_activity_id_to_update);
        $sub_activity = $this->db->get('sub_activities')->row_array();
        if ($sub_activity && $sub_activity['status'] !== 'Finalised') { // Avoid overriding "Finalised" status
            $this->db->where('id', $sub_activity_id_to_update);
            $this->db->update('sub_activities', ['status' => 'In Progress', 'updated_by' => $user_id, 'updated_at' => date('Y-m-d H:i:s')]);
            if ($this->db->affected_rows() === 0) {
                log_message('error', "Failed to update sub_activity status to In Progress for sub_activity_id: $sub_activity_id_to_update");
            }
        }
    }

    // Update the product in the database
    $this->db->where('id', $id);
    $update = $this->db->update('sub_activity_products', $data);

    if (!$update) {
        $this->db->trans_rollback();
        log_message('error', "Failed to update product: " . $this->db->error()['message']);
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400) // Bad Request
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'PRODUCT_NOT_UPDATED - ' . $this->db->error()['message']
            )));
    }

    // Commit the transaction if all operations succeed
    $this->db->trans_complete();

    if ($this->db->trans_status() === FALSE) {
        log_message('error', "Transaction failed: " . $this->db->error()['message']);
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400) // Bad Request
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'TRANSACTION_FAILED - ' . $this->db->error()['message']
            )));
    }
    
    // Determine if notifications should be sent
    $send_notifications = isset($data['status']) && in_array($data['status'], ['Submitted', 'In Review', 'Finalised', 'Declined']) && $product['status'] !== $data['status'];

    if ($send_notifications) {
        $this->load->library('phpmailer_lib');
        $mail = $this->phpmailer_lib->load();
        $mail->isSMTP();
        $mail->Host = 'smarthub.ovalspace.co';
        $mail->SMTPAuth = true;
        $mail->Username = 'notifications@smarthub.ovalspace.co';
        $mail->Password = 'wgw6.)O7sCTy';
        $mail->SMTPSecure = 'ssl';
        $mail->Port = 465;
        $mail->setFrom('notifications@smarthub.ovalspace.co', 'SmartHub Notification');
        $mail->isHTML(true);

        // Fetch sub-activity and parent activity details
        $sub_activity_id_to_use = $sub_activity_id ?? $product['sub_activity_id'];
        $this->db->select('sa.name as sub_activity_name, sa.parent_activity_id, a.name as activity_name, o.quarter_id, q.quarter, q.year_id, y.year, p.code as programme_code');
        $this->db->from('sub_activities sa');
        $this->db->join('activities a', 'sa.parent_activity_id = a.id', 'left');
        $this->db->join('outcomes o', 'a.outcome_id = o.id', 'left');
        $this->db->join('quarters q', 'o.quarter_id = q.id', 'left');
        $this->db->join('years y', 'q.year_id = y.id', 'left');
        $this->db->join('programmes p', 'y.programme_id = p.id', 'left');
        $this->db->where('sa.id', $sub_activity_id_to_use);
        $activity_data = $this->db->get()->row_array();

        $sub_activity_name = $activity_data['sub_activity_name'] ?? 'Unknown Sub-Activity';
        $target_activity_id = $activity_data['parent_activity_id'] ?? null;
        $app_link = "https://www.smarthub.ovalspace.co/ug/programmes";
       
            $entity_link = $target_activity_id 
    ? $app_link . '/' . ($activity_data['programme_code'] ?? 'SDLG') . '/activities/' . ($activity_data['quarter'] ?? 'Q1') . '/' . ($activity_data['year'] ?? '2025') . '/' . $target_activity_id
    : $app_link;

        // Fetch updater details
        $this->db->select('first_name');
        $this->db->where('id', $user_id);
        $updater = $this->db->get('users')->row_array();
        $updater_name = $updater['first_name'] ?? 'Unknown';

        // Common email template components
        $header = '<div style="background-color: #00A1E5; height: 15px; width: 100%;"></div>'
            . '<div style="background-color: #FDB913; height: 5px; width: 100%;"></div>'
            . '<div style="background-color: #ffffff; text-align: center; padding: 10px 0;">'
            . '<img src="https://api.smarthub.ovalspace.co/files/smart-hub.png" style="height: 150px; width: auto;" alt="SmartHub Logo" />'
            . '</div>';
        $footer = '<div style="font-size: 10px; color: #666; text-align: center; padding: 10px; background-color: #ffffff;">'
            . '&copy; 2025 VNG International | SmartHub<br>'
            . '<a href="https://smarthub.ovalspace.co" style="color: #00A1E5; text-decoration: underline;">Visit SmartHub</a>'
            . '</div>';

        // In-charge team notification
        $updated_in_charge_ids = !empty($in_charge_ids_array) ? $in_charge_ids_array : json_decode($product['in_charge_ids'], true);
        if (!empty($updated_in_charge_ids)) {
            $this->db->select('id, email');
            $this->db->where_in('id', $updated_in_charge_ids);
            $team_members = $this->db->get('users')->result_array();
            $team_emails = array_column($team_members, 'email');
            $team_user_ids = array_column($team_members, 'id');

            if (!empty($team_emails)) {
                foreach ($team_emails as $email) {
                    // $mail->addAddress($email);
                    $mail->addAddress('kimbowaandrew@gmail.com');
                }

                $notification_type = 'SUB_ACTIVITY_PRODUCT_UPDATE';
                $notification_title = '';
                $notification_message = '';
                $email_subject = '';
                $email_body = '';
                $email_alt_body = '';

                switch ($data['status']) {
                    case 'Submitted':
                        $notification_title = 'Sub-Activity Product Submitted';
                        // $notification_message = "The product \"{$data['name'] ?? $product['name']}\" on sub-activity: {$sub_activity_name} has been submitted by {$updater_name} for review.";
                        $notification_message = "The product \"" . ($data['name'] ?? $product['name']) . "\" on sub-activity: " . $sub_activity_name . " has been submitted by " . $updater_name . " for review.";
                        $email_subject = 'Sub-Activity Product Submitted for Review';
                        $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
                            . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
                            . "<tr><td>$header</td></tr>"
                            . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
                            . "<h2 style='color: #333; margin: 0 0 20px;'>Sub-Activity Product Submitted for Review</h2>"
                            . "<p style='margin: 0 0 15px;'>Dear Team,</p>"
                            . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($data['name'] ?? $product['name']) . "</strong>\" on sub-activity: "
                            . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($sub_activity_name) . "</a>, "
                            . "has been submitted by <strong>" . htmlspecialchars($updater_name) . "</strong>.</p>"
                            . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
                            . "</td></tr>"
                            . "<tr><td align='center'>$footer</td></tr>"
                            . "</table></body></html>";
                      $email_alt_body = "Dear Team,\n\nThe product, \"" . ($data['name'] ?? $product['name']) . "\", on sub-activity: " . $sub_activity_name . " (" . $entity_link . ") has been submitted by " . $updater_name . " for review.\n\nRegards,\nSmartHub";
                        break;

                    case 'In Review':
                        $notification_title = 'Sub-Activity Product In Review';
                        $notification_message = "The product \"" . ($data['name'] ?? $product['name']) . "\" on sub-activity: " . $sub_activity_name . " is now in review by " . $updater_name . ".";
                        $email_subject = 'Sub-Activity Product In Review';
                        $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
                            . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
                            . "<tr><td>$header</td></tr>"
                            . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
                            . "<h2 style='color: #333; margin: 0 0 20px;'>Sub-Activity Product In Review</h2>"
                            . "<p style='margin: 0 0 15px;'>Dear Team,</p>"
                            . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($data['name'] ?? $product['name']) . "</strong>\" on sub-activity: "
                            . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($sub_activity_name) . "</a>, "
                            . "is now in review by <strong>" . htmlspecialchars($updater_name) . "</strong>.</p>"
                            . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
                            . "</td></tr>"
                            . "<tr><td align='center'>$footer</td></tr>"
                            . "</table></body></html>";
                        $email_alt_body = "Dear Team,\n\nThe product, \"" . ($data['name'] ?? $product['name']) . "\", on sub-activity: " . $sub_activity_name . " (" . $entity_link . ") is now in review by " . $updater_name . ".\n\nRegards,\nSmartHub";
                        break;

                    case 'Finalised':
                        $notification_title = 'Sub-Activity Product Finalised';
                        $notification_message = "The product \"" . ($data['name'] ?? $product['name']) . "\" on sub-activity: " . $sub_activity_name . " has been finalised by " . $updater_name . ".";
                        $email_subject = 'Sub-Activity Product Finalised';
                        $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
                            . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
                            . "<tr><td>$header</td></tr>"
                            . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
                            . "<h2 style='color: #333; margin: 0 0 20px;'>Sub-Activity Product Finalised</h2>"
                            . "<p style='margin: 0 0 15px;'>Dear Team,</p>"
                            . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($data['name'] ?? $product['name']) . "</strong>\" on sub-activity: "
                            . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($sub_activity_name) . "</a>, "
                            . "has been finalised by <strong>" . htmlspecialchars($updater_name) . "</strong>.</p>"
                            . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
                            . "</td></tr>"
                            . "<tr><td align='center'>$footer</td></tr>"
                            . "</table></body></html>";
                        $email_alt_body = "Dear Team,\n\nThe product, \"" . ($data['name'] ?? $product['name']) . "\", on sub-activity: " . $sub_activity_name . " (" . $entity_link . ") has been finalised by " . $updater_name . ".\n\nRegards,\nSmartHub";
                        break;

                    case 'Declined':
                        $decline_reason = $this->input->post('decline_reason') ?? 'No reason provided';
                        $notification_title = 'Sub-Activity Product Declined';
                        $notification_message = "The product \"" . ($data['name'] ?? $product['name']) . "\" on sub-activity: " . $sub_activity_name . " has been declined by " . $updater_name . ". Reason: " . $decline_reason;
                        $email_subject = 'Sub-Activity Product Declined';
                        $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
                            . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
                            . "<tr><td>$header</td></tr>"
                            . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
                            . "<h2 style='color: #333; margin: 0 0 20px;'>Sub-Activity Product Declined</h2>"
                            . "<p style='margin: 0 0 15px;'>Dear Team,</p>"
                            . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($data['name'] ?? $product['name']) . "</strong>\" on sub-activity: "
                            . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($sub_activity_name) . "</a>, "
                            . "has been declined by <strong>" . htmlspecialchars($updater_name) . "</strong>.</p>"
                            . "<div style='background-color: #f8f8f8; border-left: 4px solid #FDB913; padding: 15px; margin: 20px 0; border-radius: 4px;'>"
                            . "<p style='color: #333; margin: 0; font-weight: bold;'>Reason for Decline:</p>"
                            . "<p style='color: #333; line-height: 1.6; margin: 10px 0 0;'>" . $decline_reason . "</p>"
                            . "</div>"
                            . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
                            . "</td></tr>"
                            . "<tr><td align='center'>$footer</td></tr>"
                            . "</table></body></html>";
                        $email_alt_body = "Dear Team,\n\nThe product, \"" . ($data['name'] ?? $product['name']) . "\", on sub-activity: " . $sub_activity_name . " (" . $entity_link . ") has been declined by " . $updater_name . ".\n\nReason: " . strip_tags($decline_reason) . "\n\nRegards,\nSmartHub";
                        break;
                                    }

                // Store notifications for team
                foreach ($team_user_ids as $team_user_id) {
                    $this->db->insert('notifications', [
                        'user_id' => $team_user_id,
                        'type' => $notification_type,
                        'title' => $notification_title,
                        'message' => $notification_message,
                        'link' => $entity_link,
                        'is_read' => 0,
                        'created_by' => $user_id
                    ]);
                }

                // Send email to team
                $mail->Subject = $email_subject;
                $mail->Body = $email_body;
                $mail->AltBody = $email_alt_body;
                if (!$mail->send()) {
                    log_message('error', 'Failed to send email to in-charge team: ' . $mail->ErrorInfo);
                }
                $mail->clearAddresses();
            }
        }

        // Admin notification
        $admin_emails = ['sam.ejibua@vng.nl','racheal.atukwase@vngi.org']; // Replace with actual admin emails
        
        $this->db->select('id')->where_in('email', $admin_emails);
        $admin_users = $this->db->get('users')->result_array();
        $admin_user_ids = array_column($admin_users, 'id');

        foreach ($admin_emails as $email) {
            // $mail->addAddress($email);
            $mail->addAddress('kimbowaandrew@gmail.com');
            
        }

        $notification_type = 'SUB_ACTIVITY_PRODUCT_UPDATE';
        $notification_title = '';
        $notification_message = '';
        $email_subject = '';
        $email_body = '';
        $email_alt_body = '';

        switch ($data['status']) {
            case 'Submitted':
                $notification_title = 'Sub-Activity Product Submitted for Review';
                $notification_message = "The product \"" . ($data['name'] ?? $product['name']) . "\" on sub-activity: " . $sub_activity_name . " has been submitted by " . $updater_name . " for review.";
                $email_subject = 'Sub-Activity Product Submitted for Review/Approval';
                $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
                    . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
                    . "<tr><td>$header</td></tr>"
                    . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
                    . "<h2 style='color: #333; margin: 0 0 20px;'>Sub-Activity Product Submitted for Review/Approval</h2>"
                    . "<p style='margin: 0 0 15px;'>Dear Sam and Racheal,</p>"
                    . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($data['name'] ?? $product['name']) . "</strong>\" on sub-activity: "
                    . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($sub_activity_name) . "</a>, "
                    . "has been submitted by <strong>" . htmlspecialchars($updater_name) . "</strong> for review/approval.</p>"
                    . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
                    . "</td></tr>"
                    . "<tr><td align='center'>$footer</td></tr>"
                    . "</table></body></html>";
                $email_alt_body = "Dear Sam and Racheal,\n\nThe product, \"" . ($data['name'] ?? $product['name']) . "\", on sub-activity: " . $sub_activity_name . " (" . $entity_link . ") has been submitted by " . $updater_name . " for review/approval.\n\nRegards,\nSmartHub";
                break;

            case 'In Review':
                $notification_title = 'Sub-Activity Product In Review';
                $notification_message = "The product \"" . ($data['name'] ?? $product['name']) . "\" on sub-activity: " . $sub_activity_name . " is now in review by " . $updater_name . ".";
                $email_subject = 'Sub-Activity Product In Review';
                $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
                    . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
                    . "<tr><td>$header</td></tr>"
                    . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
                    . "<h2 style='color: #333; margin: 0 0 20px;'>Sub-Activity Product In Review</h2>"
                    . "<p style='margin: 0 0 15px;'>Dear Sam and Racheal,</p>"
                    . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($data['name'] ?? $product['name']) . "</strong>\" on sub-activity: "
                    . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($sub_activity_name) . "</a>, "
                    . "is now in review by <strong>" . htmlspecialchars($updater_name) . "</strong>.</p>"
                    . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
                    . "</td></tr>"
                    . "<tr><td align='center'>$footer</td></tr>"
                    . "</table></body></html>";
                $email_alt_body = "Dear Sam and Racheal,\n\nThe product, \"" . ($data['name'] ?? $product['name']) . "\", on sub-activity: " . $sub_activity_name . " (" . $entity_link . ") is now in review by " . $updater_name . ".\n\nRegards,\nSmartHub";
                break;

            case 'Finalised':
                $notification_title = 'Sub-Activity Product Finalised';
                $notification_message = "The product \"" . ($data['name'] ?? $product['name']) . "\" on sub-activity: " . $sub_activity_name . " has been finalised by " . $updater_name . ".";
                $email_subject = 'Sub-Activity Product Finalised';
                $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
                    . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
                    . "<tr><td>$header</td></tr>"
                    . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
                    . "<h2 style='color: #333; margin: 0 0 20px;'>Sub-Activity Product Finalised</h2>"
                    . "<p style='margin: 0 0 15px;'>Dear Sam and Racheal,</p>"
                    . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($data['name'] ?? $product['name']) . "</strong>\" on sub-activity: "
                    . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($sub_activity_name) . "</a>, "
                    . "has been finalised by <strong>" . htmlspecialchars($updater_name) . "</strong>.</p>"
                    . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
                    . "</td></tr>"
                    . "<tr><td align='center'>$footer</td></tr>"
                    . "</table></body></html>";
              $email_alt_body = "Dear Sam and Racheal,\n\nThe product, \"" . ($data['name'] ?? $product['name']) . "\", on sub-activity: " . $sub_activity_name . " (" . $entity_link . ") has been finalised by " . $updater_name . ".\n\nRegards,\nSmartHub";
                break;

                            case 'Declined':
                    $decline_reason = $this->input->post('decline_reason') ?? 'No reason provided';
                    $notification_title = 'Sub-Activity Product Declined';
                    $notification_message = "The product \"" . ($data['name'] ?? $product['name']) . "\" on sub-activity: " . $sub_activity_name . " has been rejected by " . $updater_name . ". Reason: " . $decline_reason;
                    $email_subject = 'Sub-Activity Product Declined';
                    $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
                        . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
                        . "<tr><td>$header</td></tr>"
                        . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
                        . "<h2 style='color: #333; margin: 0 0 20px;'>Sub-Activity Product Declined</h2>"
                        . "<p style='margin: 0 0 15px;'>Dear Sam and Racheal,</p>"
                        . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($data['name'] ?? $product['name']) . "</strong>\" on sub-activity: "
                        . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($sub_activity_name) . "</a>, "
                        . "has been rejected by <strong>" . htmlspecialchars($updater_name) . "</strong>.</p>"
                        . "<div style='background-color: #f8f8f8; border-left: 4px solid #FDB913; padding: 15px; margin: 20px 0; border-radius: 4px;'>"
                        . "<p style='color: #333; margin: 0; font-weight: bold;'>Reason for Decline:</p>"
                        . "<p style='color: #333; line-height: 1.6; margin: 10px 0 0;'>" . $decline_reason . "</p>"
                        . "</div>"
                        . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
                        . "</td></tr>"
                        . "<tr><td align='center'>$footer</td></tr>"
                        . "</table></body></html>";
                    $email_alt_body = "Dear Sam and Racheal,\n\nThe product, \"" . ($data['name'] ?? $product['name']) . "\", on sub-activity: " . $sub_activity_name . " (" . $entity_link . ") has been rejected by " . $updater_name . ".\n\nReason: " . strip_tags($decline_reason) . "\n\nRegards,\nSmartHub";
                    break;
 
        }

        // Store notifications for admins
        foreach ($admin_user_ids as $admin_user_id) {
            $this->db->insert('notifications', [
                'user_id' => $admin_user_id,
                'type' => $notification_type,
                'title' => $notification_title,
                'message' => $notification_message,
                'link' => $entity_link,
                'is_read' => 0,
                'created_by' => $user_id
            ]);
        }

        // Send email to admins
        $mail->Subject = $email_subject;
        $mail->Body = $email_body;
        $mail->AltBody = $email_alt_body;
        if (!$mail->send()) {
            log_message('error', 'Failed to send email to admins: ' . $mail->ErrorInfo);
        }
    }

    // Fetch updated product and in_charge details for response
    $this->db->where('id', $id);
    $updated_product = $this->db->get('sub_activity_products')->row_array();

    $in_charge_details = [];
    if (!empty($updated_product['in_charge_ids'])) {
        $in_charge_ids = json_decode($updated_product['in_charge_ids'], true);
        if (!empty($in_charge_ids)) {
            $this->db->select('id, first_name, image as avatar');
            $this->db->where_in('id', $in_charge_ids);
            $users = $this->db->get('users')->result_array();
            foreach ($users as $user) {
                $in_charge_details[] = [
                    'id' => $user['id'],
                    'first_name' => $user['first_name'],
                    'avatar' => $user['avatar']
                ];
            }
        }
    }

    // Fetch files for folder products
    $product_files = [];
    if ($product_type['category'] === 'folder') {
        $this->db->where('product_id', $id);
        $files_data = $this->db->get('sub_activity_product_files')->result_array(); // Adjusted table
        foreach ($files_data as $file) {
            $product_files[] = [
                'id' => $file['id'],
                'name' => $file['name'],
                'type' => $file['type'],
                'url' => $file['url'],
                'date' => $file['date'],
                'size' => $file['size']
            ];
        }
    }

    $response_data = [
        'success' => true,
        'message' => 'PRODUCT_UPDATED_SUCCESSFULLY',
        'data' => [
            'id' => $updated_product['id'],
            'type' => $updated_product['type'],
            'name' => $updated_product['name'],
            'url' => $updated_product['url'],
            'inCharge' => $in_charge_details,
            'status' => $updated_product['status'],
            'dateSubmitted' => $updated_product['date_submitted'],
            'lastUpdated' => $updated_product['last_updated'],
            // 'group' => $updated_product['group'],
            // 'output_id' => $updated_product['output_id'],
            'prod_type' => $updated_product['prod_type'] // Add prod_type to the response
        ]
    ];

    // Only include 'files' if category is 'folder'
    if ($product_type['category'] === 'folder') {
        $response_data['data']['files'] = $product_files;
    }

    return $this->output
        ->set_content_type('application/json')
        ->set_status_header(200)
        ->set_output(json_encode($response_data));
}


// public function edit_product($id)
// {
    
//     // Get form data
//     $sub_activity_id = $this->input->post('sub_activity_id');
//     $name = $this->input->post('name');
//     $prod_type = $this->input->post('prod_type'); // ID from product_types
//     $status = $this->input->post('status');
//     $date_submitted = $this->input->post('date_submitted');
//     $last_updated = $this->input->post('last_updated');
//     $in_charge_ids = $this->input->post('in_charge_ids'); // Raw input, could be "[9]" or "9,10"
//     $user_id = $this->input->post('user_id'); // Assuming user_id is passed in the form
//     $group = $this->input->post('group'); // Optional, defaults to existing value
//     $output_id = $this->input->post('output_id'); // Nullable for output products
//     $is_urgent = $this->input->post('isUrgent'); 
    

//     // Validate required fields
//     if (empty($user_id)) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_INPUT'
//             )));
//     }

//     // Validate product exists
//     $this->db->where('id', $id);
//     $this->db->where('is_active', 1); // Ensure the product is active
//     $product = $this->db->get('sub_activity_products')->row_array();

//     if (empty($product)) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'PRODUCT_NOT_FOUND_OR_ALREADY_DELETED'
//             )));
//     }

//     // Validate prod_type if provided
//     if (isset($prod_type)) { // Only validate if prod_type is submitted
//         $this->db->where('id', $prod_type);
//         $product_type = $this->db->get('product_types')->row_array();
//         if (empty($product_type)) {
//             return $this->output
//                 ->set_content_type('application/json')
//                 ->set_status_header(400) // Bad Request
//                 ->set_output(json_encode(array(
//                     'success' => false,
//                     'message' => 'INVALID_PROD_TYPE'
//                 )));
//         }
//     } else {
//         // Use existing prod_type and determine type from the existing product if not provided
//         $prod_type = $product['prod_type'];
//         $this->db->where('id', $prod_type);
//         $product_type = $this->db->get('product_types')->row_array();
//     }

//     // Determine type based on product_type category, preserving existing type if prod_type isn’t submitted
//     $type = isset($prod_type) && $product_type['category'] === 'folder' ? 'folder' : ($product['type'] ?? '');

//     // Parse in_charge_ids (handle string like "[9]" or "9,10")
//     $in_charge_ids_array = [];
//     if (!empty($in_charge_ids)) {
//         // Try to decode as JSON (e.g., "[9]" -> [9])
//         $parsed_ids = json_decode($in_charge_ids, true);
//         if (is_array($parsed_ids)) {
//             $in_charge_ids_array = array_filter(array_map('intval', $parsed_ids)); // Convert to integers, remove empty
//         } else {
//             // If not JSON, split by comma (e.g., "9,10" -> [9, 10])
//             $ids = explode(',', str_replace(['[', ']', '"'], '', $in_charge_ids));
//             $in_charge_ids_array = array_filter(array_map('trim', $ids), 'strlen'); // Clean and filter empty values
//             $in_charge_ids_array = array_map('intval', $in_charge_ids_array); // Convert to integers
//         }
//     }

//     // Prepare data for update (only include provided fields, explicitly checking each)
//     $data = array();
//     if (isset($sub_activity_id)) $data['sub_activity_id'] = $sub_activity_id; // Use isset to check if submitted
//     if (isset($name)) $data['name'] = $name;
//     if (isset($prod_type)) {
//         $data['type'] = $type;
//         $data['prod_type'] = $prod_type;
//     }
//     if (isset($status)) $data['status'] = $status;
//     if (isset($date_submitted)) $data['date_submitted'] = date('Y-m-d', strtotime($date_submitted));
//     if (isset($last_updated)) $data['last_updated'] = date('Y-m-d', strtotime($last_updated));
//     if (!empty($in_charge_ids_array)) $data['in_charge_ids'] = json_encode($in_charge_ids_array);
//     if (isset($is_urgent)) $data['isUrgent'] = $is_urgent;

//     // Handle group and output_id only if provided
//     if (isset($group)) {
//         if (!in_array($group, ['general', 'output'])) {
//             return $this->output
//                 ->set_content_type('application/json')
//                 ->set_status_header(400) // Bad Request
//                 ->set_output(json_encode(array(
//                     'success' => false,
//                     'message' => 'INVALID_GROUP'
//                 )));
//         }
//         $data['group'] = $group;

//         if ($group === 'output') {
//             if (!isset($output_id) || empty($output_id)) {
//                 return $this->output
//                     ->set_content_type('application/json')
//                     ->set_status_header(400) // Bad Request
//                     ->set_output(json_encode(array(
//                         'success' => false,
//                         'message' => 'OUTPUT_ID_REQUIRED_FOR_OUTPUT_PRODUCT'
//                     )));
//             }
//             $this->db->where('id', $output_id);
//             $output_exists = $this->db->get('sub_activity_outputs')->num_rows() > 0; // Adjusted for sub_activity_outputs
//             if (!$output_exists) {
//                 return $this->output
//                     ->set_content_type('application/json')
//                     ->set_status_header(400) // Bad Request
//                     ->set_output(json_encode(array(
//                         'success' => false,
//                         'message' => 'INVALID_OUTPUT_ID'
//                     )));
//             }
//             $data['output_id'] = $output_id;
//         } else {
//             $data['output_id'] = NULL; // Reset output_id for general products
//         }
//     }

//     // Add audit fields (always updated, as they track the modification)
//     $data['updated_by'] = $user_id;
//     $data['last_updated'] = date('Y-m-d'); // Use current date if not provided

//     // Check if a file is uploaded and update status to 'Submitted' if current status is 'Pending' and no status is specified
//     $has_file_upload = !empty($_FILES['file']['name']) || (!empty($_FILES['files']) && is_array($_FILES['files']['name']) && !empty($_FILES['files']['name'][0]));
//     if ($has_file_upload && (!isset($status) || $status === 'Pending') && $product['status'] === 'Pending') {
//         $data['status'] = 'Submitted';
//     }

//     // Validate status if provided or set (must be 'Pending', 'Submitted', 'In Review', 'Declined', or 'Finalised')
//     if (isset($data['status']) && !in_array($data['status'], ['Pending', 'Submitted', 'In Review', 'Declined', 'Finalised'])) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_STATUS'
//             )));
//     }

//     // Validate sub_activity_id if provided
//     if (isset($data['sub_activity_id'])) {
//         $this->db->where('id', $data['sub_activity_id']);
//         $sub_activity_exists = $this->db->get('sub_activities')->num_rows() > 0;

//         if (!$sub_activity_exists) {
//             return $this->output
//                 ->set_content_type('application/json')
//                 ->set_status_header(400) // Bad Request
//                 ->set_output(json_encode(array(
//                     'success' => false,
//                     'message' => 'INVALID_SUB_ACTIVITY_ID'
//                 )));
//         }
//     }

//     // Validate in_charge_ids if provided (ensure all user IDs exist)
//     if (isset($data['in_charge_ids'])) {
//         $this->db->where_in('id', $in_charge_ids_array);
//         $users_exist = $this->db->get('users')->num_rows() === count($in_charge_ids_array);

//         if (!$users_exist) {
//             return $this->output
//                 ->set_content_type('application/json')
//                 ->set_status_header(400) // Bad Request
//                 ->set_output(json_encode(array(
//                     'success' => false,
//                     'message' => 'INVALID_USER_IDS_IN_IN_CHARGE'
//                 )));
//         }
//     }

//     // Validate user_id exists in users table
//     $this->db->where('id', $user_id);
//     $user_exists = $this->db->get('users')->num_rows() > 0;

//     if (!$user_exists) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_USER_ID'
//             )));
//     }

//     // Start a transaction to ensure data consistency
//     $this->db->trans_start();

//     // Handle file uploads
//     $files = [];
//     $directory = "sub_activity_products";
//     if (!file_exists($directory)) {
//         mkdir($directory, 0777, true);
//     }

//     if ($product_type['category'] === 'folder') {
//         // Handle multiple file uploads for folder products
//         $result = $this->handle_multiple_file_uploads_for_sub_activity($id, 'files', $directory, $user_id); // Adjusted helper
//         if ($result['success'] === false) {
//             $this->db->trans_rollback();
//             return $this->output
//                 ->set_content_type('application/json')
//                 ->set_status_header(400) // Bad Request
//                 ->set_output(json_encode(array(
//                     'success' => false,
//                     'message' => $result['message']
//                 )));
//         }
//         $files = $result['files'];
//         $data['url'] = ''; // No URL for folders
//     } else {
//         // Handle single file upload for non-folder products
//         if (!empty($_FILES['file']['name'])) {
//             $result = $this->handle_single_file_upload_for_sub_activity('file', $directory); // Adjusted helper
//             if ($result['success'] === false) {
//                 $this->db->trans_rollback();
//                 return $this->output
//                     ->set_content_type('application/json')
//                     ->set_status_header(400) // Bad Request
//                     ->set_output(json_encode(array(
//                         'success' => false,
//                         'message' => $result['message']
//                     )));
//             }
//             $data['url'] = $result['file_url'];
//             $data['type'] = $result['file_extension']; // Set type as the file extension
//             $files = []; // No files array for single files
//         }
//     }

//     // Update sub_activity and parent activity status to "In Progress" if a file is uploaded
//     $sub_activity_id_to_update = $data['sub_activity_id'] ?? $product['sub_activity_id']; // Use updated or existing sub_activity_id
//     if ($has_file_upload) {
//         // Update sub-activity status
//         $this->db->where('id', $sub_activity_id_to_update);
//         $sub_activity = $this->db->get('sub_activities')->row_array();
//         if ($sub_activity && $sub_activity['status'] !== 'Finalised') { // Avoid overriding "Finalised" status
//             $this->db->where('id', $sub_activity_id_to_update);
//             $this->db->update('sub_activities', [
//                 'status' => 'In Progress',
//                 'updated_by' => $user_id,
//                 'updated_at' => date('Y-m-d H:i:s')
//             ]);
//             if ($this->db->affected_rows() === 0 && $this->db->error()['code'] != 0) {
//                 log_message('error', "Failed to update sub_activity status to In Progress for sub_activity_id: $sub_activity_id_to_update");
//             }
//         }

//         // Update parent activity status
//         if ($sub_activity && !empty($sub_activity['parent_activity_id'])) {
//             $parent_activity_id = $sub_activity['parent_activity_id'];
//             $this->db->where('id', $parent_activity_id);
//             $parent_activity = $this->db->get('activities')->row_array();
//             if ($parent_activity && $parent_activity['status'] !== 'Finalised') { // Avoid overriding "Finalised" status
//                 $this->db->where('id', $parent_activity_id);
//                 $this->db->update('activities', [
//                     'status' => 'In Progress',
//                     'updated_by' => $user_id,
//                     'updated_at' => date('Y-m-d H:i:s')
//                 ]);
//                 if ($this->db->affected_rows() === 0 && $this->db->error()['code'] != 0) {
//                     log_message('error', "Failed to update parent activity status to In Progress for activity_id: $parent_activity_id");
//                 }
//             }
//         }
//     }

//     // Update the product in the database
//     $this->db->where('id', $id);
//     $update = $this->db->update('sub_activity_products', $data);

//     if (!$update) {
//         $this->db->trans_rollback();
//         log_message('error', "Failed to update product: " . $this->db->error()['message']);
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'PRODUCT_NOT_UPDATED - ' . $this->db->error()['message']
//             )));
//     }

//     // Commit the transaction if all operations succeed
//     $this->db->trans_complete();

//     if ($this->db->trans_status() === FALSE) {
//         log_message('error', "Transaction failed: " . $this->db->error()['message']);
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'TRANSACTION_FAILED - ' . $this->db->error()['message']
//             )));
//     }
    
//     // Determine if notifications should be sent
//     $send_notifications = isset($data['status']) && in_array($data['status'], ['Submitted', 'In Review', 'Finalised', 'Declined']) && $product['status'] !== $data['status'];

//     if ($send_notifications) {
//         $this->load->library('phpmailer_lib');
//         $mail = $this->phpmailer_lib->load();
//         $mail->isSMTP();
//         $mail->Host = 'smarthub.ovalspace.co';
//         $mail->SMTPAuth = true;
//         $mail->Username = 'notifications@smarthub.ovalspace.co';
//         $mail->Password = 'wgw6.)O7sCTy';
//         $mail->SMTPSecure = 'ssl';
//         $mail->Port = 465;
//         $mail->setFrom('notifications@smarthub.ovalspace.co', 'SmartHub Notification');
//         $mail->isHTML(true);

//         // Fetch sub-activity and parent activity details
//         $sub_activity_id_to_use = $sub_activity_id ?? $product['sub_activity_id'];
//         $this->db->select('sa.name as sub_activity_name, sa.parent_activity_id, a.name as activity_name, o.quarter_id, q.quarter, q.year_id, y.year, p.code as programme_code');
//         $this->db->from('sub_activities sa');
//         $this->db->join('activities a', 'sa.parent_activity_id = a.id', 'left');
//         $this->db->join('outcomes o', 'a.outcome_id = o.id', 'left');
//         $this->db->join('quarters q', 'o.quarter_id = q.id', 'left');
//         $this->db->join('years y', 'q.year_id = y.id', 'left');
//         $this->db->join('programmes p', 'y.programme_id = p.id', 'left');
//         $this->db->where('sa.id', $sub_activity_id_to_use);
//         $activity_data = $this->db->get()->row_array();

//         $sub_activity_name = $activity_data['sub_activity_name'] ?? 'Unknown Sub-Activity';
//         $target_activity_id = $activity_data['parent_activity_id'] ?? null;
//         $app_link = "https://www.smarthub.ovalspace.co/ug/programmes";
       
//         $entity_link = $target_activity_id 
//             ? $app_link . '/' . ($activity_data['programme_code'] ?? 'SDLG') . '/activities/' . ($activity_data['quarter'] ?? 'Q1') . '/' . ($activity_data['year'] ?? '2025') . '/' . $target_activity_id
//             : $app_link;

//         // Fetch updater details
//         $this->db->select('first_name');
//         $this->db->where('id', $user_id);
//         $updater = $this->db->get('users')->row_array();
//         $updater_name = $updater['first_name'] ?? 'Unknown';

//         // Common email template components
//         $header = '<div style="background-color: #00A1E5; height: 15px; width: 100%;"></div>'
//             . '<div style="background-color: #FDB913; height: 5px; width: 100%;"></div>'
//             . '<div style="background-color: #ffffff; text-align: center; padding: 10px 0;">'
//             . '<img src="https://api.smarthub.ovalspace.co/files/smart-hub.png" style="height: 150px; width: auto;" alt="SmartHub Logo" />'
//             . '</div>';
//         $footer = '<div style="font-size: 10px; color: #666; text-align: center; padding: 10px; background-color: #ffffff;">'
//             . '&copy; 2025 VNG International | SmartHub<br>'
//             . '<a href="https://smarthub.ovalspace.co" style="color: #00A1E5; text-decoration: underline;">Visit SmartHub</a>'
//             . '</div>';

//         // In-charge team notification
//         $updated_in_charge_ids = !empty($in_charge_ids_array) ? $in_charge_ids_array : json_decode($product['in_charge_ids'], true);
//         if (!empty($updated_in_charge_ids)) {
//             $this->db->select('id, email');
//             $this->db->where_in('id', $updated_in_charge_ids);
//             $team_members = $this->db->get('users')->result_array();
//             $team_emails = array_column($team_members, 'email');
//             $team_user_ids = array_column($team_members, 'id');

//             if (!empty($team_emails)) {
//                 foreach ($team_emails as $email) {
//                     // $mail->addAddress($email);
//                     $mail->addAddress('kimbowaandrew@gmail.com');
//                 }

//                 $notification_type = 'SUB_ACTIVITY_PRODUCT_UPDATE';
//                 $notification_title = '';
//                 $notification_message = '';
//                 $email_subject = '';
//                 $email_body = '';
//                 $email_alt_body = '';

//                 switch ($data['status']) {
//                     case 'Submitted':
//                         $notification_title = 'Sub-Activity Product Submitted';
//                         $notification_message = "The product \"" . ($data['name'] ?? $product['name']) . "\" on sub-activity: " . $sub_activity_name . " has been submitted by " . $updater_name . " for review.";
//                         $email_subject = 'Sub-Activity Product Submitted for Review';
//                         $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
//                             . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
//                             . "<tr><td>$header</td></tr>"
//                             . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
//                             . "<h2 style='color: #333; margin: 0 0 20px;'>Sub-Activity Product Submitted for Review</h2>"
//                             . "<p style='margin: 0 0 15px;'>Dear Team,</p>"
//                             . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($data['name'] ?? $product['name']) . "</strong>\" on sub-activity: "
//                             . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($sub_activity_name) . "</a>, "
//                             . "has been submitted by <strong>" . htmlspecialchars($updater_name) . "</strong>.</p>"
//                             . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
//                             . "</td></tr>"
//                             . "<tr><td align='center'>$footer</td></tr>"
//                             . "</table></body></html>";
//                         $email_alt_body = "Dear Team,\n\nThe product, \"" . ($data['name'] ?? $product['name']) . "\", on sub-activity: " . $sub_activity_name . " (" . $entity_link . ") has been submitted by " . $updater_name . " for review.\n\nRegards,\nSmartHub";
//                         break;

//                     case 'In Review':
//                         $notification_title = 'Sub-Activity Product In Review';
//                         $notification_message = "The product \"" . ($data['name'] ?? $product['name']) . "\" on sub-activity: " . $sub_activity_name . " is now in review by " . $updater_name . ".";
//                         $email_subject = 'Sub-Activity Product In Review';
//                         $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
//                             . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
//                             . "<tr><td>$header</td></tr>"
//                             . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
//                             . "<h2 style='color: #333; margin: 0 0 20px;'>Sub-Activity Product In Review</h2>"
//                             . "<p style='margin: 0 0 15px;'>Dear Team,</p>"
//                             . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($data['name'] ?? $product['name']) . "</strong>\" on sub-activity: "
//                             . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($sub_activity_name) . "</a>, "
//                             . "is now in review by <strong>" . htmlspecialchars($updater_name) . "</strong>.</p>"
//                             . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
//                             . "</td></tr>"
//                             . "<tr><td align='center'>$footer</td></tr>"
//                             . "</table></body></html>";
//                         $email_alt_body = "Dear Team,\n\nThe product, \"" . ($data['name'] ?? $product['name']) . "\", on sub-activity: " . $sub_activity_name . " (" . $entity_link . ") is now in review by " . $updater_name . ".\n\nRegards,\nSmartHub";
//                         break;

//                     case 'Finalised':
//                         $notification_title = 'Sub-Activity Product Finalised';
//                         $notification_message = "The product \"" . ($data['name'] ?? $product['name']) . "\" on sub-activity: " . $sub_activity_name . " has been finalised by " . $updater_name . ".";
//                         $email_subject = 'Sub-Activity Product Finalised';
//                         $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
//                             . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
//                             . "<tr><td>$header</td></tr>"
//                             . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
//                             . "<h2 style='color: #333; margin: 0 0 20px;'>Sub-Activity Product Finalised</h2>"
//                             . "<p style='margin: 0 0 15px;'>Dear Team,</p>"
//                             . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($data['name'] ?? $product['name']) . "</strong>\" on sub-activity: "
//                             . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($sub_activity_name) . "</a>, "
//                             . "has been finalised by <strong>" . htmlspecialchars($updater_name) . "</strong>.</p>"
//                             . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
//                             . "</td></tr>"
//                             . "<tr><td align='center'>$footer</td></tr>"
//                             . "</table></body></html>";
//                         $email_alt_body = "Dear Team,\n\nThe product, \"" . ($data['name'] ?? $product['name']) . "\", on sub-activity: " . $sub_activity_name . " (" . $entity_link . ") has been finalised by " . $updater_name . ".\n\nRegards,\nSmartHub";
//                         break;

//                     case 'Declined':
//                         $decline_reason = $this->input->post('decline_reason') ?? 'No reason provided';
//                         $notification_title = 'Sub-Activity Product Declined';
//                         $notification_message = "The product \"" . ($data['name'] ?? $product['name']) . "\" on sub-activity: " . $sub_activity_name . " has been declined by " . $updater_name . ". Reason: " . $decline_reason;
//                         $email_subject = 'Sub-Activity Product Declined';
//                         $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
//                             . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
//                             . "<tr><td>$header</td></tr>"
//                             . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
//                             . "<h2 style='color: #333; margin: 0 0 20px;'>Sub-Activity Product Declined</h2>"
//                             . "<p style='margin: 0 0 15px;'>Dear Team,</p>"
//                             . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($data['name'] ?? $product['name']) . "</strong>\" on sub-activity: "
//                             . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($sub_activity_name) . "</a>, "
//                             . "has been declined by <strong>" . htmlspecialchars($updater_name) . "</strong>.</p>"
//                             . "<div style='background-color: #f8f8f8; border-left: 4px solid #FDB913; padding: 15px; margin: 20px 0; border-radius: 4px;'>"
//                             . "<p style='color: #333; margin: 0; font-weight: bold;'>Reason for Decline:</p>"
//                             . "<p style='color: #333; line-height: 1.6; margin: 10px 0 0;'>" . $decline_reason . "</p>"
//                             . "</div>"
//                             . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
//                             . "</td></tr>"
//                             . "<tr><td align='center'>$footer</td></tr>"
//                             . "</table></body></html>";
//                         $email_alt_body = "Dear Team,\n\nThe product, \"" . ($data['name'] ?? $product['name']) . "\", on sub-activity: " . $sub_activity_name . " (" . $entity_link . ") has been declined by " . $updater_name . ".\n\nReason: " . strip_tags($decline_reason) . "\n\nRegards,\nSmartHub";
//                         break;
//                 }

//                 // Store notifications for team
//                 foreach ($team_user_ids as $team_user_id) {
//                     $this->db->insert('notifications', [
//                         'user_id' => $team_user_id,
//                         'type' => $notification_type,
//                         'title' => $notification_title,
//                         'message' => $notification_message,
//                         'link' => $entity_link,
//                         'is_read' => 0,
//                         'created_by' => $user_id
//                     ]);
//                 }

//                 // Send email to team
//                 $mail->Subject = $email_subject;
//                 $mail->Body = $email_body;
//                 $mail->AltBody = $email_alt_body;
//                 if (!$mail->send()) {
//                     log_message('error', 'Failed to send email to in-charge team: ' . $mail->ErrorInfo);
//                 }
//                 $mail->clearAddresses();
//             }
//         }

//         // Admin notification
//         // $admin_emails = ['sam.ejibua@vng.nl','racheal.atukwase@vngi.org'];
//         $admin_emails = ['kimbowaandrew@mail.com'];
//         // Replace with actual admin emails
//         $this->db->select('id')->where_in('email', $admin_emails);
//         $admin_users = $this->db->get('users')->result_array();
//         $admin_user_ids = array_column($admin_users, 'id');

//         foreach ($admin_emails as $email) {
//             // $mail->addAddress($email);
//             $mail->addAddress($email);
//         }

//         $notification_type = 'SUB_ACTIVITY_PRODUCT_UPDATE';
//         $notification_title = '';
//         $notification_message = '';
//         $email_subject = '';
//         $email_body = '';
//         $email_alt_body = '';

//         switch ($data['status']) {
//             case 'Submitted':
//                 $notification_title = 'Sub-Activity Product Submitted for Review';
//                 $notification_message = "The product \"" . ($data['name'] ?? $product['name']) . "\" on sub-activity: " . $sub_activity_name . " has been submitted by " . $updater_name . " for review.";
//                 $email_subject = 'Sub-Activity Product Submitted for Review/Approval';
//                 $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
//                     . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
//                     . "<tr><td>$header</td></tr>"
//                     . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
//                     . "<h2 style='color: #333; margin: 0 0 20px;'>Sub-Activity Product Submitted for Review/Approval</h2>"
//                     . "<p style='margin: 0 0 15px;'>Dear Sam and Racheal,</p>"
//                     . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($data['name'] ?? $product['name']) . "</strong>\" on sub-activity: "
//                     . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($sub_activity_name) . "</a>, "
//                     . "has been submitted by <strong>" . htmlspecialchars($updater_name) . "</strong> for review/approval.</p>"
//                     . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
//                     . "</td></tr>"
//                     . "<tr><td align='center'>$footer</td></tr>"
//                     . "</table></body></html>";
//                 $email_alt_body = "Dear Sam and Racheal,\n\nThe product, \"" . ($data['name'] ?? $product['name']) . "\", on sub-activity: " . $sub_activity_name . " (" . $entity_link . ") has been submitted by " . $updater_name . " for review/approval.\n\nRegards,\nSmartHub";
//                 break;

//             case 'In Review':
//                 $notification_title = 'Sub-Activity Product In Review';
//                 $notification_message = "The product \"" . ($data['name'] ?? $product['name']) . "\" on sub-activity: " . $sub_activity_name . " is now in review by " . $updater_name . ".";
//                 $email_subject = 'Sub-Activity Product In Review';
//                 $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
//                     . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
//                     . "<tr><td>$header</td></tr>"
//                     . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
//                     . "<h2 style='color: #333; margin: 0 0 20px;'>Sub-Activity Product In Review</h2>"
//                     . "<p style='margin: 0 0 15px;'>Dear Sam and Racheal,</p>"
//                     . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($data['name'] ?? $product['name']) . "</strong>\" on sub-activity: "
//                     . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($sub_activity_name) . "</a>, "
//                     . "is now in review by <strong>" . htmlspecialchars($updater_name) . "</strong>.</p>"
//                     . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
//                     . "</td></tr>"
//                     . "<tr><td align='center'>$footer</td></tr>"
//                     . "</table></body></html>";
//                 $email_alt_body = "Dear Sam and Racheal,\n\nThe product, \"" . ($data['name'] ?? $product['name']) . "\", on sub-activity: " . $sub_activity_name . " (" . $entity_link . ") is now in review by " . $updater_name . ".\n\nRegards,\nSmartHub";
//                 break;

//             case 'Finalised':
//                 $notification_title = 'Sub-Activity Product Finalised';
//                 $notification_message = "The product \"" . ($data['name'] ?? $product['name']) . "\" on sub-activity: " . $sub_activity_name . " has been finalised by " . $updater_name . ".";
//                 $email_subject = 'Sub-Activity Product Finalised';
//                 $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
//                     . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
//                     . "<tr><td>$header</td></tr>"
//                     . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
//                     . "<h2 style='color: #333; margin: 0 0 20px;'>Sub-Activity Product Finalised</h2>"
//                     . "<p style='margin: 0 0 15px;'>Dear Sam and Racheal,</p>"
//                     . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($data['name'] ?? $product['name']) . "</strong>\" on sub-activity: "
//                     . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($sub_activity_name) . "</a>, "
//                     . "has been finalised by <strong>" . htmlspecialchars($updater_name) . "</strong>.</p>"
//                     . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
//                     . "</td></tr>"
//                     . "<tr><td align='center'>$footer</td></tr>"
//                     . "</table></body></html>";
//                 $email_alt_body = "Dear Sam and Racheal,\n\nThe product, \"" . ($data['name'] ?? $product['name']) . "\", on sub-activity: " . $sub_activity_name . " (" . $entity_link . ") has been finalised by " . $updater_name . ".\n\nRegards,\nSmartHub";
//                 break;

//             case 'Declined':
//                 $decline_reason = $this->input->post('decline_reason') ?? 'No reason provided';
//                 $notification_title = 'Sub-Activity Product Declined';
//                 $notification_message = "The product \"" . ($data['name'] ?? $product['name']) . "\" on sub-activity: " . $sub_activity_name . " has been declined by " . $updater_name . ". Reason: " . $decline_reason;
//                 $email_subject = 'Sub-Activity Product Declined';
//                 $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
//                     . "<table cellpadding='0' cellspacing='0' border='0' width='100%' style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
//                     . "<tr><td>$header</td></tr>"
//                     . "<tr><td style='padding: 30px; color: #333; line-height: 1.6;'>"
//                     . "<h2 style='color: #333; margin: 0 0 20px;'>Sub-Activity Product Declined</h2>"
//                     . "<p style='margin: 0 0 15px;'>Dear Sam and Racheal,</p>"
//                     . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($data['name'] ?? $product['name']) . "</strong>\" on sub-activity: "
//                     . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($sub_activity_name) . "</a>, "
//                     . "has been declined by <strong>" . htmlspecialchars($updater_name) . "</strong>.</p>"
//                     . "<div style='background-color: #f8f8f8; border-left: 4px solid #FDB913; padding: 15px; margin: 20px 0; border-radius: 4px;'>"
//                     . "<p style='color: #333; margin: 0; font-weight: bold;'>Reason for Decline:</p>"
//                     . "<p style='color: #333; line-height: 1.6; margin: 10px 0 0;'>" . $decline_reason . "</p>"
//                     . "</div>"
//                     . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
//                     . "</td></tr>"
//                     . "<tr><td align='center'>$footer</td></tr>"
//                     . "</table></body></html>";
//                 $email_alt_body = "Dear Sam and Racheal,\n\nThe product, \"" . ($data['name'] ?? $product['name']) . "\", on sub-activity: " . $sub_activity_name . " (" . $entity_link . ") has been declined by " . $updater_name . ".\n\nReason: " . strip_tags($decline_reason) . "\n\nRegards,\nSmartHub";
//                 break;
//         }

//         // Store notifications for admins
//         foreach ($admin_user_ids as $admin_user_id) {
//             $this->db->insert('notifications', [
//                 'user_id' => $admin_user_id,
//                 'type' => $notification_type,
//                 'title' => $notification_title,
//                 'message' => $notification_message,
//                 'link' => $entity_link,
//                 'is_read' => 0,
//                 'created_by' => $user_id
//             ]);
//         }

//         // Send email to admins
//         $mail->Subject = $email_subject;
//         $mail->Body = $email_body;
//         $mail->AltBody = $email_alt_body;
//         if (!$mail->send()) {
//             log_message('error', 'Failed to send email to admins: ' . $mail->ErrorInfo);
//         }
//     }

//     // Fetch updated product and in_charge details for response
//     $this->db->where('id', $id);
//     $updated_product = $this->db->get('sub_activity_products')->row_array();

//     $in_charge_details = [];
//     if (!empty($updated_product['in_charge_ids'])) {
//         $in_charge_ids = json_decode($updated_product['in_charge_ids'], true);
//         if (!empty($in_charge_ids)) {
//             $this->db->select('id, first_name, image as avatar');
//             $this->db->where_in('id', $in_charge_ids);
//             $users = $this->db->get('users')->result_array();
//             foreach ($users as $user) {
//                 $in_charge_details[] = [
//                     'id' => $user['id'],
//                     'first_name' => $user['first_name'],
//                     'avatar' => $user['avatar']
//                 ];
//             }
//         }
//     }

//     // Fetch files for folder products
//     $product_files = [];
//     if ($product_type['category'] === 'folder') {
//         $this->db->where('product_id', $id);
//         $files_data = $this->db->get('sub_activity_product_files')->result_array(); // Adjusted table
//         foreach ($files_data as $file) {
//             $product_files[] = [
//                 'id' => $file['id'],
//                 'name' => $file['name'],
//                 'type' => $file['type'],
//                 'url' => $file['url'],
//                 'date' => $file['date'],
//                 'size' => $file['size']
//             ];
//         }
//     }

//     $response_data = [
//         'success' => true,
//         'message' => 'PRODUCT_UPDATED_SUCCESSFULLY',
//         'data' => [
//             'id' => $updated_product['id'],
//             'type' => $updated_product['type'],
//             'name' => $updated_product['name'],
//             'url' => $updated_product['url'],
//             'inCharge' => $in_charge_details,
//             'status' => $updated_product['status'],
//             'dateSubmitted' => $updated_product['date_submitted'],
//             'lastUpdated' => $updated_product['last_updated'],
//             'prod_type' => $updated_product['prod_type'] // Add prod_type to the response
//         ]
//     ];

//     // Only include 'files' if category is 'folder'
//     if ($product_type['category'] === 'folder') {
//         $response_data['data']['files'] = $product_files;
//     }

//     return $this->output
//         ->set_content_type('application/json')
//         ->set_status_header(200)
//         ->set_output(json_encode($response_data));
// }



private function handle_single_file_upload_for_sub_activity($field_name, $directory)
{
    if (empty($_FILES[$field_name]['name'])) {
        return ['success' => true, 'file_url' => '', 'file_extension' => ''];
    }

    $file_name = $_FILES[$field_name]['name'];
    $file_url = $this->upload_file_for_sub_activity($file_name, $field_name, $directory);

    if (!$file_url) {
        return [
            'success' => false,
            'message' => 'FILE_UPLOAD_FAILED: ' . $file_name
        ];
    }

    $file_extension = pathinfo($file_name, PATHINFO_EXTENSION);

    return [
        'success' => true,
        'file_url' => $file_url,
        'file_extension' => $file_extension
    ];
}

// private function handle_multiple_file_uploads_for_sub_activity($product_id, $file_field = 'files', $directory, $user_id)
// {
//     $result = ['success' => false, 'message' => '', 'files' => []];

//     if (empty($_FILES[$file_field]['name'][0])) {
//         $result['success'] = true; // Allow empty file upload for folder creation
//         return $result;
//     }

//     // Ensure directory exists
//     if (!file_exists($directory)) {
//         mkdir($directory, 0777, true);
//     }

//     $file_count = count($_FILES[$file_field]['name']);
//     for ($i = 0; $i < $file_count; $i++) {
//         $file_name = $_FILES[$file_field]['name'][$i];
//         $file_tmp = $_FILES[$file_field]['tmp_name'][$i];
//         $file_size = $_FILES[$file_field]['size'][$i];
//         $file_error = $_FILES[$file_field]['error'][$i];

//         // Generate a unique filename to avoid conflicts
//         $file_extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
//         $unique_filename = uniqid() . '.' . $file_extension;
//         $file_url = $directory . '/' . $unique_filename;

//         // Move the uploaded file
//         if ($file_error === UPLOAD_ERR_OK) {
//             if (move_uploaded_file($file_tmp, $file_url)) {
//                 // Prepare data for sub_activity_product_files
//                 $file_data = [
//                     'product_id' => $product_id,
//                     'name' => $file_name,
//                     'type' => $file_extension,
//                     'url' => $file_url,
//                     'date' => date('Y-m-d H:i:s'),
//                     'size' => $file_size,
//                     'created_by' => $user_id,
//                     'updated_by' => $user_id,
//                     'is_active' => 1
//                 ];

//                 // Insert into sub_activity_product_files
//                 $this->db->insert('sub_activity_product_files', $file_data);
//                 if ($this->db->affected_rows() > 0) {
//                     $result['files'][] = [
//                         'id' => $this->db->insert_id(),
//                         'name' => $file_name,
//                         'type' => $file_extension,
//                         'url' => $file_url,
//                         'date' => $file_data['date'],
//                         'size' => $file_size
//                     ];
//                 } else {
//                     $result['message'] = 'FAILED_TO_INSERT_FILE_RECORD - ' . $this->db->error()['message'];
//                     return $result; // Exit on first failure
//                 }
//             } else {
//                 $result['message'] = 'FAILED_TO_MOVE_UPLOADED_FILE';
//                 return $result;
//             }
//         } else {
//             $result['message'] = 'UPLOAD_ERROR_' . $file_error;
//             return $result;
//         }
//     }

//     $result['success'] = true;
//     return $result;
// }

private function handle_multiple_file_uploads_for_sub_activity($product_id, $field_name, $directory, $user_id)
{
    $files = [];
    if (empty($_FILES[$field_name]) || !is_array($_FILES[$field_name]['name'])) {
        return ['success' => true, 'files' => $files];
    }

    foreach ($_FILES[$field_name]['name'] as $index => $file_name) {
        if (!empty($file_name)) {
            $file_error = $_FILES[$field_name]['error'][$index];
            $file_size = $_FILES[$field_name]['size'][$index];

            if ($file_error === UPLOAD_ERR_OK) {
                $file_url = $this->upload_files_for_sub_activity($file_name, $field_name, $directory, $index);
                if ($file_url) {
                    // Insert file into product_files table
                    $file_data = array(
                        'product_id' => $product_id,
                        'name' => pathinfo($file_name, PATHINFO_FILENAME),
                        'type' => pathinfo($file_name, PATHINFO_EXTENSION),
                        'url' => $file_url,
                        'date' => date('Y-m-d'),
                        'size' => $file_size / 1024 / 1024 . ' MB', // Convert to MB
                        'created_by' => $user_id,
                        'updated_by' => $user_id
                    );
                    $this->db->insert('sub_activity_product_files', $file_data);
                    $file_id = $this->db->insert_id();
                    $files[] = array_merge($file_data, ['id' => $file_id]);
                } else {
                    return [
                        'success' => false,
                        'message' => 'FILE_UPLOAD_FAILED: ' . $file_name
                    ];
                }
            } else {
                return [
                    'success' => false,
                    'message' => 'FILE_UPLOAD_ERROR: ' . $file_name . ' (Error ' . $file_error . ')'
                ];
            }
        }
    }

    return ['success' => true, 'files' => $files];
}

private function upload_files_for_sub_activity($file_name, $field_name, $directory, $index)
{
    $config['upload_path'] = "./$directory/";
    $config['allowed_types'] = '*';
    $new_name = time() . '-' . $file_name;
    $config['file_name'] = $new_name;

    $this->load->library('upload', $config);
    $this->upload->initialize($config);

    // Set the $_FILES array to the specific file being uploaded
    $_FILES['userfile']['name'] = $_FILES[$field_name]['name'][$index];
    $_FILES['userfile']['type'] = $_FILES[$field_name]['type'][$index];
    $_FILES['userfile']['tmp_name'] = $_FILES[$field_name]['tmp_name'][$index];
    $_FILES['userfile']['error'] = $_FILES[$field_name]['error'][$index];
    $_FILES['userfile']['size'] = $_FILES[$field_name]['size'][$index];

    if (!$this->upload->do_upload('userfile') && !empty($file_name)) {
        $error = array('error' => $this->upload->display_errors());

        if ($error['error'] == "<p>The filetype you are attempting to upload is not allowed.</p>") {
            log_message('error', 'File type not allowed: ' . $file_name);
            return false;
        } else {
            log_message('error', 'File upload error: ' . $error['error']);
            return false;
        }
    }

    $upload_data = $this->upload->data();
    $file_url = base_url() . "$directory/" . $upload_data['file_name'];
    return $file_url;
}

private function upload_file_for_sub_activity($file_name, $field_name, $directory)
{
    $config['upload_path'] = "./$directory/";
    $config['allowed_types'] = '*';
    $new_name = time() . '-' . $file_name;
    $config['file_name'] = $new_name;

    $this->load->library('upload', $config);
    $this->upload->initialize($config);

    if (!$this->upload->do_upload($field_name) && !empty($file_name)) {
        $error = array('error' => $this->upload->display_errors());
       
        if ($error['error'] == "<p>The filetype you are attempting to upload is not allowed.</p>") {
            return false; // Let the main function handle the error response
        } else {
            log_message('error', 'File upload error: ' . $error['error']);
            return false;
        }
    }

    $upload_data = $this->upload->data();
    $file_url = base_url() . "$directory/" . $upload_data['file_name'];
    return $file_url;
}
  
  // old with out annual
// public function delete_product()
// {
//     // Validate user_id (assuming it's passed via GET or form for authentication)
//     $user_id = $this->input->get('user_id');
//     if (empty($user_id)) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_USER_ID'
//             )));
//     }

//     // Validate user exists
//     $this->db->where('id', $user_id);
//     $user_exists = $this->db->get('users')->num_rows() > 0;

//     if (!$user_exists) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_USER_ID'
//             )));
//     }

//     // Get product_id from input (required)
//     $product_id = $this->input->get('product_id');
//     if (empty($product_id) || !is_numeric($product_id)) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_PRODUCT_ID'
//             )));
//     }

//     // Get delete_type from input (optional, defaults to soft delete)
//     $delete_type = $this->input->get('delete_type') ?? 'soft';
//     if (!in_array($delete_type, ['soft', 'hard'])) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_DELETE_TYPE'
//             )));
//     }

//     // Check if product exists and is active
//     $this->db->where('id', $product_id);
//     $this->db->where('is_active', 1); // Ensure the product is active before deleting
//     $product = $this->db->get('sub_activity_products')->row_array();

//     if (empty($product)) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400) // Bad Request
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'PRODUCT_NOT_FOUND_OR_ALREADY_DELETED'
//             )));
//     }

//     // Start transaction for consistency
//     $this->db->trans_start();

//     if ($delete_type === 'soft') {
//         // Perform soft delete: update is_active to 0 and set deleted_at
//         $data = [
//             'is_active' => 0,
//             'deleted_at' => date('Y-m-d H:i:s'), // Current timestamp
//             'updated_by' => $user_id,
//             'updated_at' => date('Y-m-d H:i:s') // Current timestamp
//         ];

//         $this->db->where('id', $product_id);
//         $this->db->update('sub_activity_products', $data);

//         // Soft delete related sub_activity_product_files
//         $this->handle_soft_delete_sub_activity_product_files($product_id, $user_id);
//     } else {
//         // Perform hard delete: delete product and related sub_activity_product_files
//         $this->handle_hard_delete_sub_activity_product($product_id);
//     }

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

//     if ($this->db->trans_status() === FALSE) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(500) // Internal Server Error
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'DELETE_FAILED'
//             )));
//     }

//     return $this->output
//         ->set_content_type('application/json')
//         ->set_status_header(200)
//         ->set_output(json_encode(array(
//             'success' => true,
//             'message' => ($delete_type === 'soft' ? 'PRODUCT_SOFT_DELETED_SUCCESSFULLY' : 'PRODUCT_HARD_DELETED_SUCCESSFULLY'),
//             'data' => [
//                 'product_id' => $product_id,
//                 'delete_type' => $delete_type
//             ]
//         )));
// }

public function delete_product()
{
    // Validate user_id (assuming it's passed via GET or form for authentication)
    $user_id = $this->input->get('user_id');
    $isAnnual = $this->input->get('isAnnual');
    if (empty($user_id)) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400) // Bad Request
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'INVALID_USER_ID'
            )));
    }

    // Validate user exists
    $this->db->where('id', $user_id);
    $user_exists = $this->db->get('users')->num_rows() > 0;

    if (!$user_exists) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400) // Bad Request
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'INVALID_USER_ID'
            )));
    }

    // Get product_id from input (required)
    $product_id = $this->input->get('product_id');
    if (empty($product_id) || !is_numeric($product_id)) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400) // Bad Request
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'INVALID_PRODUCT_ID'
            )));
    }

    // Get delete_type from input (optional, defaults to soft delete)
    $delete_type = $this->input->get('delete_type') ?? 'soft';
    if (!in_array($delete_type, ['soft', 'hard'])) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400) // Bad Request
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'INVALID_DELETE_TYPE'
            )));
    }

    // Check if product exists and is active
    $this->db->where('id', $product_id);
    $this->db->where('is_active', 1); // Ensure the product is active before deleting
    $product = $this->db->get('sub_activity_products')->row_array();

    if (empty($product)) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400) // Bad Request
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'PRODUCT_NOT_FOUND_OR_ALREADY_DELETED'
            )));
    }
    
    //check is annual
    if($isAnnual =='true'){
        
     $data = [
            'isActiveOnAnnual' => 0,
            'updated_by' => $user_id,
            'updated_at' => date('Y-m-d H:i:s') // Current timestamp
        ];
        $this->db->where('id', $product_id);
        $this->db->update('sub_activity_products', $data);
        
        return $this->output
        ->set_content_type('application/json')
        ->set_status_header(200)
        ->set_output(json_encode(array(
            'success' => true,
            'message' => ($delete_type === 'soft' ? 'PRODUCT_SOFT_DELETED_SUCCESSFULLY' : 'PRODUCT_HARD_DELETED_SUCCESSFULLY'),
            'data' => [
                'product_id' => $product_id,
                'isAnnual'=>'YES',
                'delete_type' => $delete_type
            ]
        )));
    }
    

    // Start transaction for consistency
    $this->db->trans_start();

    if ($delete_type === 'soft') {
        // Perform soft delete: update is_active to 0 and set deleted_at
        $data = [
            'is_active' => 0,
            'deleted_at' => date('Y-m-d H:i:s'), // Current timestamp
            'updated_by' => $user_id,
            'updated_at' => date('Y-m-d H:i:s') // Current timestamp
        ];

        $this->db->where('id', $product_id);
        $this->db->update('sub_activity_products', $data);

        // Soft delete related sub_activity_product_files
        $this->handle_soft_delete_sub_activity_product_files($product_id, $user_id);
    } else {
        // Perform hard delete: delete product and related sub_activity_product_files
        $this->handle_hard_delete_sub_activity_product($product_id);
    }

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

    if ($this->db->trans_status() === FALSE) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(500) // Internal Server Error
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'DELETE_FAILED'
            )));
    }

    return $this->output
        ->set_content_type('application/json')
        ->set_status_header(200)
        ->set_output(json_encode(array(
            'success' => true,
            'message' => ($delete_type === 'soft' ? 'PRODUCT_SOFT_DELETED_SUCCESSFULLY' : 'PRODUCT_HARD_DELETED_SUCCESSFULLY'),
            'data' => [
                'product_id' => $product_id,
                'delete_type' => $delete_type
            ]
        )));
}

private function handle_soft_delete_sub_activity_product_files($product_id, $user_id)
{
    $this->db->where('product_id', $product_id);
    $this->db->where('is_active', 1); // Only soft delete active files
    $this->db->update('sub_activity_product_files', [
        'is_active' => 0,
        'deleted_at' => date('Y-m-d H:i:s'),
        'updated_by' => $user_id,
        'updated_at' => date('Y-m-d H:i:s')
    ]);
}

private function handle_hard_delete_sub_activity_product($product_id)
{
    // Delete related sub_activity_product_files
    $this->db->where('product_id', $product_id);
    $this->db->delete('sub_activity_product_files');

    // Delete the product
    $this->db->where('id', $product_id);
    $this->db->delete('sub_activity_products');
}
  
}