<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Products 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');
    }
  
    
public function get_product_types()
{
    // Query to get specific columns from product_types and join with users for created_by details
    $this->db->select('pt.id, pt.name, pt.category, u.id as created_by_id, u.first_name, u.image');
    $this->db->from('product_types pt');
    $this->db->join('users u', 'u.id = pt.created_by', 'left');
    $query = $this->db->get();
    
    if ($query->num_rows() > 0) {
        $product_types = $query->result_array();
        
        // Reshape the data to nest created_by as an object
        $formatted_data = array_map(function($row) {
            return [
                'id' => $row['id'],
                'name' => $row['name'],
                'category' => $row['category'],
                'created_by' => [
                    'id' => $row['created_by_id'],
                    'first_name' => $row['first_name'],
                    'image' => $row['image']
                ]
            ];
        }, $product_types);
        
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(200)
            ->set_output(json_encode(array(
                'success' => true,
                'message' => 'PRODUCT_TYPES_RETRIEVED_SUCCESSFULLY',
                'data' => $formatted_data
            )));
    } else {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(200)
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'NO_PRODUCT_TYPES_FOUND'
            )));
    }
}

public function add_product_type()
{
    // Get JSON data from the request body
    $json_data = json_decode(file_get_contents('php://input'), true);

    if (empty($json_data) || !isset($json_data['name']) || !isset($json_data['category']) || !isset($json_data['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'
            )));
    }

    // Prepare data for insertion
    $data = array(
        'name' => $json_data['name'],
        'category' => $json_data['category'],
        'created_by' => $json_data['user_id'],
        'updated_by' => $json_data['user_id']
    );

    // Validate category
    if (!in_array($data['category'], ['document', 'folder'])) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400) // Bad Request
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'INVALID_CATEGORY'
            )));
    }

    // Validate user_id exists in users table (optional, for security)
    $this->db->where('id', $json_data['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'
            )));
    }

    // Check if name already exists (enforce uniqueness, optional)
    $this->db->where('name', $data['name']);
    $name_exists = $this->db->get('product_types')->num_rows() > 0;

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

    // Insert the product type into the database
    $insert = $this->db->insert('product_types', $data);

    if ($insert) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(201) // Created
            ->set_output(json_encode(array(
                'success' => true,
                'message' => 'PRODUCT_TYPE_ADDED_SUCCESSFULLY',
                'data' => array('id' => $this->db->insert_id()) // Return the new ID
            )));
    } else {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(200)
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'PRODUCT_TYPE_NOT_ADDED'
            )));
    }
}

// working without notifications
// public function create_product()
// {
//     // Get form data
//     $activity_id = $this->input->post('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($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('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(
//         'activity_id' => $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 activity_id exists in activities table
//     $this->db->where('id', $data['activity_id']);
//     $activity_exists = $this->db->get('activities')->num_rows() > 0;

//     if (!$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_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('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 = "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($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('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 the product with the file URL and type
//             $this->db->where('id', $product_id);
//             $this->db->update('products', [
//                 'url' => $data['url'],
//                 'type' => $data['type']
              
              
//             ]);
//         }
//     }

//     // Update activity status to "In Progress" if a file is uploaded
//     if ($has_file_upload) {
//         $this->db->where('id', $activity_id);
//         $activity = $this->db->get('activities')->row_array();
//         if ($activity && $activity['status'] !== 'Finalised') { // Avoid overriding "Finalised" status
//             $this->db->where('id', $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) {
//                 log_message('error', "Failed to update activity status to In Progress for activity_id: $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('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'],
//             // 'group' => $data['group'],
//             // 'output_id' => $data['output_id']
//         ]
//     ];

//     // 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
    $activity_id = $this->input->post('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($activity_id) || empty($prod_type) || empty($user_id)) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400)
            ->set_output(json_encode(['success' => false, 'message' => 'INVALID_INPUT']));
    }

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

    // Validate output_id for 'output' group
    if ($group === 'output') {
        if (empty($output_id)) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(400)
                ->set_output(json_encode(['success' => false, 'message' => 'OUTPUT_ID_REQUIRED_FOR_OUTPUT_PRODUCT']));
        }
        $this->db->where('id', $output_id);
        $output_exists = $this->db->get('outputs')->num_rows() > 0;
        if (!$output_exists) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(400)
                ->set_output(json_encode(['success' => false, 'message' => 'INVALID_OUTPUT_ID']));
        }
    }

    // Validate prod_type and determine type
    $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)
            ->set_output(json_encode(['success' => false, 'message' => 'INVALID_PROD_TYPE']));
    }
    $type = ($product_type['category'] === 'folder') ? 'folder' : 'docx';

    // Parse in_charge_ids
    $in_charge_ids_array = [];
    if (!empty($in_charge_ids)) {
        $parsed_ids = json_decode($in_charge_ids, true);
        if (is_array($parsed_ids)) {
            $in_charge_ids_array = array_filter(array_map('intval', $parsed_ids));
        } else {
            $ids = explode(',', str_replace(['[', ']', '"'], '', $in_charge_ids));
            $in_charge_ids_array = array_filter(array_map('trim', $ids), 'strlen');
            $in_charge_ids_array = array_map('intval', $in_charge_ids_array);
        }
    }

    // Prepare data for insertion
    $data = [
        'activity_id' => $activity_id,
        'name' => $name,
        'type' => $type,
        'url' => '',
        'status' => $status ? $status : 'Pending',
        '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 file upload and adjust status
    $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')) {
        $data['status'] = 'Submitted';
    }

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

    // Validate activity_id
    $this->db->where('id', $data['activity_id']);
    $activity_exists = $this->db->get('activities')->num_rows() > 0;
    if (!$activity_exists) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400)
            ->set_output(json_encode(['success' => false, 'message' => 'INVALID_ACTIVITY_ID']));
    }

    // Validate in_charge_ids
    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)
                ->set_output(json_encode(['success' => false, 'message' => 'INVALID_USER_IDS_IN_IN_CHARGE']));
        }
    }

    // Validate user_id
    $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)
            ->set_output(json_encode(['success' => false, 'message' => 'INVALID_USER_ID']));
    }

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

    // Insert product
    $insert = $this->db->insert('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)
            ->set_output(json_encode(['success' => false, 'message' => 'PRODUCT_NOT_ADDED - ' . $this->db->error()['message']]));
    }

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

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

    if ($product_type['category'] === 'folder') {
        $result = $this->handle_multiple_file_uploads($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(['success' => false, 'message' => $result['message']]));
        }
        $files = $result['files'];
    } else {
        if (!empty($_FILES['file']['name'])) {
            $result = $this->handle_single_file_upload('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(['success' => false, 'message' => $result['message']]));
            }
            $data['url'] = $result['file_url'];
            $data['type'] = $result['file_extension'];
            $this->db->where('id', $product_id);
            $this->db->update('products', ['url' => $data['url'], 'type' => $data['type']]);
        }
    }

    // Update activity status
    if ($has_file_upload) {
        $this->db->where('id', $activity_id);
        $activity = $this->db->get('activities')->row_array();
        if ($activity && $activity['status'] !== 'Finalised') {
            $this->db->where('id', $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) {
                log_message('error', "Failed to update activity status to In Progress for activity_id: $activity_id");
            }
        }
    }

    // Commit transaction
    $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)
            ->set_output(json_encode(['success' => false, 'message' => 'TRANSACTION_FAILED - ' . $this->db->error()['message']]));
    }

    // Fetch created product
    $this->db->where('id', $product_id);
    $created_product = $this->db->get('products')->row_array();

    // Prepare in_charge details
    $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']
            ];
        }
    }

    // Prepare product files for folder category
    $product_files = [];
    if ($product_type['category'] === 'folder') {
        $this->db->where('product_id', $product_id);
        $files_data = $this->db->get('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']
            ];
        }
    }

  
// Notification logic
$send_notifications = in_array($data['status'], ['Submitted', 'In Review', 'Finalised', 'Declined']);
if ($send_notifications) {
    $this->load->library('phpmailer_lib');
    $mail = $this->phpmailer_lib->load();

    // SMTP Configuration
    $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 activity details for link
    $this->db->select('a.name as activity_name, o.quarter_id, q.quarter, q.year_id, y.year, p.code as programme_code');
    $this->db->from('activities a');
    $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('a.id', $created_product['activity_id']);
    $activity_data = $this->db->get()->row_array();

    $activity_name = $activity_data['activity_name'] ?? 'Unknown Activity';
    $programme_code = $activity_data['programme_code'] ?? 'SDLG';
    $quarter = $activity_data['quarter'] ?? 'Q1';
    $year = $activity_data['year'] ?? '2025';
    // $app_link = "http://localhost:8080/ug/programmes";
    $app_link = "https://www.smarthub.ovalspace.co/ug/programmes";
    $activity_link = "$app_link/{$programme_code}/activities/{$quarter}/{$year}/{$created_product['activity_id']}";

    // 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 HTML 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>';

    // Team notification
    if (!empty($in_charge_ids_array)) {
        $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');
        
        $mail->addAddress('paul.bate@vngi.org');          // Additional recipient 1
        $mail->addAddress('nakitende.millen@vngi.org');

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

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

            switch ($data['status']) {
                case 'Submitted':
                    $notification_title = 'New Product Submitted';
                    $notification_message = "A new product \"{$created_product['name']}\" on activity: {$activity_name} has been submitted by {$creator_name}.";
                    $email_subject = 'New 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 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($created_product['name']) . "</strong>\" on activity: "
                        . "<a href='$activity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($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, \"{$created_product['name']}\", on activity: {$activity_name} ($activity_link) has been submitted by {$creator_name}.\n\nRegards,\nSmartHub";
                    break;

                case 'In Review':
                    $notification_title = 'New Product In Review';
                    $notification_message = "A new product \"{$created_product['name']}\" on activity: {$activity_name} is in review by {$creator_name}.";
                    $email_subject = 'New 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 Product In Review</h2>"
                        . "<p style='margin: 0 0 15px;'>Dear Team,</p>"
                        . "<p style='margin: 0 0 15px;'>A new product, \"<strong>" . htmlspecialchars($created_product['name']) . "</strong>\" on activity: "
                        . "<a href='$activity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($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, \"{$created_product['name']}\", on activity: {$activity_name} ($activity_link) is in review by {$creator_name}.\n\nRegards,\nSmartHub";
                    break;

                case 'Finalised':
                    $notification_title = 'New Product Finalised';
                    $notification_message = "A new product \"{$created_product['name']}\" on activity: {$activity_name} has been finalised by {$creator_name}.";
                    $email_subject = 'New 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 Product Finalised</h2>"
                        . "<p style='margin: 0 0 15px;'>Dear Team,</p>"
                        . "<p style='margin: 0 0 15px;'>A new product, \"<strong>" . htmlspecialchars($created_product['name']) . "</strong>\" on activity: "
                        . "<a href='$activity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($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, \"{$created_product['name']}\", on activity: {$activity_name} ($activity_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 Product Declined';
                    $notification_message = "A new product \"{$created_product['name']}\" on activity: {$activity_name} has been declined by {$creator_name}. Reason: " . strip_tags($decline_reason);
                    $email_subject = 'New 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 Product Declined</h2>"
                        . "<p style='margin: 0 0 15px;'>Dear Team,</p>"
                        . "<p style='margin: 0 0 15px;'>A new product, \"<strong>" . htmlspecialchars($created_product['name']) . "</strong>\" on activity: "
                        . "<a href='$activity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($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 Team,\n\nA new product, \"{$created_product['name']}\", on activity: {$activity_name} ($activity_link) has been declined by {$creator_name}.\n\nReason: " . strip_tags($decline_reason) . "\n\nRegards,\nSmartHub";
                    break;
            }

            // Store notification 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' => $activity_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 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 = 'PRODUCT_CREATION';
    $notification_title = '';
    $notification_message = '';
    $email_subject = '';
    $email_body = '';
    $email_alt_body = '';

    switch ($data['status']) {
        case 'Submitted':
            $notification_title = 'New Product Submitted';
            $notification_message = "A new product \"{$created_product['name']}\" on activity: {$activity_name} has been submitted by {$creator_name} for review.";
            $email_subject = 'New 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 Product Submitted for Review/Approval</h2>"
                . "<p style='margin: 0 0 15px;'>Dear Admins,</p>"
                . "<p style='margin: 0 0 15px;'>A new product, \"<strong>" . htmlspecialchars($created_product['name']) . "</strong>\" on activity: "
                . "<a href='$activity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($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 Admins,\n\nA new product, \"{$created_product['name']}\", on activity: {$activity_name} ($activity_link) has been submitted by {$creator_name} for review/approval.\n\nRegards,\nSmartHub";
            break;

        case 'In Review':
            $notification_title = 'New Product In Review';
            $notification_message = "A new product \"{$created_product['name']}\" on activity: {$activity_name} is in review by {$creator_name}.";
            $email_subject = 'New 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 Product In Review</h2>"
                . "<p style='margin: 0 0 15px;'>Dear Admins,</p>"
                . "<p style='margin: 0 0 15px;'>A new product, \"<strong>" . htmlspecialchars($created_product['name']) . "</strong>\" on activity: "
                . "<a href='$activity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($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 Admins,\n\nA new product, \"{$created_product['name']}\", on activity: {$activity_name} ($activity_link) is in review by {$creator_name}.\n\nRegards,\nSmartHub";
            break;

        case 'Finalised':
            $notification_title = 'New Product Finalised';
            $notification_message = "A new product \"{$created_product['name']}\" on activity: {$activity_name} has been finalised by {$creator_name}.";
            $email_subject = 'New 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 Product Finalised</h2>"
                . "<p style='margin: 0 0 15px;'>Dear Admins,</p>"
                . "<p style='margin: 0 0 15px;'>A new product, \"<strong>" . htmlspecialchars($created_product['name']) . "</strong>\" on activity: "
                . "<a href='$activity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($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 Admins,\n\nA new product, \"{$created_product['name']}\", on activity: {$activity_name} ($activity_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 Product Declined';
            $notification_message = "A new product \"{$created_product['name']}\" on activity: {$activity_name} has been declined by {$creator_name}. Reason: " . strip_tags($decline_reason);
            $email_subject = 'New 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 Product Declined</h2>"
                . "<p style='margin: 0 0 15px;'>Dear Admins,</p>"
                . "<p style='margin: 0 0 15px;'>A new product, \"<strong>" . htmlspecialchars($created_product['name']) . "</strong>\" on activity: "
                . "<a href='$activity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($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 Admins,\n\nA new product, \"{$created_product['name']}\", on activity: {$activity_name} ($activity_link) has been declined by {$creator_name}.\n\nReason: " . strip_tags($decline_reason) . "\n\nRegards,\nSmartHub";
            break;
    }

    // Store notification 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' => $activity_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);
    }
}

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

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

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

// private function handle_single_file_upload($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($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_single_file_upload($field_name, $directory)
// {
//     if (empty($_FILES[$field_name]['name'])) {
//         return ['success' => true, 'file_url' => '', 'file_extension' => '', 'file_size' => ''];
//     }

//     $file_name = $_FILES[$field_name]['name'];
//     $file_size_bytes = $_FILES[$field_name]['size']; // Get file size in bytes
//     $file_url = $this->upload_file($file_name, $field_name, $directory);

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

//     $file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
//     $file_size = $this->get_file_size($file_size_bytes); // Convert to MB

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

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

    $file_name = $_FILES[$field_name]['name'];
    $file_size_bytes = $_FILES[$field_name]['size']; // Get file size in bytes
    $file_url = $this->upload_file($file_name, $field_name, $directory);

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

    $file_extension = pathinfo($file_name, PATHINFO_EXTENSION);

    // Convert file size: KB for < 1 MB, MB for >= 1 MB
    $file_size_kb = $file_size_bytes / 1024; // Bytes to KB
    if ($file_size_kb < 1024) {
        $file_size = round($file_size_kb, 2) . ' KB'; // Less than 1 MB, use KB
    } else {
        $file_size_mb = $file_size_kb / 1024; // KB to MB
        $file_size = round($file_size_mb, 2) . ' MB'; // 1 MB or more, use MB
    }

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

private function handle_multiple_file_uploads($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($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('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 handle_multiple_file_uploads_attachments($attachment_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];
            
              $file_size_kb = $file_size / 1024; // Bytes to KB
    if ($file_size_kb < 1024) {
        $file_size = round($file_size_kb, 2) . ' KB'; // Less than 1 MB, use KB
    } else {
        $file_size_mb = $file_size_kb / 1024; // KB to MB
        $file_size = round($file_size_mb, 2) . ' MB'; // 1 MB or more, use MB
    }

            if ($file_error === UPLOAD_ERR_OK) {
                $file_url = $this->upload_files($file_name, $field_name, $directory, $index);
                if ($file_url) {
                    $file_data = [
                        'attachment_id' => $attachment_id,
                        'name' => pathinfo($file_name, PATHINFO_FILENAME),
                        'type' => pathinfo($file_name, PATHINFO_EXTENSION),
                        'url' => $file_url,
                        'date' => date('Y-m-d'),
                        'size' => $file_size,
                        'created_by' => $user_id,
                        'updated_by' => $user_id
                    ];
                    $this->db->insert('attachment_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 . ' (' . $this->get_upload_error_message($file_error) . ')'
                ];
            }
        }
    }

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

private function upload_files($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)) { // Changed field name to 'userfile'
        $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($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;
}


// public function edit_product($id)
// {
//     // Get form data
//     $activity_id = $this->input->post('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

//     // 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('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($activity_id)) $data['activity_id'] = $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);

//     // 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('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'
//                     )));
//             }
//             $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 activity_id if provided
//     if (isset($data['activity_id'])) {
//         $this->db->where('id', $data['activity_id']);
//         $activity_exists = $this->db->get('activities')->num_rows() > 0;

//         if (!$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_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 = "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($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('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 activity status to "In Progress" if a file is uploaded
//     $activity_id_to_update = $data['activity_id'] ?? $product['activity_id']; // Use updated or existing activity_id
//     if ($has_file_upload) {
//         $this->db->where('id', $activity_id_to_update);
//         $activity = $this->db->get('activities')->row_array();
//         if ($activity && $activity['status'] !== 'Finalised') { // Avoid overriding "Finalised" status
//             $this->db->where('id', $activity_id_to_update);
//             $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) {
//                 log_message('error', "Failed to update activity status to In Progress for activity_id: $activity_id_to_update");
//             }
//         }
//     }

//     // Update the product in the database
//     $this->db->where('id', $id);
//     $update = $this->db->update('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']
//             )));
//     }

//     // Fetch updated product and in_charge details for response
//     $this->db->where('id', $id);
//     $updated_product = $this->db->get('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('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_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
//     $activity_id = $this->input->post('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

//     // 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('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($activity_id)) $data['activity_id'] = $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);

//     // 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('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'
//                     )));
//             }
//             $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 activity_id if provided
//     if (isset($data['activity_id'])) {
//         $this->db->where('id', $data['activity_id']);
//         $activity_exists = $this->db->get('activities')->num_rows() > 0;

//         if (!$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_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 = "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($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('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 activity status to "In Progress" if a file is uploaded
//     $activity_id_to_update = $data['activity_id'] ?? $product['activity_id']; // Use updated or existing activity_id
//     if ($has_file_upload) {
//         $this->db->where('id', $activity_id_to_update);
//         $activity = $this->db->get('activities')->row_array();
//         if ($activity && $activity['status'] !== 'Finalised') { // Avoid overriding "Finalised" status
//             $this->db->where('id', $activity_id_to_update);
//             $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) {
//                 log_message('error', "Failed to update activity status to In Progress for activity_id: $activity_id_to_update");
//             }
//         }
//     }

//     // Check if status is changing to 'Submitted' or 'Finalised' for email notifications
//     $send_emails = isset($data['status']) && ($data['status'] === 'Submitted' || $data['status'] === 'Finalised') && $product['status'] !== $data['status'];

//     // Update the product in the database
//     $this->db->where('id', $id);
//     $update = $this->db->update('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']
//             )));
//     }

//     // Fetch updated product and in_charge details for response
//     $this->db->where('id', $id);
//     $updated_product = $this->db->get('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('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']
//             ];
//         }
//     }

//     // Send email notifications if status changed to 'Submitted' or 'Finalised'
//     if ($send_emails) {
//         $this->load->library('email');

//         // Fetch activity name
//         $this->db->where('id', $updated_product['activity_id']);
//         $activity = $this->db->get('activities')->row_array();
//         $activity_name = $activity['name'] ?? 'Unknown Activity';

//         // Email configuration (adjust as per your SMTP settings)
//         $config = [
//             'protocol' => 'smtp',
//             'smtp_host' => 'smarthub.ovalspace.co', // e.g., 'smtp.gmail.com'
//             'smtp_port' => 465,
//             'smtp_user' => 'notifications@smarthub.ovalspace.co',
//             'smtp_pass' => 'wgw6.)O7sCTy',
//             'mailtype' => 'text',
//             'charset' => 'utf-8',
//             'newline' => "\r\n"
//         ];
//         $this->email->initialize($config);

//         // Fetch team member emails from in_charge_ids
//         $team_emails = [];
//         if (!empty($in_charge_ids)) {
//             $this->db->select('email');
//             $this->db->where_in('id', $in_charge_ids);
//             $team_members = $this->db->get('users')->result_array();
//             $team_emails = array_column($team_members, 'email');
//         }

//         // Team notification
//         if (!empty($team_emails)) {
//             // $this->email->from('notifications@smarthub.ovalspace.co', 'SmartHub Notification');
//             // // $this->email->to($team_emails);
//             // $this->email->to('kimbowaandrew@gmail.com');
//             // $this->email->subject('Product Status Update');
//             // $message = "Hello Team,\n\nA product, '{$updated_product['name']}', has been {$data['status']}. Pending Review.\n\nRegards,\nSmartHub";
//             // $this->email->message($message);
//             // if (!$this->email->send()) {
//             //     log_message('error', 'Failed to send email to team: ' . $this->email->print_debugger());
//             // }
            
//             $message = "Hello Team,\n\nA product, '{$updated_product['name']}', has been {$data['status']}. Pending Review.\n\nRegards,\nSmartHub";
            
            
//              $this->load->library('phpmailer_lib');

    
//     // PHPMailer object
//         $mail = $this->phpmailer_lib->load();

// $mail->isSMTP();                                      // Set mailer to use SMTP
// $mail->Host = 'smarthub.ovalspace.co';                       // Specify main and backup SMTP servers
// $mail->SMTPAuth = true;                               // Enable SMTP authentication
// $mail->Username = 'notifications@smarthub.ovalspace.co';             // SMTP username
// $mail->Password = 'wgw6.)O7sCTy';              // SMTP password
// $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
// $mail->Port = 465;                                    // TCP port to connect to

// $mail->setFrom('notifications@smarthub.ovalspace.co', 'SmartHub Notification');
// $mail->addAddress($email);           // Add a recipient
// $mail->addReplyTo('notifications@smarthub.ovalspace.co', 'SmartHub Notification');
// $mail->isHTML(true);                                  // Set email format to HTML
// $mail->Subject = 'Product Status Update';
// $mail->Body    = $message;
// $mail->AltBody = 'Hello, this is a test email!';       // Plain-text message

// if (!$mail->send()) {
//     echo 'Mailer Error: ' . $mail->ErrorInfo;
// }
//         }

//         // Admin notification (Sam and Racheal)
//         // $admin_emails = ['sam.ejibua@vng.nl', 'racheal.atukwase@vngi.org'];
//         // $admin_emails = ['kimbowaandrew@gmail.com', 'andrew@ovalspace.co'];
//         // $this->email->clear(); // Clear previous email settings
//         // $this->email->from('notifications@smarthub.ovalspace.co', 'System Notification');
//         // $this->email->to($admin_emails);
//         // $this->email->subject('Product Submitted for Review/Approval');
//         // $admin_message = "Dear Sam and Racheal,\n\nA product, '{$updated_product['name']}', has been {$data['status']} on '{$activity_name}' for review/approval.\n\nRegards,\nSystem";
//         // $this->email->message($admin_message);
//         // if (!$this->email->send()) {
//         //     log_message('error', 'Failed to send email to admins: ' . $this->email->print_debugger());
//         // }
//     }

//     $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));
// }


// public function edit_product($id)
// {
//     // Get form data
//     $activity_id = $this->input->post('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

//     // 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('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)) {
//         $parsed_ids = json_decode($in_charge_ids, true);
//         if (is_array($parsed_ids)) {
//             $in_charge_ids_array = array_filter(array_map('intval', $parsed_ids));
//         } else {
//             $ids = explode(',', str_replace(['[', ']', '"'], '', $in_charge_ids));
//             $in_charge_ids_array = array_filter(array_map('trim', $ids), 'strlen');
//             $in_charge_ids_array = array_map('intval', $in_charge_ids_array);
//         }
//     }

//     // Prepare data for update
//     $data = array();
//     if (isset($activity_id)) $data['activity_id'] = $activity_id;
//     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($group)) {
//         if (!in_array($group, ['general', 'output'])) {
//             return $this->output
//                 ->set_content_type('application/json')
//                 ->set_status_header(400)
//                 ->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)
//                     ->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('outputs')->num_rows() > 0;
//             if (!$output_exists) {
//                 return $this->output
//                     ->set_content_type('application/json')
//                     ->set_status_header(400)
//                     ->set_output(json_encode(array(
//                         'success' => false,
//                         'message' => 'INVALID_OUTPUT_ID'
//                     )));
//             }
//             $data['output_id'] = $output_id;
//         } else {
//             $data['output_id'] = NULL;
//         }
//     }

//     $data['updated_by'] = $user_id;
//     $data['last_updated'] = date('Y-m-d');

//     $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';
//     }

//     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)
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_STATUS'
//             )));
//     }

//     if (isset($data['activity_id'])) {
//         $this->db->where('id', $data['activity_id']);
//         $activity_exists = $this->db->get('activities')->num_rows() > 0;
//         if (!$activity_exists) {
//             return $this->output
//                 ->set_content_type('application/json')
//                 ->set_status_header(400)
//                 ->set_output(json_encode(array(
//                     'success' => false,
//                     'message' => 'INVALID_ACTIVITY_ID'
//                 )));
//         }
//     }

//     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)
//                 ->set_output(json_encode(array(
//                     'success' => false,
//                     'message' => 'INVALID_USER_IDS_IN_IN_CHARGE'
//                 )));
//         }
//     }

//     $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)
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_USER_ID'
//             )));
//     }

//     $this->db->trans_start();

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

//     if ($product_type['category'] === 'folder') {
//         $result = $this->handle_multiple_file_uploads($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'] = '';
//     } else {
//         if (!empty($_FILES['file']['name'])) {
//             $result = $this->handle_single_file_upload('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']
//                     )));
//             }
//             $data['url'] = $result['file_url'];
//             $data['type'] = $result['file_extension'];
//             $files = [];
//         }
//     }

//     $activity_id_to_update = $data['activity_id'] ?? $product['activity_id'];
//     if ($has_file_upload) {
//         $this->db->where('id', $activity_id_to_update);
//         $activity = $this->db->get('activities')->row_array();
//         if ($activity && $activity['status'] !== 'Finalised') {
//             $this->db->where('id', $activity_id_to_update);
//             $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) {
//                 log_message('error', "Failed to update activity status to In Progress for activity_id: $activity_id_to_update");
//             }
//         }
//     }

//     $send_emails = isset($data['status']) && ($data['status'] === 'Submitted' || $data['status'] === 'Finalised') && $product['status'] !== $data['status'];

//     $this->db->where('id', $id);
//     $update = $this->db->update('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)
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'PRODUCT_NOT_UPDATED - ' . $this->db->error()['message']
//             )));
//     }

//     $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)
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'TRANSACTION_FAILED - ' . $this->db->error()['message']
//             )));
//     }

//     $this->db->where('id', $id);
//     $updated_product = $this->db->get('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']
//                 ];
//             }
//         }
//     }

//     $product_files = [];
//     if ($product_type['category'] === 'folder') {
//         $this->db->where('product_id', $id);
//         $files_data = $this->db->get('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']
//             ];
//         }
//     }

//     // Send email notifications if status changed to 'Submitted' or 'Finalised'
//     if ($send_emails) {
//         $this->load->library('phpmailer_lib');
//         $mail = $this->phpmailer_lib->load();

//         // SMTP Configuration
//         $mail->isSMTP();
//         $mail->Host = 'smarthub.ovalspace.co';
//         $mail->SMTPAuth = true;
//         $mail->Username = 'notifications@smarthub.ovalspace.co';
//         $mail->Password = 'wgw6.)O7sCTy';
//         $mail->SMTPSecure = 'ssl'; // Use 'ssl' for port 465
//         $mail->Port = 465;
//         $mail->setFrom('notifications@smarthub.ovalspace.co', 'SmartHub Notification');
//         $mail->isHTML(false); // Plain text email

//         // Fetch activity name
//         $this->db->where('id', $updated_product['activity_id']);
//         $activity = $this->db->get('activities')->row_array();
//         $activity_name = $activity['name'] ?? 'Unknown Activity';

//         // Team notification
//         if (!empty($in_charge_ids)) {
//             $this->db->select('email');
//             $this->db->where_in('id', $in_charge_ids);
//             $team_members = $this->db->get('users')->result_array();
//             $team_emails = array_column($team_members, 'email');

//             if (!empty($team_emails)) {
//                 foreach ($team_emails as $email) {
//                     // $mail->addAddress($email);
//                     $mail->addAddress('kimbowaandrew@gmail.com');
//                 }
//                 $mail->Subject = 'Product Status Update';
//                 $message = "Hello Team,\n\nA product, '{$updated_product['name']}', has been {$data['status']}. Pending Review.\n\nRegards,\nSmartHub";
//                 $mail->Body = $message;

//                 if (!$mail->send()) {
//                     log_message('error', 'Failed to send email to team: ' . $mail->ErrorInfo);
//                 }
//                 $mail->clearAddresses(); // Clear recipients for next email
//             }
//         }

//         // Admin notification
//         // $admin_emails = ['sam.ejibua@vng.nl', 'racheal.atukwase@vngi.org'];
//         $admin_emails = ['kimbowaandrew@gmail.com', 'kimbowaandrew@gmail.com'];
//         foreach ($admin_emails as $email) {
//             $mail->addAddress($email);
//         }
//         $mail->Subject = 'Product Submitted for Review/Approval';
//         $admin_message = "Dear Sam and Racheal,\n\nA product, '{$updated_product['name']}', has been {$data['status']} on '{$activity_name}' for review/approval.\n\nRegards,\nSmartHub";
//         $mail->Body = $admin_message;

//         if (!$mail->send()) {
//             log_message('error', 'Failed to send email to admins: ' . $mail->ErrorInfo);
//         }
//     }

//     $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']
//         ]
//     ];

//     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
//     $activity_id = $this->input->post('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

//     // 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('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 {
//         $prod_type = $product['prod_type'];
//         $this->db->where('id', $prod_type);
//         $product_type = $this->db->get('product_types')->row_array();
//     }

//     $type = isset($prod_type) && $product_type['category'] === 'folder' ? 'folder' : ($product['type'] ?? '');

//     // Parse in_charge_ids
//     $in_charge_ids_array = [];
//     if (!empty($in_charge_ids)) {
//         $parsed_ids = json_decode($in_charge_ids, true);
//         if (is_array($parsed_ids)) {
//             $in_charge_ids_array = array_filter(array_map('intval', $parsed_ids));
//         } else {
//             $ids = explode(',', str_replace(['[', ']', '"'], '', $in_charge_ids));
//             $in_charge_ids_array = array_filter(array_map('trim', $ids), 'strlen');
//             $in_charge_ids_array = array_map('intval', $in_charge_ids_array);
//         }
//     }

//     // Prepare data for update
//     $data = array();
//     if (isset($activity_id)) $data['activity_id'] = $activity_id;
//     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($group)) {
//         if (!in_array($group, ['general', 'output'])) {
//             return $this->output
//                 ->set_content_type('application/json')
//                 ->set_status_header(400)
//                 ->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)
//                     ->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('outputs')->num_rows() > 0;
//             if (!$output_exists) {
//                 return $this->output
//                     ->set_content_type('application/json')
//                     ->set_status_header(400)
//                     ->set_output(json_encode(array(
//                         'success' => false,
//                         'message' => 'INVALID_OUTPUT_ID'
//                     )));
//             }
//             $data['output_id'] = $output_id;
//         } else {
//             $data['output_id'] = NULL;
//         }
//     }

//     $data['updated_by'] = $user_id;
//     $data['last_updated'] = date('Y-m-d');

//     $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';
//     }

//     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)
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_STATUS'
//             )));
//     }

//     if (isset($data['activity_id'])) {
//         $this->db->where('id', $data['activity_id']);
//         $activity_exists = $this->db->get('activities')->num_rows() > 0;
//         if (!$activity_exists) {
//             return $this->output
//                 ->set_content_type('application/json')
//                 ->set_status_header(400)
//                 ->set_output(json_encode(array(
//                     'success' => false,
//                     'message' => 'INVALID_ACTIVITY_ID'
//                 )));
//         }
//     }

//     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)
//                 ->set_output(json_encode(array(
//                     'success' => false,
//                     'message' => 'INVALID_USER_IDS_IN_IN_CHARGE'
//                 )));
//         }
//     }

//     $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)
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_USER_ID'
//             )));
//     }

//     $this->db->trans_start();

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

//     if ($product_type['category'] === 'folder') {
//         $result = $this->handle_multiple_file_uploads($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'] = '';
//     } else {
//         if (!empty($_FILES['file']['name'])) {
//             $result = $this->handle_single_file_upload('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']
//                     )));
//             }
//             $data['url'] = $result['file_url'];
//             $data['type'] = $result['file_extension'];
//             $files = [];
//         }
//     }

//     $activity_id_to_update = $data['activity_id'] ?? $product['activity_id'];
//     if ($has_file_upload) {
//         $this->db->where('id', $activity_id_to_update);
//         $activity = $this->db->get('activities')->row_array();
//         if ($activity && $activity['status'] !== 'Finalised') {
//             $this->db->where('id', $activity_id_to_update);
//             $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) {
//                 log_message('error', "Failed to update activity status to In Progress for activity_id: $activity_id_to_update");
//             }
//         }
//     }

//     $send_emails = isset($data['status']) && ($data['status'] === 'Submitted' || $data['status'] === 'Finalised') && $product['status'] !== $data['status'];

//     $this->db->where('id', $id);
//     $update = $this->db->update('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)
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'PRODUCT_NOT_UPDATED - ' . $this->db->error()['message']
//             )));
//     }

//     $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)
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'TRANSACTION_FAILED - ' . $this->db->error()['message']
//             )));
//     }

//     $this->db->where('id', $id);
//     $updated_product = $this->db->get('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']
//                 ];
//             }
//         }
//     }

//     $product_files = [];
//     if ($product_type['category'] === 'folder') {
//         $this->db->where('product_id', $id);
//         $files_data = $this->db->get('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']
//             ];
//         }
//     }

//     // Send email notifications if status changed to 'Submitted' or 'Finalised'
//     if ($send_emails) {
//         $this->load->library('phpmailer_lib');
//         $mail = $this->phpmailer_lib->load();

//         // SMTP Configuration
//         $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); // Enable HTML emails

//         // Fetch activity name
//         $this->db->where('id', $updated_product['activity_id']);
//         $activity = $this->db->get('activities')->row_array();
//         $activity_name = $activity['name'] ?? 'Unknown Activity';

//         // Common HTML template components
//         $header = '<div style="background-color: #00A1E5; height: 50px; width: 100%;"></div>';
//         $footer = '<div style="background-color: #f5f5f5; padding: 20px; font-size: 12px; color: #666; text-align: center;">'
//                 . 'SmartHub &copy; ' . date('Y') . ' | All rights reserved<br>'
//                 . '<a href="https://smarthub.ovalspace.co" style="color: #00A1E5; text-decoration: none;">Visit SmartHub</a>'
//                 . '</div>';

//         // Team notification
//         if (!empty($in_charge_ids)) {
//             $this->db->select('email');
//             $this->db->where_in('id', $in_charge_ids);
//             $team_members = $this->db->get('users')->result_array();
//             $team_emails = array_column($team_members, 'email');

//             if (!empty($team_emails)) {
//                 foreach ($team_emails as $email) {
//                     $mail->addAddress('kimbowaandrew@gmail.com'); // Debugging recipient
//                 }
//                 $mail->Subject = 'Product Status Update';
//                 $message = '<!DOCTYPE html><html><body>'
//                          . $header
//                          . '<div style="padding: 20px; font-family: Arial, sans-serif;">'
//                          . '<h2 style="color: #333;">Product Status Update</h2>'
//                          . '<p>Hello Team,</p>'
//                          . '<p>A product, <strong>' . htmlspecialchars($updated_product['name']) . '</strong>, has been ' . htmlspecialchars($data['status']) . '. It is now pending review.</p>'
//                          . '<p>Regards,<br>SmartHub Team</p>'
//                          . '</div>'
//                          . $footer
//                          . '</body></html>';
//                 $mail->Body = $message;
//                 $mail->AltBody = "Hello Team,\n\nA product, '{$updated_product['name']}', has been {$data['status']}. Pending Review.\n\nRegards,\nSmartHub";

//                 if (!$mail->send()) {
//                     log_message('error', 'Failed to send email to team: ' . $mail->ErrorInfo);
//                 }
//                 $mail->clearAddresses();
//             }
//         }

//         // Admin notification
//         $admin_emails = ['kimbowaandrew@gmail.com', 'kimbowaandrew@gmail.com'];
//         foreach ($admin_emails as $email) {
//             $mail->addAddress($email);
//         }
//         $mail->Subject = 'Product Submitted for Review/Approval';
//         $admin_message = '<!DOCTYPE html><html><body>'
//                       . $header
//                       . '<div style="padding: 20px; font-family: Arial, sans-serif;">'
//                       . '<h2 style="color: #333;">Product Submitted for Review/Approval</h2>'
//                       . '<p>Dear Sam and Racheal,</p>'
//                       . '<p>A product, <strong>' . htmlspecialchars($updated_product['name']) . '</strong>, has been ' . htmlspecialchars($data['status']) 
//                       . ' on <strong>' . htmlspecialchars($activity_name) . '</strong> for review/approval.</p>'
//                       . '<p>Regards,<br>SmartHub Team</p>'
//                       . '</div>'
//                       . $footer
//                       . '</body></html>';
//         $mail->Body = $admin_message;
//         $mail->AltBody = "Dear Sam and Racheal,\n\nA product, '{$updated_product['name']}', has been {$data['status']} on '{$activity_name}' for review/approval.\n\nRegards,\nSmartHub";

//         if (!$mail->send()) {
//             log_message('error', 'Failed to send email to admins: ' . $mail->ErrorInfo);
//         }
//     }

//     $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']
//         ]
//     ];

//     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
//     $activity_id = $this->input->post('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

//     // 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('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 {
//         $prod_type = $product['prod_type'];
//         $this->db->where('id', $prod_type);
//         $product_type = $this->db->get('product_types')->row_array();
//     }

//     $type = isset($prod_type) && $product_type['category'] === 'folder' ? 'folder' : ($product['type'] ?? '');

//     // Parse in_charge_ids
//     $in_charge_ids_array = [];
//     if (!empty($in_charge_ids)) {
//         $parsed_ids = json_decode($in_charge_ids, true);
//         if (is_array($parsed_ids)) {
//             $in_charge_ids_array = array_filter(array_map('intval', $parsed_ids));
//         } else {
//             $ids = explode(',', str_replace(['[', ']', '"'], '', $in_charge_ids));
//             $in_charge_ids_array = array_filter(array_map('trim', $ids), 'strlen');
//             $in_charge_ids_array = array_map('intval', $in_charge_ids_array);
//         }
//     }

//     // Prepare data for update
//     $data = array();
//     if (isset($activity_id)) $data['activity_id'] = $activity_id;
//     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($group)) {
//         if (!in_array($group, ['general', 'output'])) {
//             return $this->output
//                 ->set_content_type('application/json')
//                 ->set_status_header(400)
//                 ->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)
//                     ->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('outputs')->num_rows() > 0;
//             if (!$output_exists) {
//                 return $this->output
//                     ->set_content_type('application/json')
//                     ->set_status_header(400)
//                     ->set_output(json_encode(array(
//                         'success' => false,
//                         'message' => 'INVALID_OUTPUT_ID'
//                     )));
//             }
//             $data['output_id'] = $output_id;
//         } else {
//             $data['output_id'] = NULL;
//         }
//     }

//     $data['updated_by'] = $user_id;
//     $data['last_updated'] = date('Y-m-d');

//     $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';
//     }

//     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)
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_STATUS'
//             )));
//     }

//     if (isset($data['activity_id'])) {
//         $this->db->where('id', $data['activity_id']);
//         $activity_exists = $this->db->get('activities')->num_rows() > 0;
//         if (!$activity_exists) {
//             return $this->output
//                 ->set_content_type('application/json')
//                 ->set_status_header(400)
//                 ->set_output(json_encode(array(
//                     'success' => false,
//                     'message' => 'INVALID_ACTIVITY_ID'
//                 )));
//         }
//     }

//     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)
//                 ->set_output(json_encode(array(
//                     'success' => false,
//                     'message' => 'INVALID_USER_IDS_IN_IN_CHARGE'
//                 )));
//         }
//     }

//     $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)
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_USER_ID'
//             )));
//     }

//     $this->db->trans_start();

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

//     if ($product_type['category'] === 'folder') {
//         $result = $this->handle_multiple_file_uploads($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'] = '';
//     } else {
//         if (!empty($_FILES['file']['name'])) {
//             $result = $this->handle_single_file_upload('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']
//                     )));
//             }
//             $data['url'] = $result['file_url'];
//             $data['type'] = $result['file_extension'];
//             $files = [];
//         }
//     }

//     $activity_id_to_update = $data['activity_id'] ?? $product['activity_id'];
//     if ($has_file_upload) {
//         $this->db->where('id', $activity_id_to_update);
//         $activity = $this->db->get('activities')->row_array();
//         if ($activity && $activity['status'] !== 'Finalised') {
//             $this->db->where('id', $activity_id_to_update);
//             $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) {
//                 log_message('error', "Failed to update activity status to In Progress for activity_id: $activity_id_to_update");
//             }
//         }
//     }

//     $send_emails = isset($data['status']) && in_array($data['status'], ['Submitted', 'In Review', 'Finalised']) && $product['status'] !== $data['status'];

//     $this->db->where('id', $id);
//     $update = $this->db->update('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)
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'PRODUCT_NOT_UPDATED - ' . $this->db->error()['message']
//             )));
//     }

//     $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)
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'TRANSACTION_FAILED - ' . $this->db->error()['message']
//             )));
//     }

//     $this->db->where('id', $id);
//     $updated_product = $this->db->get('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']
//                 ];
//             }
//         }
//     }

//     $product_files = [];
//     if ($product_type['category'] === 'folder') {
//         $this->db->where('product_id', $id);
//         $files_data = $this->db->get('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']
//             ];
//         }
//     }

//     // Send email notifications
//     if ($send_emails) {
//         $this->load->library('phpmailer_lib');
//         $mail = $this->phpmailer_lib->load();

//         // SMTP Configuration
//         $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 activity details and relationships for the link
//         $this->db->select('a.name as activity_name, o.quarter_id, q.quarter, q.year_id, y.year, p.code as programme_code');
//         $this->db->from('activities a');
//         $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('a.id', $updated_product['activity_id']);
//         $activity_data = $this->db->get()->row_array();

//         $activity_name = $activity_data['activity_name'] ?? 'Unknown Activity';
//         $programme_code = $activity_data['programme_code'] ?? 'SDLG'; // Default to 'SDLG' if not found
//         $quarter = $activity_data['quarter'] ?? 'Q1'; // Default to 'Q1' if not found
//         $year = $activity_data['year'] ?? '2025'; // Default to current year if not found
//         $activity_link = "https://www.smarthub.ovalspace.co/ug/programmes/{$programme_code}/activities/{$quarter}/{$year}/{$updated_product['activity_id']}";

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

//         // Common HTML template components
//         $header = '<div style="background-color: #00A1E5; height: 50px; width: 100%;"></div>';
//         $footer = '<div style="background-color: #f5f5f5; padding: 20px; font-size: 12px; color: #666; text-align: center;">'
//                 . 'SmartHub © ' . date('Y') . ' | All rights reserved<br>'
//                 . '<a href="https://smarthub.ovalspace.co" style="color: #00A1E5; text-decoration: none;">Visit SmartHub</a>'
//                 . '</div>';

//         // Team notification
//         if (!empty($in_charge_ids)) {
//             $this->db->select('email');
//             $this->db->where_in('id', $in_charge_ids);
//             $team_members = $this->db->get('users')->result_array();
//             $team_emails = array_column($team_members, 'email');

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

//                 if ($data['status'] === 'In Review') {
//                     $mail->Subject = 'Product In Review';
//                     $message = '<!DOCTYPE html><html><body>'
//                              . $header
//                              . '<div style="padding: 20px; font-family: Arial, sans-serif;">'
//                              . '<h2 style="color: #333;">Product In Review</h2>'
//                              . '<p>Dear Team,</p>'
//                              . '<p>The product, <strong>' . htmlspecialchars($updated_product['name']) . '</strong> on '
//                              . '<a href="' . $activity_link . '" style="color: #00A1E5; text-decoration: none;">' . htmlspecialchars($activity_name) . '</a>, '
//                              . 'is In Review by <strong>' . htmlspecialchars($reviewer_name) . '</strong>.</p>'
//                              . '<p>Regards,<br>SmartHub Team</p>'
//                              . '</div>'
//                              . $footer
//                              . '</body></html>';
//                     $mail->Body = $message;
//                     $mail->AltBody = "Dear Team,\n\nThe product, '{$updated_product['name']}', on {$activity_name} ({$activity_link}) is In Review by {$reviewer_name}.\n\nRegards,\nSmartHub";
//                 } else {
//                     $mail->Subject = 'Product Status Update';
//                     $message = '<!DOCTYPE html><html><body>'
//                              . $header
//                              . '<div style="padding: 20px; font-family: Arial, sans-serif;">'
//                              . '<h2 style="color: #333;">Product Status Update</h2>'
//                              . '<p>Hello Team,</p>'
//                              . '<p>A product, <strong>' . htmlspecialchars($updated_product['name']) . '</strong>, has been ' . htmlspecialchars($data['status']) . '. It is now pending review.</p>'
//                              . '<p>Regards,<br>SmartHub Team</p>'
//                              . '</div>'
//                              . $footer
//                              . '</body></html>';
//                     $mail->Body = $message;
//                     $mail->AltBody = "Hello Team,\n\nA product, '{$updated_product['name']}', has been {$data['status']}. Pending Review.\n\nRegards,\nSmartHub";
//                 }

//                 if (!$mail->send()) {
//                     log_message('error', 'Failed to send email to team: ' . $mail->ErrorInfo);
//                 }
//                 $mail->clearAddresses();
//             }
//         }

//         // Admin notification
//         $admin_emails = ['kimbowaandrew@gmail.com', 'kimbowaandrew@gmail.com']; // Replace with actual admin emails later
//         foreach ($admin_emails as $email) {
//             $mail->addAddress($email);
//         }

//         if ($data['status'] === 'In Review') {
//             // Fetch the original submitter
//             $this->db->select('first_name');
//             $this->db->where('id', $product['updated_by']); // Use original updated_by before this update
//             $submitter = $this->db->get('users')->row_array();
//             $submitter_name = $submitter['first_name'] ?? 'Unknown';

//             $mail->Subject = 'Product In Review';
//             $admin_message = '<!DOCTYPE html><html><body>'
//                           . $header
//                           . '<div style="padding: 20px; font-family: Arial, sans-serif;">'
//                           . '<h2 style="color: #333;">Product In Review</h2>'
//                           . '<p>Dear Admins,</p>'
//                           . '<p>The product, <strong>' . htmlspecialchars($updated_product['name']) . '</strong> on '
//                           . '<a href="' . $activity_link . '" style="color: #00A1E5; text-decoration: none;">' . htmlspecialchars($activity_name) . '</a>, '
//                           . 'submitted by <strong>' . htmlspecialchars($submitter_name) . '</strong>, '
//                           . 'is in review by <strong>' . htmlspecialchars($reviewer_name) . '</strong>.</p>'
//                           . '<p>Regards,<br>SmartHub Team</p>'
//                           . '</div>'
//                           . $footer
//                           . '</body></html>';
//             $mail->Body = $admin_message;
//             $mail->AltBody = "Dear Admins,\n\nThe product, '{$updated_product['name']}', on {$activity_name} ({$activity_link}), submitted by {$submitter_name}, is in review by {$reviewer_name}.\n\nRegards,\nSmartHub";
//         } else {
//             $mail->Subject = 'Product Submitted for Review/Approval';
//             $admin_message = '<!DOCTYPE html><html><body>'
//                           . $header
//                           . '<div style="padding: 20px; font-family: Arial, sans-serif;">'
//                           . '<h2 style="color: #333;">Product Submitted for Review/Approval</h2>'
//                           . '<p>Dear Sam and Racheal,</p>'
//                           . '<p>A product, <strong>' . htmlspecialchars($updated_product['name']) . '</strong>, has been ' . htmlspecialchars($data['status']) 
//                           . ' on <strong>' . htmlspecialchars($activity_name) . '</strong> for review/approval.</p>'
//                           . '<p>Regards,<br>SmartHub Team</p>'
//                           . '</div>'
//                           . $footer
//                           . '</body></html>';
//             $mail->Body = $admin_message;
//             $mail->AltBody = "Dear Sam and Racheal,\n\nA product, '{$updated_product['name']}', has been {$data['status']} on '{$activity_name}' for review/approval.\n\nRegards,\nSmartHub";
//         }

//         if (!$mail->send()) {
//             log_message('error', 'Failed to send email to admins: ' . $mail->ErrorInfo);
//         }
//     }

//     $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']
//         ]
//     ];

//     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
//     $activity_id = $this->input->post('activity_id');
//     $name = $this->input->post('name');
//     $prod_type = $this->input->post('prod_type'); // ID from product_types
//     $status = $this->input->post('status');
//     $decline_reason = $this->input->post('decline_reason'); // HTML input for Declined 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

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

//     // Validate product exists
//     $this->db->where('id', $id)->where('is_active', 1);
//     $product = $this->db->get('products')->row_array();
//     if (empty($product)) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400)
//             ->set_output(json_encode(['success' => false, 'message' => 'PRODUCT_NOT_FOUND_OR_ALREADY_DELETED']));
//     }

//     // Validate prod_type if provided
//     if (isset($prod_type)) {
//         $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)
//                 ->set_output(json_encode(['success' => false, 'message' => 'INVALID_PROD_TYPE']));
//         }
//     } else {
//         $prod_type = $product['prod_type'];
//         $this->db->where('id', $prod_type);
//         $product_type = $this->db->get('product_types')->row_array();
//     }

//     $type = isset($prod_type) && $product_type['category'] === 'folder' ? 'folder' : ($product['type'] ?? '');

//     // Parse in_charge_ids
//     $in_charge_ids_array = [];
//     if (!empty($in_charge_ids)) {
//         $parsed_ids = json_decode($in_charge_ids, true);
//         if (is_array($parsed_ids)) {
//             $in_charge_ids_array = array_filter(array_map('intval', $parsed_ids));
//         } else {
//             $ids = explode(',', str_replace(['[', ']', '"'], '', $in_charge_ids));
//             $in_charge_ids_array = array_filter(array_map('trim', $ids), 'strlen');
//             $in_charge_ids_array = array_map('intval', $in_charge_ids_array);
//         }
//     }

//     // Prepare data for update
//     $data = [];
//     if (isset($activity_id)) $data['activity_id'] = $activity_id;
//     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($group)) {
//         if (!in_array($group, ['general', 'output'])) {
//             return $this->output
//                 ->set_content_type('application/json')
//                 ->set_status_header(400)
//                 ->set_output(json_encode(['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)
//                     ->set_output(json_encode(['success' => false, 'message' => 'OUTPUT_ID_REQUIRED_FOR_OUTPUT_PRODUCT']));
//             }
//             $this->db->where('id', $output_id);
//             $output_exists = $this->db->get('outputs')->num_rows() > 0;
//             if (!$output_exists) {
//                 return $this->output
//                     ->set_content_type('application/json')
//                     ->set_status_header(400)
//                     ->set_output(json_encode(['success' => false, 'message' => 'INVALID_OUTPUT_ID']));
//             }
//             $data['output_id'] = $output_id;
//         } else {
//             $data['output_id'] = NULL;
//         }
//     }

//     $data['updated_by'] = $user_id;
//     $data['last_updated'] = date('Y-m-d');

//     $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';
//     }

//     // Update valid statuses to include Declined
//     if (isset($data['status']) && !in_array($data['status'], ['Pending', 'Submitted', 'In Review', 'Declined', 'Finalised', 'Declined'])) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400)
//             ->set_output(json_encode(['success' => false, 'message' => 'INVALID_STATUS']));
//     }

//     // Require decline_reason for Declined status
//     if (isset($data['status']) && $data['status'] === 'Declined' && empty($decline_reason)) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400)
//             ->set_output(json_encode(['success' => false, 'message' => 'DECLINE_REASON_REQUIRED']));
//     }

//     if (isset($data['activity_id'])) {
//         $this->db->where('id', $data['activity_id']);
//         $activity_exists = $this->db->get('activities')->num_rows() > 0;
//         if (!$activity_exists) {
//             return $this->output
//                 ->set_content_type('application/json')
//                 ->set_status_header(400)
//                 ->set_output(json_encode(['success' => false, 'message' => 'INVALID_ACTIVITY_ID']));
//         }
//     }

//     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)
//                 ->set_output(json_encode(['success' => false, 'message' => 'INVALID_USER_IDS_IN_IN_CHARGE']));
//         }
//     }

//     $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)
//             ->set_output(json_encode(['success' => false, 'message' => 'INVALID_USER_ID']));
//     }

//     $this->db->trans_start();

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

//     if ($product_type['category'] === 'folder') {
//         $result = $this->handle_multiple_file_uploads($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(['success' => false, 'message' => $result['message']]));
//         }
//         $files = $result['files'];
//         $data['url'] = '';
//     } else {
//         if (!empty($_FILES['file']['name'])) {
//             $result = $this->handle_single_file_upload('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(['success' => false, 'message' => $result['message']]));
//             }
//             $data['url'] = $result['file_url'];
//             $data['type'] = $result['file_extension'];
//             $files = [];
//         }
//     }

//     $activity_id_to_update = $data['activity_id'] ?? $product['activity_id'];
//     if ($has_file_upload) {
//         $this->db->where('id', $activity_id_to_update);
//         $activity = $this->db->get('activities')->row_array();
//         if ($activity && $activity['status'] !== 'Finalised') {
//             $this->db->where('id', $activity_id_to_update);
//             $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) {
//                 log_message('error', "Failed to update activity status to In Progress for activity_id: $activity_id_to_update");
//             }
//         }
//     }

//     // Determine if notifications/emails should be sent
//     $send_notifications = isset($data['status']) && in_array($data['status'], ['Submitted', 'In Review', 'Finalised', 'Declined']) && $product['status'] !== $data['status'];

//     $this->db->where('id', $id);
//     $update = $this->db->update('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)
//             ->set_output(json_encode(['success' => false, 'message' => 'PRODUCT_NOT_UPDATED - ' . $this->db->error()['message']]));
//     }

//     $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)
//             ->set_output(json_encode(['success' => false, 'message' => 'TRANSACTION_FAILED - ' . $this->db->error()['message']]));
//     }

//     $this->db->where('id', $id);
//     $updated_product = $this->db->get('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']
//                 ];
//             }
//         }
//     }

//     $product_files = [];
//     if ($product_type['category'] === 'folder') {
//         $this->db->where('product_id', $id);
//         $files_data = $this->db->get('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']
//             ];
//         }
//     }

//     // Handle notifications and emails
//     if ($send_notifications) {
//         $this->load->library('phpmailer_lib');
//         $mail = $this->phpmailer_lib->load();

//         // SMTP Configuration
//         $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 activity details for the link
//         $this->db->select('a.name as activity_name, o.quarter_id, q.quarter, q.year_id, y.year, p.code as programme_code');
//         $this->db->from('activities a');
//         $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('a.id', $updated_product['activity_id']);
//         $activity_data = $this->db->get()->row_array();

//         $activity_name = $activity_data['activity_name'] ?? 'Unknown Activity';
//         $programme_code = $activity_data['programme_code'] ?? 'SDLG';
//         $quarter = $activity_data['quarter'] ?? 'Q1';
//         $year = $activity_data['year'] ?? '2025';
//         // $app_link = "https://www.smarthub.ovalspace.co/ug/programmes";
        
//         $app_link = "http://localhost:8080/ug/programmes";
//         $activity_link = $app_link."/{$programme_code}/activities/{$quarter}/{$year}/{$updated_product['activity_id']}";

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

//         // Common HTML template components
//         $header = '<div style="background-color: #143462; height: 60px; width: 100%; text-align: center; padding-top: 10px;">'
//                 . '<img src="https://www.vng-international.nl/app/data/uploads/2024/09/VNG-logo-International.svg" alt="VNG International Logo" style="height: 40px; width: auto;" />'
//                 . '</div>'
//                 . '<div style="background-color: #FDB913; height: 5px; width: 100%;"></div>';
//         $footer = '<div style="background-color: #143462; padding: 20px; font-size: 12px; color: #ffffff; text-align: center;">'
//                 . '© Copyright 2025 VNG International<br>'
//                 . '<a href="https://smarthub.ovalspace.co" style="color: #FDB913; text-decoration: none;">Visit SmartHub</a>'
//                 . '</div>';

//         // Team notification
//         if (!empty($in_charge_ids)) {
//             $this->db->select('id, email');
//             $this->db->where_in('id', $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('kimbowaandrew@gmail.com'); // Debugging recipient
//                 }

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

//                 switch ($data['status']) {
//                     case 'Submitted':
//                         $notification_title = 'Product Submitted';
//                         $notification_message = "The product '{$updated_product['name']}' on {$activity_name} has been submitted for review.";
//                         $email_subject = 'Product Submitted for Review';
//                         $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
//                                     . "<div style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
//                                     . $header
//                                     . "<div style='padding: 30px;'>"
//                                     . "<h2 style='color: #143462; margin: 0 0 20px;'>Product Submitted for Review</h2>"
//                                     . "<p style='color: #333; line-height: 1.6;'>Dear Team,</p>"
//                                     . "<p style='color: #333; line-height: 1.6;'>The product, <strong>" . htmlspecialchars($updated_product['name']) . "</strong> on "
//                                     . "<a href='$activity_link' style='color: #00A1E5; text-decoration: none;'>" . htmlspecialchars($activity_name) . "</a>, "
//                                     . "has been submitted for review.</p>"
//                                     . "<p style='color: #333; line-height: 1.6;'>Regards,<br>SmartHub Team</p>"
//                                     . "</div>$footer</div></body></html>";
//                         $email_alt_body = "Dear Team,\n\nThe product, '{$updated_product['name']}', on {$activity_name} ($activity_link) has been submitted for review.\n\nRegards,\nSmartHub";
//                         break;

//                     case 'In Review':
//                         $notification_title = 'Product In Review';
//                         $notification_message = "The product '{$updated_product['name']}' on {$activity_name} is now in review by {$reviewer_name}.";
//                         $email_subject = 'Product In Review';
//                         $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
//                                     . "<div style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
//                                     . $header
//                                     . "<div style='padding: 30px;'>"
//                                     . "<h2 style='color: #143462; margin: 0 0 20px;'>Product In Review</h2>"
//                                     . "<p style='color: #333; line-height: 1.6;'>Dear Team,</p>"
//                                     . "<p style='color: #333; line-height: 1.6;'>The product, <strong>" . htmlspecialchars($updated_product['name']) . "</strong> on "
//                                     . "<a href='$activity_link' style='color: #00A1E5; text-decoration: none;'>" . htmlspecialchars($activity_name) . "</a>, "
//                                     . "is in review by <strong>" . htmlspecialchars($reviewer_name) . "</strong>.</p>"
//                                     . "<p style='color: #333; line-height: 1.6;'>Regards,<br>SmartHub Team</p>"
//                                     . "</div>$footer</div></body></html>";
//                         $email_alt_body = "Dear Team,\n\nThe product, '{$updated_product['name']}', on {$activity_name} ($activity_link) is in review by {$reviewer_name}.\n\nRegards,\nSmartHub";
//                         break;

//                     case 'Finalised':
//                         $notification_title = 'Product Finalised';
//                         $notification_message = "The product '{$updated_product['name']}' on {$activity_name} has been finalised by {$reviewer_name}.";
//                         $email_subject = 'Product Finalised';
//                         $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
//                                     . "<div style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
//                                     . $header
//                                     . "<div style='padding: 30px;'>"
//                                     . "<h2 style='color: #143462; margin: 0 0 20px;'>Product Finalised</h2>"
//                                     . "<p style='color: #333; line-height: 1.6;'>Dear Team,</p>"
//                                     . "<p style='color: #333; line-height: 1.6;'>The product, <strong>" . htmlspecialchars($updated_product['name']) . "</strong> on "
//                                     . "<a href='$activity_link' style='color: #00A1E5; text-decoration: none;'>" . htmlspecialchars($activity_name) . "</a>, "
//                                     . "has been finalised by <strong>" . htmlspecialchars($reviewer_name) . "</strong>.</p>"
//                                     . "<p style='color: #333; line-height: 1.6;'>Congratulations on completing this milestone!</p>"
//                                     . "<p style='color: #333; line-height: 1.6;'>Regards,<br>SmartHub Team</p>"
//                                     . "</div>$footer</div></body></html>";
//                         $email_alt_body = "Dear Team,\n\nThe product, '{$updated_product['name']}', on {$activity_name} ($activity_link) has been finalised by {$reviewer_name}.\n\nCongratulations!\n\nRegards,\nSmartHub";
//                         break;

//                     case 'Declined':
//                         $notification_title = 'Product Declined';
//                         $notification_message = "The product '{$updated_product['name']}' on {$activity_name} has been declined by {$reviewer_name}. Reason: " . strip_tags($decline_reason);
//                         $email_subject = 'Product Declined';
//                         $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
//                                     . "<div style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
//                                     . $header
//                                     . "<div style='padding: 30px;'>"
//                                     . "<h2 style='color: #143462; margin: 0 0 20px;'>Product Declined</h2>"
//                                     . "<p style='color: #333; line-height: 1.6;'>Dear Team,</p>"
//                                     . "<p style='color: #333; line-height: 1.6;'>The product, <strong>" . htmlspecialchars($updated_product['name']) . "</strong> on "
//                                     . "<a href='$activity_link' style='color: #00A1E5; text-decoration: none;'>" . htmlspecialchars($activity_name) . "</a>, "
//                                     . "has been declined by <strong>" . htmlspecialchars($reviewer_name) . "</strong>.</p>"
//                                     . "<div style='background-color: #f8f8f8; border-left: 4px solid #FDB913; padding: 15px; margin: 20px 0; border-radius: 4px;'>"
//                                     . "<p style='color: #143462; 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='color: #333; line-height: 1.6;'>Please review the feedback and take necessary action.</p>"
//                                     . "<p style='color: #333; line-height: 1.6;'>Regards,<br>SmartHub Team</p>"
//                                     . "</div>$footer</div></body></html>";
//                         $email_alt_body = "Dear Team,\n\nThe product, '{$updated_product['name']}', on {$activity_name} ($activity_link) has been declined by {$reviewer_name}.\n\nReason: " . strip_tags($decline_reason) . "\n\nPlease review the feedback.\n\nRegards,\nSmartHub";
//                         break;
//                 }

//                 // Store notification for each team member
//                 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' => $activity_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 team: ' . $mail->ErrorInfo);
//                 }
//                 $mail->clearAddresses();
//             }
//         }

//         // Admin notification
//         $admin_emails = ['kimbowaandrew@gmail.com', 'kimbowaandrew@gmail.com']; // Replace with actual admin emails later
//         $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 = 'PRODUCT_STATUS_UPDATE';
//         $notification_title = '';
//         $notification_message = '';
//         $email_subject = '';
//         $email_body = '';
//         $email_alt_body = '';

//         // Fetch submitter for admin notification
//         $this->db->select('first_name');
//         $this->db->where('id', $product['updated_by']);
//         $submitter = $this->db->get('users')->row_array();
//         $submitter_name = $submitter['first_name'] ?? 'Unknown';

//         switch ($data['status']) {
//             case 'Submitted':
//                 $notification_title = 'Product Submitted for Review';
//                 $notification_message = "The product '{$updated_product['name']}' on {$activity_name} has been submitted by {$submitter_name} for review.";
//                 $email_subject = 'Product Submitted for Review/Approval';
//                 $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
//                             . "<div style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
//                             . $header
//                             . "<div style='padding: 30px;'>"
//                             . "<h2 style='color: #143462; margin: 0 0 20px;'>Product Submitted for Review/Approval</h2>"
//                             . "<p style='color: #333; line-height: 1.6;'>Dear Admins,</p>"
//                             . "<p style='color: #333; line-height: 1.6;'>The product, <strong>" . htmlspecialchars($updated_product['name']) . "</strong> on "
//                             . "<a href='$activity_link' style='color: #00A1E5; text-decoration: none;'>" . htmlspecialchars($activity_name) . "</a>, "
//                             . "has been submitted by <strong>" . htmlspecialchars($submitter_name) . "</strong> for review/approval.</p>"
//                             . "<p style='color: #333; line-height: 1.6;'>Regards,<br>SmartHub Team</p>"
//                             . "</div>$footer</div></body></html>";
//                 $email_alt_body = "Dear Admins,\n\nThe product, '{$updated_product['name']}', on {$activity_name} ($activity_link) has been submitted by {$submitter_name} for review/approval.\n\nRegards,\nSmartHub";
//                 break;

//             case 'In Review':
//                 $notification_title = 'Product In Review';
//                 $notification_message = "The product '{$updated_product['name']}' on {$activity_name}, submitted by {$submitter_name}, is now in review by {$reviewer_name}.";
//                 $email_subject = 'Product In Review';
//                 $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
//                             . "<div style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
//                             . $header
//                             . "<div style='padding: 30px;'>"
//                             . "<h2 style='color: #143462; margin: 0 0 20px;'>Product In Review</h2>"
//                             . "<p style='color: #333; line-height: 1.6;'>Dear Admins,</p>"
//                             . "<p style='color: #333; line-height: 1.6;'>The product, <strong>" . htmlspecialchars($updated_product['name']) . "</strong> on "
//                             . "<a href='$activity_link' style='color: #00A1E5; text-decoration: none;'>" . htmlspecialchars($activity_name) . "</a>, "
//                             . "submitted by <strong>" . htmlspecialchars($submitter_name) . "</strong>, is in review by <strong>" . htmlspecialchars($reviewer_name) . "</strong>.</p>"
//                             . "<p style='color: #333; line-height: 1.6;'>Regards,<br>SmartHub Team</p>"
//                             . "</div>$footer</div></body></html>";
//                 $email_alt_body = "Dear Admins,\n\nThe product, '{$updated_product['name']}', on {$activity_name} ($activity_link), submitted by {$submitter_name}, is in review by {$reviewer_name}.\n\nRegards,\nSmartHub";
//                 break;

//             case 'Finalised':
//                 $notification_title = 'Product Finalised';
//                 $notification_message = "The product '{$updated_product['name']}' on {$activity_name}, submitted by {$submitter_name}, has been finalised by {$reviewer_name}.";
//                 $email_subject = 'Product Finalised';
//                 $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
//                             . "<div style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
//                             . $header
//                             . "<div style='padding: 30px;'>"
//                             . "<h2 style='color: #143462; margin: 0 0 20px;'>Product Finalised</h2>"
//                             . "<p style='color: #333; line-height: 1.6;'>Dear Admins,</p>"
//                             . "<p style='color: #333; line-height: 1.6;'>The product, <strong>" . htmlspecialchars($updated_product['name']) . "</strong> on "
//                             . "<a href='$activity_link' style='color: #00A1E5; text-decoration: none;'>" . htmlspecialchars($activity_name) . "</a>, "
//                             . "submitted by <strong>" . htmlspecialchars($submitter_name) . "</strong>, has been finalised by <strong>" . htmlspecialchars($reviewer_name) . "</strong>.</p>"
//                             . "<p style='color: #333; line-height: 1.6;'>Regards,<br>SmartHub Team</p>"
//                             . "</div>$footer</div></body></html>";
//                 $email_alt_body = "Dear Admins,\n\nThe product, '{$updated_product['name']}', on {$activity_name} ($activity_link), submitted by {$submitter_name}, has been finalised by {$reviewer_name}.\n\nRegards,\nSmartHub";
//                 break;

//             case 'Declined':
//                 $notification_title = 'Product Declined';
//                 $notification_message = "The product '{$updated_product['name']}' on {$activity_name}, submitted by {$submitter_name}, has been declined by {$reviewer_name}. Reason: " . strip_tags($decline_reason);
//                 $email_subject = 'Product Declined';
//                 $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
//                             . "<div style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
//                             . $header
//                             . "<div style='padding: 30px;'>"
//                             . "<h2 style='color: #143462; margin: 0 0 20px;'>Product Declined</h2>"
//                             . "<p style='color: #333; line-height: 1.6;'>Dear Admins,</p>"
//                             . "<p style='color: #333; line-height: 1.6;'>The product, <strong>" . htmlspecialchars($updated_product['name']) . "</strong> on "
//                             . "<a href='$activity_link' style='color: #00A1E5; text-decoration: none;'>" . htmlspecialchars($activity_name) . "</a>, "
//                             . "submitted by <strong>" . htmlspecialchars($submitter_name) . "</strong>, has been declined by <strong>" . htmlspecialchars($reviewer_name) . "</strong>.</p>"
//                             . "<div style='background-color: #f8f8f8; border-left: 4px solid #FDB913; padding: 15px; margin: 20px 0; border-radius: 4px;'>"
//                             . "<p style='color: #143462; 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='color: #333; line-height: 1.6;'>Regards,<br>SmartHub Team</p>"
//                             . "</div>$footer</div></body></html>";
//                 $email_alt_body = "Dear Admins,\n\nThe product, '{$updated_product['name']}', on {$activity_name} ($activity_link), submitted by {$submitter_name}, has been declined by {$reviewer_name}.\n\nReason: " . strip_tags($decline_reason) . "\n\nRegards,\nSmartHub";
//                 break;
//         }

//         // Store notification for each admin
//         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' => $activity_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);
//         }
//     }

//     $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']
//         ]
//     ];

//     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
//     $activity_id = $this->input->post('activity_id');
//     $name = $this->input->post('name');
//     $prod_type = $this->input->post('prod_type'); // ID from product_types
//     $status = $this->input->post('status');
//     $decline_reason = $this->input->post('decline_reason'); // HTML input for Declined 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

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

//     // Validate product exists
//     $this->db->where('id', $id)->where('is_active', 1);
//     $product = $this->db->get('products')->row_array();
//     if (empty($product)) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400)
//             ->set_output(json_encode(['success' => false, 'message' => 'PRODUCT_NOT_FOUND_OR_ALREADY_DELETED']));
//     }

//     // Validate prod_type if provided
//     if (isset($prod_type)) {
//         $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)
//                 ->set_output(json_encode(['success' => false, 'message' => 'INVALID_PROD_TYPE']));
//         }
//     } else {
//         $prod_type = $product['prod_type'];
//         $this->db->where('id', $prod_type);
//         $product_type = $this->db->get('product_types')->row_array();
//     }

//     $type = isset($prod_type) && $product_type['category'] === 'folder' ? 'folder' : ($product['type'] ?? '');

//     // Parse in_charge_ids
//     $in_charge_ids_array = [];
//     if (!empty($in_charge_ids)) {
//         $parsed_ids = json_decode($in_charge_ids, true);
//         if (is_array($parsed_ids)) {
//             $in_charge_ids_array = array_filter(array_map('intval', $parsed_ids));
//         } else {
//             $ids = explode(',', str_replace(['[', ']', '"'], '', $in_charge_ids));
//             $in_charge_ids_array = array_filter(array_map('trim', $ids), 'strlen');
//             $in_charge_ids_array = array_map('intval', $in_charge_ids_array);
//         }
//     }

//     // Prepare data for update
//     $data = [];
//     if (isset($activity_id)) $data['activity_id'] = $activity_id;
//     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($group)) {
//         if (!in_array($group, ['general', 'output'])) {
//             return $this->output
//                 ->set_content_type('application/json')
//                 ->set_status_header(400)
//                 ->set_output(json_encode(['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)
//                     ->set_output(json_encode(['success' => false, 'message' => 'OUTPUT_ID_REQUIRED_FOR_OUTPUT_PRODUCT']));
//             }
//             $this->db->where('id', $output_id);
//             $output_exists = $this->db->get('outputs')->num_rows() > 0;
//             if (!$output_exists) {
//                 return $this->output
//                     ->set_content_type('application/json')
//                     ->set_status_header(400)
//                     ->set_output(json_encode(['success' => false, 'message' => 'INVALID_OUTPUT_ID']));
//             }
//             $data['output_id'] = $output_id;
//         } else {
//             $data['output_id'] = NULL;
//         }
//     }

//     $data['updated_by'] = $user_id;
//     $data['last_updated'] = date('Y-m-d');

//     $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';
//     }

//     // Update valid statuses to include Declined
//     if (isset($data['status']) && !in_array($data['status'], ['Pending', 'Submitted', 'In Review', 'Declined', 'Finalised', 'Declined'])) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400)
//             ->set_output(json_encode(['success' => false, 'message' => 'INVALID_STATUS']));
//     }

//     // Require decline_reason for Declined status
//     if (isset($data['status']) && $data['status'] === 'Declined' && empty($decline_reason)) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400)
//             ->set_output(json_encode(['success' => false, 'message' => 'DECLINE_REASON_REQUIRED']));
//     }

//     if (isset($data['activity_id'])) {
//         $this->db->where('id', $data['activity_id']);
//         $activity_exists = $this->db->get('activities')->num_rows() > 0;
//         if (!$activity_exists) {
//             return $this->output
//                 ->set_content_type('application/json')
//                 ->set_status_header(400)
//                 ->set_output(json_encode(['success' => false, 'message' => 'INVALID_ACTIVITY_ID']));
//         }
//     }

//     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)
//                 ->set_output(json_encode(['success' => false, 'message' => 'INVALID_USER_IDS_IN_IN_CHARGE']));
//         }
//     }

//     $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)
//             ->set_output(json_encode(['success' => false, 'message' => 'INVALID_USER_ID']));
//     }

//     $this->db->trans_start();

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

//     if ($product_type['category'] === 'folder') {
//         $result = $this->handle_multiple_file_uploads($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(['success' => false, 'message' => $result['message']]));
//         }
//         $files = $result['files'];
//         $data['url'] = '';
//     } else {
//         if (!empty($_FILES['file']['name'])) {
//             $result = $this->handle_single_file_upload('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(['success' => false, 'message' => $result['message']]));
//             }
//             $data['url'] = $result['file_url'];
//             $data['type'] = $result['file_extension'];
//             $files = [];
//         }
//     }

//     $activity_id_to_update = $data['activity_id'] ?? $product['activity_id'];
//     if ($has_file_upload) {
//         $this->db->where('id', $activity_id_to_update);
//         $activity = $this->db->get('activities')->row_array();
//         if ($activity && $activity['status'] !== 'Finalised') {
//             $this->db->where('id', $activity_id_to_update);
//             $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) {
//                 log_message('error', "Failed to update activity status to In Progress for activity_id: $activity_id_to_update");
//             }
//         }
//     }

//     // Determine if notifications/emails should be sent
//     $send_notifications = isset($data['status']) && in_array($data['status'], ['Submitted', 'In Review', 'Finalised', 'Declined']) && $product['status'] !== $data['status'];

//     $this->db->where('id', $id);
//     $update = $this->db->update('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)
//             ->set_output(json_encode(['success' => false, 'message' => 'PRODUCT_NOT_UPDATED - ' . $this->db->error()['message']]));
//     }

//     $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)
//             ->set_output(json_encode(['success' => false, 'message' => 'TRANSACTION_FAILED - ' . $this->db->error()['message']]));
//     }

//     $this->db->where('id', $id);
//     $updated_product = $this->db->get('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']
//                 ];
//             }
//         }
//     }

//     $product_files = [];
//     if ($product_type['category'] === 'folder') {
//         $this->db->where('product_id', $id);
//         $files_data = $this->db->get('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']
//             ];
//         }
//     }

//     // Handle notifications and emails
//     if ($send_notifications) {
//         $this->load->library('phpmailer_lib');
//         $mail = $this->phpmailer_lib->load();

//         // SMTP Configuration
//         $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 activity details for the link
//         $this->db->select('a.name as activity_name, o.quarter_id, q.quarter, q.year_id, y.year, p.code as programme_code');
//         $this->db->from('activities a');
//         $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('a.id', $updated_product['activity_id']);
//         $activity_data = $this->db->get()->row_array();

//         $activity_name = $activity_data['activity_name'] ?? 'Unknown Activity';
//         $programme_code = $activity_data['programme_code'] ?? 'SDLG';
//         $quarter = $activity_data['quarter'] ?? 'Q1';
//         $year = $activity_data['year'] ?? '2025';
//         $app_link = "http://localhost:8080/ug/programmes"; // Using your local link
//         $activity_link = $app_link . "/{$programme_code}/activities/{$quarter}/{$year}/{$updated_product['activity_id']}";

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

//      // Common HTML 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;" />'
//         . '</div>';
// $footer = '<div style="font-size: 10px; color: #333; text-align: center;">'
//         . 'Copyright 2025 VNG International | SmartHub<br>'
//         . '<a href="https://smarthub.ovalspace.co" style="color: white; text-decoration: none;">Visit SmartHub</a>'
//         . '</div>';

//         // Team notification
//         if (!empty($in_charge_ids)) {
//             $this->db->select('id, email');
//             $this->db->where_in('id', $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('kimbowaandrew@gmail.com'); // Debugging recipient
//                 }

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

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

//                     case 'In Review':
//                         $notification_title = 'Product In Review';
//                         $notification_message = "The product '{$updated_product['name']}' on {$activity_name} is now in review by {$reviewer_name}.";
//                         $email_subject = 'Product In Review';
//                         $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
//                                     . "<div style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
//                                     . $header
//                                     . "<div style='padding: 30px;'>"
//                                     . "<h2 style='color: #333; margin: 0 0 20px;'>Product In Review</h2>"
//                                     . "<p style='color: #333; line-height: 1.6;'>Dear Team,</p>"
//                                     . "<p style='color: #333; line-height: 1.6;'>The product, <strong>" . htmlspecialchars($updated_product['name']) . "</strong> on "
//                                     . "<a href='$activity_link' style='color: #00A1E5; text-decoration: none;'>" . htmlspecialchars($activity_name) . "</a>, "
//                                     . "is in review by <strong>" . htmlspecialchars($reviewer_name) . "</strong>.</p>"
//                                     . "<p style='color: #333; line-height: 1.6;'>Regards,<br>SmartHub Team</p>"
//                                     . "</div>$footer</div></body></html>";
//                         $email_alt_body = "Dear Team,\n\nThe product, '{$updated_product['name']}', on {$activity_name} ($activity_link) is in review by {$reviewer_name}.\n\nRegards,\nSmartHub";
//                         break;

//                     case 'Finalised':
//                         $notification_title = 'Product Finalised';
//                         $notification_message = "The product '{$updated_product['name']}' on {$activity_name} has been finalised by {$reviewer_name}.";
//                         $email_subject = 'Product Finalised';
//                         $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
//                                     . "<div style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
//                                     . $header
//                                     . "<div style='padding: 30px;'>"
//                                     . "<h2 style='color: #333; margin: 0 0 20px;'>Product Finalised</h2>"
//                                     . "<p style='color: #333; line-height: 1.6;'>Dear Team,</p>"
//                                     . "<p style='color: #333; line-height: 1.6;'>The product, <strong>" . htmlspecialchars($updated_product['name']) . "</strong> on "
//                                     . "<a href='$activity_link' style='color: #00A1E5; text-decoration: none;'>" . htmlspecialchars($activity_name) . "</a>, "
//                                     . "has been finalised by <strong>" . htmlspecialchars($reviewer_name) . "</strong>.</p>"
//                                     . "<p style='color: #333; line-height: 1.6;'>Congratulations on completing this milestone!</p>"
//                                     . "<p style='color: #333; line-height: 1.6;'>Regards,<br>SmartHub Team</p>"
//                                     . "</div>$footer</div></body></html>";
//                         $email_alt_body = "Dear Team,\n\nThe product, '{$updated_product['name']}', on {$activity_name} ($activity_link) has been finalised by {$reviewer_name}.\n\nCongratulations!\n\nRegards,\nSmartHub";
//                         break;

//                     case 'Declined':
//                         $notification_title = 'Product Declined';
//                         $notification_message = "The product '{$updated_product['name']}' on {$activity_name} has been declined by {$reviewer_name}. Reason: " . strip_tags($decline_reason);
//                         $email_subject = 'Product Declined';
//                         $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
//                                     . "<div style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
//                                     . $header
//                                     . "<div style='padding: 30px;'>"
//                                     . "<h2 style='color: #333; margin: 0 0 20px;'>Product Declined</h2>"
//                                     . "<p style='color: #333; line-height: 1.6;'>Dear Team,</p>"
//                                     . "<p style='color: #333; line-height: 1.6;'>The product, <strong>" . htmlspecialchars($updated_product['name']) . "</strong> on "
//                                     . "<a href='$activity_link' style='color: #00A1E5; text-decoration: none;'>" . htmlspecialchars($activity_name) . "</a>, "
//                                     . "has been declined by <strong>" . htmlspecialchars($reviewer_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='color: #333; line-height: 1.6;'>Please review the feedback and take necessary action.</p>"
//                                     . "<p style='color: #333; line-height: 1.6;'>Regards,<br>SmartHub Team</p>"
//                                     . "</div>$footer</div></body></html>";
//                         $email_alt_body = "Dear Team,\n\nThe product, '{$updated_product['name']}', on {$activity_name} ($activity_link) has been declined by {$reviewer_name}.\n\nReason: " . strip_tags($decline_reason) . "\n\nPlease review the feedback.\n\nRegards,\nSmartHub";
//                         break;
//                 }

//                 // Store notification for each team member
//                 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' => $activity_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 team: ' . $mail->ErrorInfo);
//                 }
//                 $mail->clearAddresses();
//             }
//         }

//         // Admin notification
//         $admin_emails = ['kimbowaandrew@gmail.com', 'kimbowaandrew@gmail.com']; // Replace with actual admin emails later
//         $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 = 'PRODUCT_STATUS_UPDATE';
//         $notification_title = '';
//         $notification_message = '';
//         $email_subject = '';
//         $email_body = '';
//         $email_alt_body = '';

//         // Fetch submitter for admin notification
//         $this->db->select('first_name');
//         $this->db->where('id', $product['updated_by']);
//         $submitter = $this->db->get('users')->row_array();
//         $submitter_name = $submitter['first_name'] ?? 'Unknown';

//         switch ($data['status']) {
//             case 'Submitted':
//                 $notification_title = 'Product Submitted for Review';
//                 $notification_message = "The product '{$updated_product['name']}' on {$activity_name} has been submitted by {$submitter_name} for review.";
//                 $email_subject = 'Product Submitted for Review/Approval';
//                 $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
//                             . "<div style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
//                             . $header
//                             . "<div style='padding: 30px;'>"
//                             . "<h2 style='color: #333; margin: 0 0 20px;'>Product Submitted for Review/Approval</h2>"
//                             . "<p style='color: #333; line-height: 1.6;'>Dear Admins,</p>"
//                             . "<p style='color: #333; line-height: 1.6;'>The product, <strong>" . htmlspecialchars($updated_product['name']) . "</strong> on "
//                             . "<a href='$activity_link' style='color: #00A1E5; text-decoration: none;'>" . htmlspecialchars($activity_name) . "</a>, "
//                             . "has been submitted by <strong>" . htmlspecialchars($submitter_name) . "</strong> for review/approval.</p>"
//                             . "<p style='color: #333; line-height: 1.6;'>Regards,<br>SmartHub Team</p>"
//                             . "</div>$footer</div></body></html>";
//                 $email_alt_body = "Dear Admins,\n\nThe product, '{$updated_product['name']}', on {$activity_name} ($activity_link) has been submitted by {$submitter_name} for review/approval.\n\nRegards,\nSmartHub";
//                 break;

//             case 'In Review':
//                 $notification_title = 'Product In Review';
//                 $notification_message = "The product '{$updated_product['name']}' on {$activity_name}, submitted by {$submitter_name}, is now in review by {$reviewer_name}.";
//                 $email_subject = 'Product In Review';
//                 $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
//                             . "<div style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
//                             . $header
//                             . "<div style='padding: 30px;'>"
//                             . "<h2 style='color: #333; margin: 0 0 20px;'>Product In Review</h2>"
//                             . "<p style='color: #333; line-height: 1.6;'>Dear Admins,</p>"
//                             . "<p style='color: #333; line-height: 1.6;'>The product, <strong>" . htmlspecialchars($updated_product['name']) . "</strong> on "
//                             . "<a href='$activity_link' style='color: #00A1E5; text-decoration: none;'>" . htmlspecialchars($activity_name) . "</a>, "
//                             . "submitted by <strong>" . htmlspecialchars($submitter_name) . "</strong>, is in review by <strong>" . htmlspecialchars($reviewer_name) . "</strong>.</p>"
//                             . "<p style='color: #333; line-height: 1.6;'>Regards,<br>SmartHub Team</p>"
//                             . "</div>$footer</div></body></html>";
//                 $email_alt_body = "Dear Admins,\n\nThe product, '{$updated_product['name']}', on {$activity_name} ($activity_link), submitted by {$submitter_name}, is in review by {$reviewer_name}.\n\nRegards,\nSmartHub";
//                 break;

//             case 'Finalised':
//                 $notification_title = 'Product Finalised';
//                 $notification_message = "The product '{$updated_product['name']}' on {$activity_name}, submitted by {$submitter_name}, has been finalised by {$reviewer_name}.";
//                 $email_subject = 'Product Finalised';
//                 $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
//                             . "<div style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
//                             . $header
//                             . "<div style='padding: 30px;'>"
//                             . "<h2 style='color: #333; margin: 0 0 20px;'>Product Finalised</h2>"
//                             . "<p style='color: #333; line-height: 1.6;'>Dear Admins,</p>"
//                             . "<p style='color: #333; line-height: 1.6;'>The product, <strong>" . htmlspecialchars($updated_product['name']) . "</strong> on "
//                             . "<a href='$activity_link' style='color: #00A1E5; text-decoration: none;'>" . htmlspecialchars($activity_name) . "</a>, "
//                             . "submitted by <strong>" . htmlspecialchars($submitter_name) . "</strong>, has been finalised by <strong>" . htmlspecialchars($reviewer_name) . "</strong>.</p>"
//                             . "<p style='color: #333; line-height: 1.6;'>Regards,<br>SmartHub Team</p>"
//                             . "</div>$footer</div></body></html>";
//                 $email_alt_body = "Dear Admins,\n\nThe product, '{$updated_product['name']}', on {$activity_name} ($activity_link), submitted by {$submitter_name}, has been finalised by {$reviewer_name}.\n\nRegards,\nSmartHub";
//                 break;

//             case 'Declined':
//                 $notification_title = 'Product Declined';
//                 $notification_message = "The product '{$updated_product['name']}' on {$activity_name}, submitted by {$submitter_name}, has been declined by {$reviewer_name}. Reason: " . strip_tags($decline_reason);
//                 $email_subject = 'Product Declined';
//                 $email_body = "<!DOCTYPE html><html><body style='margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #f4f4f4;'>"
//                             . "<div style='max-width: 600px; margin: 20px auto; background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);'>"
//                             . $header
//                             . "<div style='padding: 30px;'>"
//                             . "<h2 style='color: #333; margin: 0 0 20px;'>Product Declined</h2>"
//                             . "<p style='color: #333; line-height: 1.6;'>Dear Admins,</p>"
//                             . "<p style='color: #333; line-height: 1.6;'>The product, <strong>" . htmlspecialchars($updated_product['name']) . "</strong> on "
//                             . "<a href='$activity_link' style='color: #00A1E5; text-decoration: none;'>" . htmlspecialchars($activity_name) . "</a>, "
//                             . "submitted by <strong>" . htmlspecialchars($submitter_name) . "</strong>, has been declined by <strong>" . htmlspecialchars($reviewer_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='color: #333; line-height: 1.6;'>Regards,<br>SmartHub Team</p>"
//                             . "</div>$footer</div></body></html>";
//                 $email_alt_body = "Dear Admins,\n\nThe product, '{$updated_product['name']}', on {$activity_name} ($activity_link), submitted by {$submitter_name}, has been declined by {$reviewer_name}.\n\nReason: " . strip_tags($decline_reason) . "\n\nRegards,\nSmartHub";
//                 break;
//         }

//         // Store notification for each admin
//         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' => $activity_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);
//         }
//     }

//     $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']
//         ]
//     ];

//     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
//     $activity_id = $this->input->post('activity_id');
//     $name = $this->input->post('name');
//     $prod_type = $this->input->post('prod_type'); // ID from product_types
//     $status = $this->input->post('status');
//     $decline_reason = $this->input->post('decline_reason'); // HTML input for Declined 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

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

//     // Validate product exists
//     $this->db->where('id', $id)->where('is_active', 1);
//     $product = $this->db->get('products')->row_array();
//     if (empty($product)) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400)
//             ->set_output(json_encode(['success' => false, 'message' => 'PRODUCT_NOT_FOUND_OR_ALREADY_DELETED']));
//     }

//     // Validate prod_type if provided
//     if (isset($prod_type)) {
//         $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)
//                 ->set_output(json_encode(['success' => false, 'message' => 'INVALID_PROD_TYPE']));
//         }
//     } else {
//         $prod_type = $product['prod_type'];
//         $this->db->where('id', $prod_type);
//         $product_type = $this->db->get('product_types')->row_array();
//     }

//     $type = isset($prod_type) && $product_type['category'] === 'folder' ? 'folder' : ($product['type'] ?? '');

//     // Parse in_charge_ids
//     $in_charge_ids_array = [];
//     if (!empty($in_charge_ids)) {
//         $parsed_ids = json_decode($in_charge_ids, true);
//         if (is_array($parsed_ids)) {
//             $in_charge_ids_array = array_filter(array_map('intval', $parsed_ids));
//         } else {
//             $ids = explode(',', str_replace(['[', ']', '"'], '', $in_charge_ids));
//             $in_charge_ids_array = array_filter(array_map('trim', $ids), 'strlen');
//             $in_charge_ids_array = array_map('intval', $in_charge_ids_array);
//         }
//     }

//     // Prepare data for update
//     $data = [];
//     if (isset($activity_id)) $data['activity_id'] = $activity_id;
//     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($group)) {
//         if (!in_array($group, ['general', 'output'])) {
//             return $this->output
//                 ->set_content_type('application/json')
//                 ->set_status_header(400)
//                 ->set_output(json_encode(['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)
//                     ->set_output(json_encode(['success' => false, 'message' => 'OUTPUT_ID_REQUIRED_FOR_OUTPUT_PRODUCT']));
//             }
//             $this->db->where('id', $output_id);
//             $output_exists = $this->db->get('outputs')->num_rows() > 0;
//             if (!$output_exists) {
//                 return $this->output
//                     ->set_content_type('application/json')
//                     ->set_status_header(400)
//                     ->set_output(json_encode(['success' => false, 'message' => 'INVALID_OUTPUT_ID']));
//             }
//             $data['output_id'] = $output_id;
//         } else {
//             $data['output_id'] = NULL;
//         }
//     }

//     $data['updated_by'] = $user_id;
//     $data['last_updated'] = date('Y-m-d');

//     $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';
//     }

//     // Update valid statuses to include Declined
//     if (isset($data['status']) && !in_array($data['status'], ['Pending', 'Submitted', 'In Review', 'Finalised', 'Declined'])) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400)
//             ->set_output(json_encode(['success' => false, 'message' => 'INVALID_STATUS']));
//     }

//     // Require decline_reason for Declined status
//     if (isset($data['status']) && $data['status'] === 'Declined' && empty($decline_reason)) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400)
//             ->set_output(json_encode(['success' => false, 'message' => 'DECLINE_REASON_REQUIRED']));
//     }

//     if (isset($data['activity_id'])) {
//         $this->db->where('id', $data['activity_id']);
//         $activity_exists = $this->db->get('activities')->num_rows() > 0;
//         if (!$activity_exists) {
//             return $this->output
//                 ->set_content_type('application/json')
//                 ->set_status_header(400)
//                 ->set_output(json_encode(['success' => false, 'message' => 'INVALID_ACTIVITY_ID']));
//         }
//     }

//     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)
//                 ->set_output(json_encode(['success' => false, 'message' => 'INVALID_USER_IDS_IN_IN_CHARGE']));
//         }
//     }

//     $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)
//             ->set_output(json_encode(['success' => false, 'message' => 'INVALID_USER_ID']));
//     }

//     $this->db->trans_start();

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

//     if ($product_type['category'] === 'folder') {
//         $result = $this->handle_multiple_file_uploads($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(['success' => false, 'message' => $result['message']]));
//         }
//         $files = $result['files'];
//         $data['url'] = '';
//     } else {
//         if (!empty($_FILES['file']['name'])) {
//             $result = $this->handle_single_file_upload('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(['success' => false, 'message' => $result['message']]));
//             }
//             $data['url'] = $result['file_url'];
//             $data['type'] = $result['file_extension'];
//             $files = [];
//         }
//     }

//     $activity_id_to_update = $data['activity_id'] ?? $product['activity_id'];
//     if ($has_file_upload) {
//         $this->db->where('id', $activity_id_to_update);
//         $activity = $this->db->get('activities')->row_array();
//         if ($activity && $activity['status'] !== 'Finalised') {
//             $this->db->where('id', $activity_id_to_update);
//             $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) {
//                 log_message('error', "Failed to update activity status to In Progress for activity_id: $activity_id_to_update");
//             }
//         }
//     }

//     // Determine if notifications/emails should be sent
//     $send_notifications = isset($data['status']) && in_array($data['status'], ['Submitted', 'In Review', 'Finalised', 'Declined']) && $product['status'] !== $data['status'];

//     $this->db->where('id', $id);
//     $update = $this->db->update('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)
//             ->set_output(json_encode(['success' => false, 'message' => 'PRODUCT_NOT_UPDATED - ' . $this->db->error()['message']]));
//     }

//     $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)
//             ->set_output(json_encode(['success' => false, 'message' => 'TRANSACTION_FAILED - ' . $this->db->error()['message']]));
//     }

//     $this->db->where('id', $id);
//     $updated_product = $this->db->get('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']
//                 ];
//             }
//         }
//     }

//     $product_files = [];
//     if ($product_type['category'] === 'folder') {
//         $this->db->where('product_id', $id);
//         $files_data = $this->db->get('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']
//             ];
//         }
//     }

//     // Handle notifications and emails
//     if ($send_notifications) {
//         $this->load->library('phpmailer_lib');
//         $mail = $this->phpmailer_lib->load();

//         // SMTP Configuration
//         $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 activity details for the link
//         $this->db->select('a.name as activity_name, o.quarter_id, q.quarter, q.year_id, y.year, p.code as programme_code');
//         $this->db->from('activities a');
//         $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('a.id', $updated_product['activity_id']);
//         $activity_data = $this->db->get()->row_array();

//         $activity_name = $activity_data['activity_name'] ?? 'Unknown Activity';
//         $programme_code = $activity_data['programme_code'] ?? 'SDLG';
//         $quarter = $activity_data['quarter'] ?? 'Q1';
//         $year = $activity_data['year'] ?? '2025';
//         $app_link = "http://localhost:8080/ug/programmes";
//         $activity_link = "$app_link/{$programme_code}/activities/{$quarter}/{$year}/{$updated_product['activity_id']}";

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

//         // Common HTML 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>';

//         // Team notification
//         if (!empty($in_charge_ids_array)) {
//             $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("kimbowaandrew@gmail.com"); // Use actual team emails
//                 }

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

//                 switch ($data['status']) {
//                     case 'Submitted':
//                         $notification_title = 'Product Submitted';
//                         $notification_message = "The product \"{$updated_product['name']}\" on activity: {$activity_name} has been submitted by {$reviewer_name} for review.";
//                         $email_subject = '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;'>Product Submitted for Review</h2>"
//                             . "<p style='margin: 0 0 15px;'>Dear Team,</p>"
//                             . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($updated_product['name']) . "</strong>\" on activity: "
//                             . "<a href='$activity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($activity_name) . "</a>, "
//                             . "has been submitted by <strong>" . htmlspecialchars($reviewer_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, \"{$updated_product['name']}\", on activity: {$activity_name} ($activity_link) has been submitted by {$reviewer_name} for review.\n\nRegards,\nSmartHub";
//                         break;

//                     case 'In Review':
//                         $notification_title = 'Product In Review';
//                         $notification_message = "The product \"{$updated_product['name']}\" on activity: {$activity_name} is now in review by {$reviewer_name}.";
//                         $email_subject = '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;'>Product In Review</h2>"
//                             . "<p style='margin: 0 0 15px;'>Dear Team,</p>"
//                             . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($updated_product['name']) . "</strong>\" on activity: "
//                             . "<a href='$activity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($activity_name) . "</a>, "
//                             . "is now in review by <strong>" . htmlspecialchars($reviewer_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, \"{$updated_product['name']}\", on activity: {$activity_name} ($activity_link) is now in review by {$reviewer_name}.\n\nRegards,\nSmartHub";
//                         break;

//                     case 'Finalised':
//                         $notification_title = 'Product Finalised';
//                         $notification_message = "The product \"{$updated_product['name']}\" on activity: {$activity_name} has been finalised by {$reviewer_name}.";
//                         $email_subject = '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;'>Product Finalised</h2>"
//                             . "<p style='margin: 0 0 15px;'>Dear Team,</p>"
//                             . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($updated_product['name']) . "</strong>\" on activity: "
//                             . "<a href='$activity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($activity_name) . "</a>, "
//                             . "has been finalised by <strong>" . htmlspecialchars($reviewer_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, \"{$updated_product['name']}\", on activity: {$activity_name} ($activity_link) has been finalised by {$reviewer_name}.\n\nRegards,\nSmartHub";
//                         break;

//                     case 'Declined':
//                         $notification_title = 'Product Declined';
//                         $notification_message = "The product \"{$updated_product['name']}\" on activity: {$activity_name} has been declined by {$reviewer_name}. Reason: " . strip_tags($decline_reason);
//                         $email_subject = '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;'>Product Declined</h2>"
//                             . "<p style='margin: 0 0 15px;'>Dear Team,</p>"
//                             . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($updated_product['name']) . "</strong>\" on activity: "
//                             . "<a href='$activity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($activity_name) . "</a>, "
//                             . "has been declined by <strong>" . htmlspecialchars($reviewer_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 Team,\n\nThe product, \"{$updated_product['name']}\", on activity: {$activity_name} ($activity_link) has been declined by {$reviewer_name}.\n\nReason: " . strip_tags($decline_reason) . "\n\nRegards,\nSmartHub";
//                         break;
//                 }

//                 // Store notification for each team member
//                 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' => $activity_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 team: ' . $mail->ErrorInfo);
//                 }
//                 $mail->clearAddresses();
//             }
//         }

//         // Admin notification
//         $admin_emails = ['kimbowaandrew@gmail.com', 'kimbowaandrew@gmail.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);
//         }

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

//         switch ($data['status']) {
//             case 'Submitted':
//                 $notification_title = 'Product Submitted for Review';
//                 $notification_message = "The product \"{$updated_product['name']}\" on activity: {$activity_name} has been submitted by {$reviewer_name} for review.";
//                 $email_subject = '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;'>Product Submitted for Review/Approval</h2>"
//                     . "<p style='margin: 0 0 15px;'>Dear Admins,</p>"
//                     . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($updated_product['name']) . "</strong>\" on activity: "
//                     . "<a href='$activity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($activity_name) . "</a>, "
//                     . "has been submitted by <strong>" . htmlspecialchars($reviewer_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 Admins,\n\nThe product, \"{$updated_product['name']}\", on activity: {$activity_name} ($activity_link) has been submitted by {$reviewer_name} for review.\n\nRegards,\nSmartHub";
//                 break;

//             case 'In Review':
//                 $notification_title = 'Product In Review';
//                 $notification_message = "The product \"{$updated_product['name']}\" on activity: {$activity_name} is now in review by {$reviewer_name}.";
//                 $email_subject = '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;'>Product In Review</h2>"
//                     . "<p style='margin: 0 0 15px;'>Dear Admins,</p>"
//                     . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($updated_product['name']) . "</strong>\" on activity: "
//                     . "<a href='$activity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($activity_name) . "</a>, "
//                     . "is now in review by <strong>" . htmlspecialchars($reviewer_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 Admins,\n\nThe product, \"{$updated_product['name']}\", on activity: {$activity_name} ($activity_link) is now in review by {$reviewer_name}.\n\nRegards,\nSmartHub";
//                 break;

//             case 'Finalised':
//                 $notification_title = 'Product Finalised';
//                 $notification_message = "The product \"{$updated_product['name']}\" on activity: {$activity_name} has been finalised by {$reviewer_name}.";
//                 $email_subject = '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;'>Product Finalised</h2>"
//                     . "<p style='margin: 0 0 15px;'>Dear Admins,</p>"
//                     . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($updated_product['name']) . "</strong>\" on activity: "
//                     . "<a href='$activity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($activity_name) . "</a>, "
//                     . "has been finalised by <strong>" . htmlspecialchars($reviewer_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 Admins,\n\nThe product, \"{$updated_product['name']}\", on activity: {$activity_name} ($activity_link) has been finalised by {$reviewer_name}.\n\nRegards,\nSmartHub";
//                 break;

//             case 'Declined':
//                 $notification_title = 'Product Declined';
//                 $notification_message = "The product \"{$updated_product['name']}\" on activity: {$activity_name} has been declined by {$reviewer_name}. Reason: " . strip_tags($decline_reason);
//                 $email_subject = '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;'>Product Declined</h2>"
//                     . "<p style='margin: 0 0 15px;'>Dear Admins,</p>"
//                     . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($updated_product['name']) . "</strong>\" on activity: "
//                     . "<a href='$activity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($activity_name) . "</a>, "
//                     . "has been declined by <strong>" . htmlspecialchars($reviewer_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 Admins,\n\nThe product, \"{$updated_product['name']}\", on activity: {$activity_name} ($activity_link) has been declined by {$reviewer_name}.\n\nReason: " . strip_tags($decline_reason) . "\n\nRegards,\nSmartHub";
//                 break;
//         }

//         // Store notification for each admin
//         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' => $activity_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);
//         }
//     }

//     $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']
//         ]
//     ];

//     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
//     $activity_id = $this->input->post('activity_id');
//     $name = $this->input->post('name');
//     $prod_type = $this->input->post('prod_type'); // ID from product_types
//     $status = $this->input->post('status');
//     $decline_reason = $this->input->post('decline_reason'); // HTML input for Declined 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

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

//     // Validate product exists
//     $this->db->where('id', $id)->where('is_active', 1);
//     $product = $this->db->get('products')->row_array();
//     if (empty($product)) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400)
//             ->set_output(json_encode(['success' => false, 'message' => 'PRODUCT_NOT_FOUND_OR_ALREADY_DELETED']));
//     }

//     // Validate prod_type if provided
//     if (isset($prod_type)) {
//         $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)
//                 ->set_output(json_encode(['success' => false, 'message' => 'INVALID_PROD_TYPE']));
//         }
//     } else {
//         $prod_type = $product['prod_type'];
//         $this->db->where('id', $prod_type);
//         $product_type = $this->db->get('product_types')->row_array();
//     }

//     $type = isset($prod_type) && $product_type['category'] === 'folder' ? 'folder' : ($product['type'] ?? '');

//     // Parse in_charge_ids
//     $in_charge_ids_array = [];
//     if (!empty($in_charge_ids)) {
//         $parsed_ids = json_decode($in_charge_ids, true);
//         if (is_array($parsed_ids)) {
//             $in_charge_ids_array = array_filter(array_map('intval', $parsed_ids));
//         } else {
//             $ids = explode(',', str_replace(['[', ']', '"'], '', $in_charge_ids));
//             $in_charge_ids_array = array_filter(array_map('trim', $ids), 'strlen');
//             $in_charge_ids_array = array_map('intval', $in_charge_ids_array);
//         }
//     }

//     // Prepare data for update
//     $data = [];
//     if (isset($activity_id)) $data['activity_id'] = $activity_id;
//     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($group)) {
//         if (!in_array($group, ['general', 'output'])) {
//             return $this->output
//                 ->set_content_type('application/json')
//                 ->set_status_header(400)
//                 ->set_output(json_encode(['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)
//                     ->set_output(json_encode(['success' => false, 'message' => 'OUTPUT_ID_REQUIRED_FOR_OUTPUT_PRODUCT']));
//             }
//             $this->db->where('id', $output_id);
//             $output_exists = $this->db->get('outputs')->num_rows() > 0;
//             if (!$output_exists) {
//                 return $this->output
//                     ->set_content_type('application/json')
//                     ->set_status_header(400)
//                     ->set_output(json_encode(['success' => false, 'message' => 'INVALID_OUTPUT_ID']));
//             }
//             $data['output_id'] = $output_id;
//         } else {
//             $data['output_id'] = NULL;
//         }
//     }

//     $data['updated_by'] = $user_id;
//     $data['last_updated'] = date('Y-m-d');

//     $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';
//     }

//     // Update valid statuses to include Declined
//     if (isset($data['status']) && !in_array($data['status'], ['Pending', 'Submitted', 'In Review', 'Finalised', 'Declined'])) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400)
//             ->set_output(json_encode(['success' => false, 'message' => 'INVALID_STATUS']));
//     }

//     // Require decline_reason for Declined status
//     if (isset($data['status']) && $data['status'] === 'Declined' && empty($decline_reason)) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(400)
//             ->set_output(json_encode(['success' => false, 'message' => 'DECLINE_REASON_REQUIRED']));
//     }

//     if (isset($data['activity_id'])) {
//         $this->db->where('id', $data['activity_id']);
//         $activity_exists = $this->db->get('activities')->num_rows() > 0;
//         if (!$activity_exists) {
//             return $this->output
//                 ->set_content_type('application/json')
//                 ->set_status_header(400)
//                 ->set_output(json_encode(['success' => false, 'message' => 'INVALID_ACTIVITY_ID']));
//         }
//     }

//     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)
//                 ->set_output(json_encode(['success' => false, 'message' => 'INVALID_USER_IDS_IN_IN_CHARGE']));
//         }
//     }

//     $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)
//             ->set_output(json_encode(['success' => false, 'message' => 'INVALID_USER_ID']));
//     }

//     $this->db->trans_start();

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

//     if ($product_type['category'] === 'folder') {
//         $result = $this->handle_multiple_file_uploads($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(['success' => false, 'message' => $result['message']]));
//         }
//         $files = $result['files'];
//         $data['url'] = '';
//     } else {
//         if (!empty($_FILES['file']['name'])) {
//             $result = $this->handle_single_file_upload('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(['success' => false, 'message' => $result['message']]));
//             }
//             $data['url'] = $result['file_url'];
//             $data['type'] = $result['file_extension'];
//             $files = [];
//         }
//     }

//     $activity_id_to_update = $data['activity_id'] ?? $product['activity_id'];
//     if ($has_file_upload) {
//         $this->db->where('id', $activity_id_to_update);
//         $activity = $this->db->get('activities')->row_array();
//         if ($activity && $activity['status'] !== 'Finalised') {
//             $this->db->where('id', $activity_id_to_update);
//             $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) {
//                 log_message('error', "Failed to update activity status to In Progress for activity_id: $activity_id_to_update");
//             }
//         }
//     }

//     // Determine if notifications/emails should be sent
//     $send_notifications = isset($data['status']) && in_array($data['status'], ['Submitted', 'In Review', 'Finalised', 'Declined']) && $product['status'] !== $data['status'];

//     $this->db->where('id', $id);
//     $update = $this->db->update('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)
//             ->set_output(json_encode(['success' => false, 'message' => 'PRODUCT_NOT_UPDATED - ' . $this->db->error()['message']]));
//     }

//     $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)
//             ->set_output(json_encode(['success' => false, 'message' => 'TRANSACTION_FAILED - ' . $this->db->error()['message']]));
//     }

//     $this->db->where('id', $id);
//     $updated_product = $this->db->get('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']
//                 ];
//             }
//         }
//     }

//     $product_files = [];
//     if ($product_type['category'] === 'folder') {
//         $this->db->where('product_id', $id);
//         $files_data = $this->db->get('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']
//             ];
//         }
//     }

//     // Handle notifications and emails
//     if ($send_notifications) {
//         $this->load->library('phpmailer_lib');
//         $mail = $this->phpmailer_lib->load();

//         // SMTP Configuration
//         $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 activity details for the link
//         $this->db->select('a.name as activity_name, o.quarter_id, q.quarter, q.year_id, y.year, p.code as programme_code');
//         $this->db->from('activities a');
//         $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('a.id', $updated_product['activity_id']);
//         $activity_data = $this->db->get()->row_array();

//         $activity_name = $activity_data['activity_name'] ?? 'Unknown Activity';
//         $programme_code = $activity_data['programme_code'] ?? 'SDLG';
//         $quarter = $activity_data['quarter'] ?? 'Q1';
//         $year = $activity_data['year'] ?? '2025';
//         $app_link = "http://localhost:8080/ug/programmes";     "https://www.smarthub.ovalspace.co/ug/programmes";
//         $activity_link = "$app_link/{$programme_code}/activities/{$quarter}/{$year}/{$updated_product['activity_id']}";

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

//         // Common HTML 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;">'
//             . '© 2025 VNG International | SmartHub<br>'
//             . '<a href="https://smarthub.ovalspace.co" style="color: #00A1E5; text-decoration: underline;">Visit SmartHub</a>'
//             . '</div>';

//         // Team notification
//         if (!empty($in_charge_ids_array)) {
//             $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('kimbowaandrew@gmail.com'); // Debugging email
//                 }

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

//                 switch ($data['status']) {
//                     case 'Submitted':
//                         $notification_title = 'Product Submitted';
//                         $notification_message = "The product \"{$updated_product['name']}\" on activity: {$activity_name} has been submitted by {$reviewer_name} for review.";
//                         $email_subject = '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;'>Product Submitted for Review</h2>"
//                             . "<p style='margin: 0 0 15px;'>Dear Team,</p>"
//                             . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($updated_product['name']) . "</strong>\" on activity: "
//                             . "<a href='$activity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($activity_name) . "</a>, "
//                             . "has been submitted by <strong>" . htmlspecialchars($reviewer_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, \"{$updated_product['name']}\", on activity: {$activity_name} ($activity_link) has been submitted by {$reviewer_name} for review.\n\nRegards,\nSmartHub";
//                         break;

//                     case 'In Review':
//                         $notification_title = 'Product In Review';
//                         $notification_message = "The product \"{$updated_product['name']}\" on activity: {$activity_name} is now in review by {$reviewer_name}.";
//                         $email_subject = '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;'>Product In Review</h2>"
//                             . "<p style='margin: 0 0 15px;'>Dear Team,</p>"
//                             . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($updated_product['name']) . "</strong>\" on activity: "
//                             . "<a href='$activity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($activity_name) . "</a>, "
//                             . "is now in review by <strong>" . htmlspecialchars($reviewer_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, \"{$updated_product['name']}\", on activity: {$activity_name} ($activity_link) is now in review by {$reviewer_name}.\n\nRegards,\nSmartHub";
//                         break;

//                     case 'Finalised':
//                         $notification_title = 'Product Finalised';
//                         $notification_message = "The product \"{$updated_product['name']}\" on activity: {$activity_name} has been finalised by {$reviewer_name}.";
//                         $email_subject = '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;'>Product Finalised</h2>"
//                             . "<p style='margin: 0 0 15px;'>Dear Team,</p>"
//                             . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($updated_product['name']) . "</strong>\" on activity: "
//                             . "<a href='$activity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($activity_name) . "</a>, "
//                             . "has been finalised by <strong>" . htmlspecialchars($reviewer_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, \"{$updated_product['name']}\", on activity: {$activity_name} ($activity_link) has been finalised by {$reviewer_name}.\n\nRegards,\nSmartHub";
//                         break;

//                     case 'Declined':
//                         $notification_title = 'Product Declined';
//                         $notification_message = "The product \"{$updated_product['name']}\" on activity: {$activity_name} has been declined by {$reviewer_name}. Reason: " . strip_tags($decline_reason);
//                         $email_subject = '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;'>Product Declined</h2>"
//                             . "<p style='margin: 0 0 15px;'>Dear Team,</p>"
//                             . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($updated_product['name']) . "</strong>\" on activity: "
//                             . "<a href='$activity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($activity_name) . "</a>, "
//                             . "has been declined by <strong>" . htmlspecialchars($reviewer_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;'>" . strip_tags($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, \"{$updated_product['name']}\", on activity: {$activity_name} ($activity_link) has been declined by {$reviewer_name}.\n\nReason: " . strip_tags($decline_reason) . "\n\nRegards,\nSmartHub";
//                         break;
//                 }

//                 // Store notification for each team member
//                 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' => $activity_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 team: ' . $mail->ErrorInfo);
//                 }
//                 $mail->clearAddresses();
//             }
//         }

//         // Admin notification
//         $admin_emails = ['kimbowaandrew@gmail.com', 'kimbowaandrew@gmail.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);
//         }

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

//         switch ($data['status']) {
//             case 'Submitted':
//                 $notification_title = 'Product Submitted for Review';
//                 $notification_message = "The product \"{$updated_product['name']}\" on activity: {$activity_name} has been submitted by {$reviewer_name} for review.";
//                 $email_subject = '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;'>Product Submitted for Review/Approval</h2>"
//                     . "<p style='margin: 0 0 15px;'>Dear Admins,</p>"
//                     . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($updated_product['name']) . "</strong>\" on activity: "
//                     . "<a href='$activity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($activity_name) . "</a>, "
//                     . "has been submitted by <strong>" . htmlspecialchars($reviewer_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 Admins,\n\nThe product, \"{$updated_product['name']}\", on activity: {$activity_name} ($activity_link) has been submitted by {$reviewer_name} for review.\n\nRegards,\nSmartHub";
//                 break;

//             case 'In Review':
//                 $notification_title = 'Product In Review';
//                 $notification_message = "The product \"{$updated_product['name']}\" on activity: {$activity_name} is now in review by {$reviewer_name}.";
//                 $email_subject = '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;'>Product In Review</h2>"
//                     . "<p style='margin: 0 0 15px;'>Dear Admins,</p>"
//                     . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($updated_product['name']) . "</strong>\" on activity: "
//                     . "<a href='$activity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($activity_name) . "</a>, "
//                     . "is now in review by <strong>" . htmlspecialchars($reviewer_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 Admins,\n\nThe product, \"{$updated_product['name']}\", on activity: {$activity_name} ($activity_link) is now in review by {$reviewer_name}.\n\nRegards,\nSmartHub";
//                 break;

//             case 'Finalised':
//                 $notification_title = 'Product Finalised';
//                 $notification_message = "The product \"{$updated_product['name']}\" on activity: {$activity_name} has been finalised by {$reviewer_name}.";
//                 $email_subject = '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;'>Product Finalised</h2>"
//                     . "<p style='margin: 0 0 15px;'>Dear Admins,</p>"
//                     . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($updated_product['name']) . "</strong>\" on activity: "
//                     . "<a href='$activity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($activity_name) . "</a>, "
//                     . "has been finalised by <strong>" . htmlspecialchars($reviewer_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 Admins,\n\nThe product, \"{$updated_product['name']}\", on activity: {$activity_name} ($activity_link) has been finalised by {$reviewer_name}.\n\nRegards,\nSmartHub";
//                 break;

//             case 'Declined':
//                 $notification_title = 'Product Declined';
//                 $notification_message = "The product \"{$updated_product['name']}\" on activity: {$activity_name} has been declined by {$reviewer_name}. Reason: " . strip_tags($decline_reason);
//                 $email_subject = '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;'>Product Declined</h2>"
//                     . "<p style='margin: 0 0 15px;'>Dear Admins,</p>"
//                     . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($updated_product['name']) . "</strong>\" on activity: "
//                     . "<a href='$activity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($activity_name) . "</a>, "
//                     . "has been declined by <strong>" . htmlspecialchars($reviewer_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;'>" . strip_tags($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 Admins,\n\nThe product, \"{$updated_product['name']}\", on activity: {$activity_name} ($activity_link) has been declined by {$reviewer_name}.\n\nReason: " . strip_tags($decline_reason) . "\n\nRegards,\nSmartHub";
//                 break;
//         }

//         // Store notification for each admin
//         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' => $activity_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);
//         }
//     }

//     $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']
//         ]
//     ];

//     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
    $activity_id = $this->input->post('activity_id');
    $name = $this->input->post('name');
    $prod_type = $this->input->post('prod_type'); // ID from product_types
    $status = $this->input->post('status');
    $decline_reason = $this->input->post('decline_reason'); // HTML input for Declined 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

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

    // Validate product exists
    $this->db->where('id', $id)->where('is_active', 1);
    $product = $this->db->get('products')->row_array();
    if (empty($product)) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400)
            ->set_output(json_encode(['success' => false, 'message' => 'PRODUCT_NOT_FOUND_OR_ALREADY_DELETED']));
    }

    // Validate prod_type if provided
    if (isset($prod_type)) {
        $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)
                ->set_output(json_encode(['success' => false, 'message' => 'INVALID_PROD_TYPE']));
        }
    } else {
        $prod_type = $product['prod_type'];
        $this->db->where('id', $prod_type);
        $product_type = $this->db->get('product_types')->row_array();
    }

    $type = isset($prod_type) && $product_type['category'] === 'folder' ? 'folder' : ($product['type'] ?? '');

    // Parse in_charge_ids
    $in_charge_ids_array = [];
    if (!empty($in_charge_ids)) {
        $parsed_ids = json_decode($in_charge_ids, true);
        if (is_array($parsed_ids)) {
            $in_charge_ids_array = array_filter(array_map('intval', $parsed_ids));
        } else {
            $ids = explode(',', str_replace(['[', ']', '"'], '', $in_charge_ids));
            $in_charge_ids_array = array_filter(array_map('trim', $ids), 'strlen');
            $in_charge_ids_array = array_map('intval', $in_charge_ids_array);
        }
    }

    // Prepare data for update
    $data = [];
    if (isset($activity_id)) $data['activity_id'] = $activity_id;
    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($group)) {
        if (!in_array($group, ['general', 'output'])) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(400)
                ->set_output(json_encode(['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)
                    ->set_output(json_encode(['success' => false, 'message' => 'OUTPUT_ID_REQUIRED_FOR_OUTPUT_PRODUCT']));
            }
            $this->db->where('id', $output_id);
            $output_exists = $this->db->get('outputs')->num_rows() > 0;
            if (!$output_exists) {
                return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(400)
                    ->set_output(json_encode(['success' => false, 'message' => 'INVALID_OUTPUT_ID']));
            }
            $data['output_id'] = $output_id;
        } else {
            $data['output_id'] = NULL;
        }
    }

    $data['updated_by'] = $user_id;
    $data['last_updated'] = date('Y-m-d');

    $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';
    }

    // Update valid statuses to include Declined
    if (isset($data['status']) && !in_array($data['status'], ['Pending', 'Submitted', 'In Review', 'Finalised', 'Declined'])) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400)
            ->set_output(json_encode(['success' => false, 'message' => 'INVALID_STATUS']));
    }

    // Require decline_reason for Declined status
    if (isset($data['status']) && $data['status'] === 'Declined' && empty($decline_reason)) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400)
            ->set_output(json_encode(['success' => false, 'message' => 'DECLINE_REASON_REQUIRED']));
    }

    if (isset($data['activity_id'])) {
        $this->db->where('id', $data['activity_id']);
        $activity_exists = $this->db->get('activities')->num_rows() > 0;
        if (!$activity_exists) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(400)
                ->set_output(json_encode(['success' => false, 'message' => 'INVALID_ACTIVITY_ID']));
        }
    }

    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)
                ->set_output(json_encode(['success' => false, 'message' => 'INVALID_USER_IDS_IN_IN_CHARGE']));
        }
    }

    $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)
            ->set_output(json_encode(['success' => false, 'message' => 'INVALID_USER_ID']));
    }

    $this->db->trans_start();

    $files = [];
    $directory = "products";
    if (!file_exists($directory)) {
        mkdir($directory, 0777, true);
    }

    if ($product_type['category'] === 'folder') {
        $result = $this->handle_multiple_file_uploads($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(['success' => false, 'message' => $result['message']]));
        }
        $files = $result['files'];
        $data['url'] = '';
    } else {
        if (!empty($_FILES['file']['name'])) {
            $result = $this->handle_single_file_upload('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(['success' => false, 'message' => $result['message']]));
            }
            $data['url'] = $result['file_url'];
            $data['type'] = $result['file_extension'];
            $files = [];
        }
    }

    $activity_id_to_update = $data['activity_id'] ?? $product['activity_id'];
    if ($has_file_upload) {
        $this->db->where('id', $activity_id_to_update);
        $activity = $this->db->get('activities')->row_array();
        if ($activity && $activity['status'] !== 'Finalised') {
            $this->db->where('id', $activity_id_to_update);
            $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) {
                log_message('error', "Failed to update activity status to In Progress for activity_id: $activity_id_to_update");
            }
        }
    }

    // Determine if notifications/emails should be sent
    $send_notifications = isset($data['status']) && in_array($data['status'], ['Submitted', 'In Review', 'Finalised', 'Declined']) && $product['status'] !== $data['status'];

    $this->db->where('id', $id);
    $update = $this->db->update('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)
            ->set_output(json_encode(['success' => false, 'message' => 'PRODUCT_NOT_UPDATED - ' . $this->db->error()['message']]));
    }

    $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)
            ->set_output(json_encode(['success' => false, 'message' => 'TRANSACTION_FAILED - ' . $this->db->error()['message']]));
    }

    $this->db->where('id', $id);
    $updated_product = $this->db->get('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']
                ];
            }
        }
    }

    $product_files = [];
    if ($product_type['category'] === 'folder') {
        $this->db->where('product_id', $id);
        $files_data = $this->db->get('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']
            ];
        }
    }

    // Handle notifications and emails
    if ($send_notifications) {
        $this->load->library('phpmailer_lib');
        $mail = $this->phpmailer_lib->load();

        // SMTP Configuration
        $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 activity details for the link
        $this->db->select('a.name as activity_name, o.quarter_id, q.quarter, q.year_id, y.year, p.code as programme_code');
        $this->db->from('activities a');
        $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('a.id', $updated_product['activity_id']);
        $activity_data = $this->db->get()->row_array();

        $activity_name = $activity_data['activity_name'] ?? 'Unknown Activity';
        $programme_code = $activity_data['programme_code'] ?? 'SDLG';
        $quarter = $activity_data['quarter'] ?? 'Q1';
        $year = $activity_data['year'] ?? '2025';
        // $app_link = "http://localhost:8080/ug/programmes";
        $app_link = "https://www.smarthub.ovalspace.co/ug/programmes";
        $activity_link = "$app_link/{$programme_code}/activities/{$quarter}/{$year}/{$updated_product['activity_id']}";

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

        // Common HTML 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>';

        // Team notification
        if (!empty($in_charge_ids_array)) {
            $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');
            
              $mail->addAddress('paul.bate@vngi.org');          // Additional recipient 1
        $mail->addAddress('nakitende.millen@vngi.org');

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

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

                switch ($data['status']) {
                    case 'Submitted':
                        $notification_title = 'Product Submitted';
                        $notification_message = "The product \"{$updated_product['name']}\" on activity: {$activity_name} has been submitted by {$reviewer_name} for review.";
                        $email_subject = '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;'>Product Submitted for Review</h2>"
                            . "<p style='margin: 0 0 15px;'>Dear Team,</p>"
                            . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($updated_product['name']) . "</strong>\" on activity: "
                            . "<a href='$activity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($activity_name) . "</a>, "
                            . "has been submitted by <strong>" . htmlspecialchars($reviewer_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, \"{$updated_product['name']}\", on activity: {$activity_name} ($activity_link) has been submitted by {$reviewer_name} for review.\n\nRegards,\nSmartHub";
                        break;

                    case 'In Review':
                        $notification_title = 'Product In Review';
                        $notification_message = "The product \"{$updated_product['name']}\" on activity: {$activity_name} is now in review by {$reviewer_name}.";
                        $email_subject = '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;'>Product In Review</h2>"
                            . "<p style='margin: 0 0 15px;'>Dear Team,</p>"
                            . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($updated_product['name']) . "</strong>\" on activity: "
                            . "<a href='$activity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($activity_name) . "</a>, "
                            . "is now in review by <strong>" . htmlspecialchars($reviewer_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, \"{$updated_product['name']}\", on activity: {$activity_name} ($activity_link) is now in review by {$reviewer_name}.\n\nRegards,\nSmartHub";
                        break;

                    case 'Finalised':
                        $notification_title = 'Product Finalised';
                        $notification_message = "The product \"{$updated_product['name']}\" on activity: {$activity_name} has been finalised by {$reviewer_name}.";
                        $email_subject = '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;'>Product Finalised</h2>"
                            . "<p style='margin: 0 0 15px;'>Dear Team,</p>"
                            . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($updated_product['name']) . "</strong>\" on activity: "
                            . "<a href='$activity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($activity_name) . "</a>, "
                            . "has been finalised by <strong>" . htmlspecialchars($reviewer_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, \"{$updated_product['name']}\", on activity: {$activity_name} ($activity_link) has been finalised by {$reviewer_name}.\n\nRegards,\nSmartHub";
                        break;

                    case 'Declined':
                        $notification_title = 'Product Declined';
                        $notification_message = "The product \"{$updated_product['name']}\" on activity: {$activity_name} has been declined by {$reviewer_name}. Reason: " . strip_tags($decline_reason);
                        $email_subject = '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;'>Product Declined</h2>"
                            . "<p style='margin: 0 0 15px;'>Dear Team,</p>"
                            . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($updated_product['name']) . "</strong>\" on activity: "
                            . "<a href='$activity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($activity_name) . "</a>, "
                            . "has been declined by <strong>" . htmlspecialchars($reviewer_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>"
                            . "<div style='color: #333; line-height: 1.6; margin: 10px 0 0;'>" . $decline_reason . "</div>"
                            . "</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, \"{$updated_product['name']}\", on activity: {$activity_name} ($activity_link) has been declined by {$reviewer_name}.\n\nReason: " . strip_tags($decline_reason) . "\n\nRegards,\nSmartHub";
                        break;
                }

                // Store notification for each team member
                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' => $activity_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 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 = 'PRODUCT_STATUS_UPDATE';
        $notification_title = '';
        $notification_message = '';
        $email_subject = '';
        $email_body = '';
        $email_alt_body = '';

        switch ($data['status']) {
            case 'Submitted':
                $notification_title = 'Product Submitted for Review';
                $notification_message = "The product \"{$updated_product['name']}\" on activity: {$activity_name} has been submitted by {$reviewer_name} for review.";
                $email_subject = '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;'>Product Submitted for Review/Approval</h2>"
                    . "<p style='margin: 0 0 15px;'>Dear Admins,</p>"
                    . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($updated_product['name']) . "</strong>\" on activity: "
                    . "<a href='$activity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($activity_name) . "</a>, "
                    . "has been submitted by <strong>" . htmlspecialchars($reviewer_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 Admins,\n\nThe product, \"{$updated_product['name']}\", on activity: {$activity_name} ($activity_link) has been submitted by {$reviewer_name} for review.\n\nRegards,\nSmartHub";
                break;

            case 'In Review':
                $notification_title = 'Product In Review';
                $notification_message = "The product \"{$updated_product['name']}\" on activity: {$activity_name} is now in review by {$reviewer_name}.";
                $email_subject = '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;'>Product In Review</h2>"
                    . "<p style='margin: 0 0 15px;'>Dear Admins,</p>"
                    . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($updated_product['name']) . "</strong>\" on activity: "
                    . "<a href='$activity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($activity_name) . "</a>, "
                    . "is now in review by <strong>" . htmlspecialchars($reviewer_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 Admins,\n\nThe product, \"{$updated_product['name']}\", on activity: {$activity_name} ($activity_link) is now in review by {$reviewer_name}.\n\nRegards,\nSmartHub";
                break;

            case 'Finalised':
                $notification_title = 'Product Finalised';
                $notification_message = "The product \"{$updated_product['name']}\" on activity: {$activity_name} has been finalised by {$reviewer_name}.";
                $email_subject = '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;'>Product Finalised</h2>"
                    . "<p style='margin: 0 0 15px;'>Dear Admins,</p>"
                    . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($updated_product['name']) . "</strong>\" on activity: "
                    . "<a href='$activity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($activity_name) . "</a>, "
                    . "has been finalised by <strong>" . htmlspecialchars($reviewer_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 Admins,\n\nThe product, \"{$updated_product['name']}\", on activity: {$activity_name} ($activity_link) has been finalised by {$reviewer_name}.\n\nRegards,\nSmartHub";
                break;

            case 'Declined':
                $notification_title = 'Product Declined';
                $notification_message = "The product \"{$updated_product['name']}\" on activity: {$activity_name} has been declined by {$reviewer_name}. Reason: " . strip_tags($decline_reason);
                $email_subject = '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;'>Product Declined</h2>"
                    . "<p style='margin: 0 0 15px;'>Dear Admins,</p>"
                    . "<p style='margin: 0 0 15px;'>The product, \"<strong>" . htmlspecialchars($updated_product['name']) . "</strong>\" on activity: "
                    . "<a href='$activity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($activity_name) . "</a>, "
                    . "has been declined by <strong>" . htmlspecialchars($reviewer_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>"
                    . "<div style='color: #333; line-height: 1.6; margin: 10px 0 0;'>" . $decline_reason . "</div>"
                    . "</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 Admins,\n\nThe product, \"{$updated_product['name']}\", on activity: {$activity_name} ($activity_link) has been declined by {$reviewer_name}.\n\nReason: " . strip_tags($decline_reason) . "\n\nRegards,\nSmartHub";
                break;
        }

        // Store notification for each admin
        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' => $activity_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);
        }
    }

    $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']
        ]
    ];

    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 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('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('products', $data);

        // Soft delete related product_files
        $this->handle_soft_delete_product_files($product_id, $user_id);
    } else {
        // Perform hard delete: delete product and related product_files
        $this->handle_hard_delete_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_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('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_product($product_id)
{
    // Delete related product_files
    $this->db->where('product_id', $product_id);
    $this->db->delete('product_files');

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




public function restore_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'
            )));
    }

    // Check if product exists and is soft-deleted
    $this->db->where('id', $product_id);
    $this->db->where('is_active', 0); // Ensure the product is soft-deleted
    $product = $this->db->get('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_NOT_SOFT_DELETED'
            )));
    }

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

    // Perform restore: update is_active to 1, clear deleted_at, and update audit fields
    $data = [
        'is_active' => 1,
        'deleted_at' => NULL, // Clear the soft delete 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('products', $data);

    // Restore related product_files (if they exist and are soft-deleted)
    $this->restore_related_product_files($product_id, $user_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' => 'RESTORE_FAILED'
            )));
    }

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

// Helper function to restore related product_files
private function restore_related_product_files($product_id, $user_id)
{
    $data = [
        'is_active' => 1,
        'deleted_at' => NULL, // Clear the soft delete timestamp
        'updated_by' => $user_id,
        'updated_at' => date('Y-m-d H:i:s') // Current timestamp
    ];

    $this->db->where('product_id', $product_id);
    $this->db->where('is_active', 0); // Only restore soft-deleted files
    $this->db->update('product_files', $data);
}


// Helper function to get descriptive upload error messages
private function get_upload_error_message($error_code)
{
    $errors = [
        UPLOAD_ERR_OK => 'No error',
        UPLOAD_ERR_INI_SIZE => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
        UPLOAD_ERR_FORM_SIZE => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
        UPLOAD_ERR_PARTIAL => 'The uploaded file was only partially uploaded',
        UPLOAD_ERR_NO_FILE => 'No file was uploaded',
        UPLOAD_ERR_NO_TMP_DIR => 'Missing a temporary folder',
        UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk',
        UPLOAD_ERR_EXTENSION => 'A PHP extension stopped the file upload'
    ];
    return isset($errors[$error_code]) ? $errors[$error_code] : 'Unknown error';
}

//ATTACHEMENTS : 

public function add_attachment()
{
    // Get form data (multipart/form-data expected for file uploads)
    $user_id = $this->input->post('user_id');
    $activity_id = $this->input->post('activity_id');
    $sub_activity_id = $this->input->post('sub_activity_id');
    $follow_up_activity_id = $this->input->post('follow_up_activity_id');
    $title = $this->input->post('title');
    $date = date('Y-m-d');
    $in_charge_ids = $this->input->post('in_charge_ids'); // JSON array or comma-separated string

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

    // Check that exactly one of activity_id, sub_activity_id, or follow_up_activity_id is provided
    $ids_provided = array_filter([$activity_id, $sub_activity_id, $follow_up_activity_id], function ($id) {
        return !empty($id);
    });
    if (count($ids_provided) === 0) {
        return $this->output->set_content_type('application/json')->set_status_header(400)
            ->set_output(json_encode(['success' => false, 'message' => 'NO_ENTITY_ID_PROVIDED']));
    }
    if (count($ids_provided) > 1) {
        return $this->output->set_content_type('application/json')->set_status_header(400)
            ->set_output(json_encode(['success' => false, 'message' => 'MULTIPLE_ENTITY_IDS_PROVIDED']));
    }

    // Check if files are uploaded
    $has_file_upload = !empty($_FILES['file']['name']) || (!empty($_FILES['files']) && is_array($_FILES['files']['name']) && !empty($_FILES['files']['name'][0]));
    if (!$has_file_upload) {
        return $this->output->set_content_type('application/json')->set_status_header(400)
            ->set_output(json_encode(['success' => false, 'message' => 'NO_FILES_UPLOADED']));
    }

    // Validate user
    $this->db->where('id', $user_id)->where('is_active', 1);
    if ($this->db->get('users')->num_rows() == 0) {
        return $this->output->set_content_type('application/json')->set_status_header(400)
            ->set_output(json_encode(['success' => false, 'message' => 'INVALID_USER_ID']));
    }

    // Validate the provided entity exists
    if ($activity_id) {
        $this->db->where('id', $activity_id)->where('is_active', 1);
        if ($this->db->get('activities')->num_rows() == 0) {
            return $this->output->set_content_type('application/json')->set_status_header(400)
                ->set_output(json_encode(['success' => false, 'message' => 'ACTIVITY_NOT_FOUND']));
        }
    } elseif ($sub_activity_id) {
        $this->db->where('id', $sub_activity_id)->where('is_active', 1);
        if ($this->db->get('sub_activities')->num_rows() == 0) {
            return $this->output->set_content_type('application/json')->set_status_header(400)
                ->set_output(json_encode(['success' => false, 'message' => 'SUB_ACTIVITY_NOT_FOUND']));
        }
    } elseif ($follow_up_activity_id) {
        $this->db->where('id', $follow_up_activity_id)->where('is_active', 1);
        if ($this->db->get('follow_up_activities')->num_rows() == 0) {
            return $this->output->set_content_type('application/json')->set_status_header(400)
                ->set_output(json_encode(['success' => false, 'message' => 'FOLLOW_UP_ACTIVITY_NOT_FOUND']));
        }
    }

    // Parse and validate in_charge_ids
    $in_charge_array = [];
    if ($in_charge_ids !== null) {
        $parsed_ids = json_decode($in_charge_ids, true);
        if (is_array($parsed_ids)) {
            $in_charge_array = array_filter(array_map('intval', $parsed_ids));
        } else {
            $ids = explode(',', str_replace(['[', ']', '"'], '', $in_charge_ids));
            $in_charge_array = array_filter(array_map('trim', $ids), 'strlen');
            $in_charge_array = array_map('intval', $in_charge_array);
        }

        if (!empty($in_charge_array)) {
            $this->db->where_in('id', $in_charge_array)->where('is_active', 1);
            $users_exist = $this->db->get('users')->num_rows() === count($in_charge_array);
            if (!$users_exist) {
                return $this->output->set_content_type('application/json')->set_status_header(400)
                    ->set_output(json_encode(['success' => false, 'message' => 'INVALID_IN_CHARGE_IDS']));
            }
        }
    }

    // Determine type based on upload: single file or folder
    $type = !empty($_FILES['file']['name']) ? 'file' : 'folder'; // Single file uses 'file', multiple uses 'files'
    $directory = 'attachments';
    if (!file_exists($directory)) {
        mkdir($directory, 0777, true);
    }

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

    // Insert attachment
    $attachment_data = [
        'activity_id' => $activity_id ?: null,
        'sub_activity_id' => $sub_activity_id ?: null,
        'follow_up_activity_id' => $follow_up_activity_id ?: null,
        'type' => $type,
        'title' => $title,
        'date' => $date ?: date('Y-m-d'),
        'in_charge_ids' => !empty($in_charge_array) ? json_encode($in_charge_array) : json_encode([]),
        'created_by' => $user_id,
        'updated_by' => $user_id
    ];

    // Handle file uploads
    if ($type === 'file') {
        $result = $this->handle_single_file_upload('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(['success' => false, 'message' => $result['message']]));
        }
        $attachment_data['url'] = $result['file_url'];
        $attachment_data['size'] =$result['file_size'];
        $attachment_data['type'] = $result['file_extension']; // Use extension as type
    }

    $this->db->insert('attachments', $attachment_data);
    $attachment_id = $this->db->insert_id();

    // Handle multiple files for folders
    if ($type === 'folder') {
        $result = $this->handle_multiple_file_uploads_attachments($attachment_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(['success' => false, 'message' => $result['message']]));
        }
    }

    // Commit transaction
    $this->db->trans_complete();
    if ($this->db->trans_status() === FALSE) {
        return $this->output->set_content_type('application/json')->set_status_header(400)
            ->set_output(json_encode(['success' => false, 'message' => 'TRANSACTION_FAILED']));
    }

    // Fetch response data
    $response_data = $this->get_attachment_data($attachment_id);
    return $this->output->set_content_type('application/json')->set_status_header(201)
        ->set_output(json_encode(['success' => true, 'message' => 'ATTACHMENT_ADDED', 'data' => $response_data]));
}

// public function update_attachment($id)
// {
//     // Get form data (multipart/form-data expected for file uploads)
//     $user_id = $this->input->post('user_id');
//     $activity_id = $this->input->post('activity_id');
//     $sub_activity_id = $this->input->post('sub_activity_id');
//     $follow_up_activity_id = $this->input->post('follow_up_activity_id');
//     $title = $this->input->post('title');
//     $date = $this->input->post('date');
//     $in_charge_ids = $this->input->post('in_charge_ids'); // JSON array or comma-separated string

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

//     // Validate attachment exists and is active
//     $this->db->where('id', $id)->where('is_active', 1);
//     $attachment = $this->db->get('attachments')->row_array();
//     if (!$attachment) {
//         return $this->output->set_content_type('application/json')->set_status_header(400)
//             ->set_output(json_encode(['success' => false, 'message' => 'ATTACHMENT_NOT_FOUND']));
//     }

//     // Validate user
//     $this->db->where('id', $user_id)->where('is_active', 1);
//     if ($this->db->get('users')->num_rows() == 0) {
//         return $this->output->set_content_type('application/json')->set_status_header(400)
//             ->set_output(json_encode(['success' => false, 'message' => 'INVALID_USER_ID']));
//     }

//     // Check entity IDs: if provided, ensure exactly one and validate it
//     $ids_provided = array_filter([$activity_id, $sub_activity_id, $follow_up_activity_id], function ($id) {
//         return !empty($id);
//     });
//     if (count($ids_provided) > 1) {
//         return $this->output->set_content_type('application/json')->set_status_header(400)
//             ->set_output(json_encode(['success' => false, 'message' => 'MULTIPLE_ENTITY_IDS_PROVIDED']));
//     }

//     // Validate the provided entity exists if changed
//     if ($activity_id && $activity_id != $attachment['activity_id']) {
//         $this->db->where('id', $activity_id)->where('is_active', 1);
//         if ($this->db->get('activities')->num_rows() == 0) {
//             return $this->output->set_content_type('application/json')->set_status_header(400)
//                 ->set_output(json_encode(['success' => false, 'message' => 'ACTIVITY_NOT_FOUND']));
//         }
//     } elseif ($sub_activity_id && $sub_activity_id != $attachment['sub_activity_id']) {
//         $this->db->where('id', $sub_activity_id)->where('is_active', 1);
//         if ($this->db->get('sub_activities')->num_rows() == 0) {
//             return $this->output->set_content_type('application/json')->set_status_header(400)
//                 ->set_output(json_encode(['success' => false, 'message' => 'SUB_ACTIVITY_NOT_FOUND']));
//         }
//     } elseif ($follow_up_activity_id && $follow_up_activity_id != $attachment['follow_up_activity_id']) {
//         $this->db->where('id', $follow_up_activity_id)->where('is_active', 1);
//         if ($this->db->get('follow_up_activities')->num_rows() == 0) {
//             return $this->output->set_content_type('application/json')->set_status_header(400)
//                 ->set_output(json_encode(['success' => false, 'message' => 'FOLLOW_UP_ACTIVITY_NOT_FOUND']));
//         }
//     }

//     // Parse and validate in_charge_ids if provided
//     $in_charge_array = [];
//     if ($in_charge_ids !== null) {
//         $parsed_ids = json_decode($in_charge_ids, true);
//         if (is_array($parsed_ids)) {
//             $in_charge_array = array_filter(array_map('intval', $parsed_ids));
//         } else {
//             $ids = explode(',', str_replace(['[', ']', '"'], '', $in_charge_ids));
//             $in_charge_array = array_filter(array_map('trim', $ids), 'strlen');
//             $in_charge_array = array_map('intval', $in_charge_array);
//         }

//         if (!empty($in_charge_array)) {
//             $this->db->where_in('id', $in_charge_array)->where('is_active', 1);
//             $users_exist = $this->db->get('users')->num_rows() === count($in_charge_array);
//             if (!$users_exist) {
//                 return $this->output->set_content_type('application/json')->set_status_header(400)
//                     ->set_output(json_encode(['success' => false, 'message' => 'INVALID_IN_CHARGE_IDS']));
//             }
//         }
//     }

//     // Prepare update data
//     $update_data = [
//         'updated_by' => $user_id
//     ];
//     if ($activity_id) $update_data['activity_id'] = $activity_id;
//     if ($sub_activity_id) $update_data['sub_activity_id'] = $sub_activity_id;
//     if ($follow_up_activity_id) $update_data['follow_up_activity_id'] = $follow_up_activity_id;
//     if ($title) $update_data['title'] = $title;
//     if ($date) $update_data['date'] = $date;
//     if (!empty($in_charge_array)) $update_data['in_charge_ids'] = json_encode($in_charge_array);

//     // Check for file uploads
//     $has_single_file = !empty($_FILES['file']['name']);
//     $has_multiple_files = !empty($_FILES['files']) && is_array($_FILES['files']['name']) && !empty($_FILES['files']['name'][0]);
//     if ($has_single_file && $has_multiple_files) {
//         return $this->output->set_content_type('application/json')->set_status_header(400)
//             ->set_output(json_encode(['success' => false, 'message' => 'AMBIGUOUS_FILE_INPUT']));
//     }

//     $directory = 'attachments';
//     if (!file_exists($directory)) {
//         mkdir($directory, 0777, true);
//     }

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

//     // Handle file replacement or addition
//     if ($has_single_file && $attachment['type'] !== 'folder') {
//         $result = $this->handle_single_file_upload('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(['success' => false, 'message' => $result['message']]));
//         }
//         $update_data['url'] = $result['file_url'];
//         $update_data['size'] = $result['file_size'];
//         $update_data['type'] = $result['file_extension'];
//     } elseif ($has_multiple_files && $attachment['type'] === 'folder') {
//         $result = $this->handle_multiple_file_uploads_attachments($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(['success' => false, 'message' => $result['message']]));
//         }
//     } elseif (($has_single_file && $attachment['type'] === 'folder') || ($has_multiple_files && $attachment['type'] !== 'folder')) {
//         return $this->output->set_content_type('application/json')->set_status_header(400)
//             ->set_output(json_encode(['success' => false, 'message' => 'FILE_TYPE_MISMATCH']));
//     }

//     // Update attachment
//     $this->db->where('id', $id);
//     $this->db->update('attachments', $update_data);

//     // Commit transaction
//     $this->db->trans_complete();
//     if ($this->db->trans_status() === FALSE) {
//         return $this->output->set_content_type('application/json')->set_status_header(400)
//             ->set_output(json_encode(['success' => false, 'message' => 'TRANSACTION_FAILED']));
//     }

//     // Fetch updated data
//     $response_data = $this->get_attachment_data($id);
//     return $this->output->set_content_type('application/json')->set_status_header(200)
//         ->set_output(json_encode(['success' => true, 'message' => 'ATTACHMENT_UPDATED', 'data' => $response_data]));
// }


public function update_attachment($id)
{
    // Get form data (multipart/form-data expected for file uploads)
    $user_id = $this->input->post('user_id');
    $activity_id = $this->input->post('activity_id');
    $sub_activity_id = $this->input->post('sub_activity_id');
    $follow_up_activity_id = $this->input->post('follow_up_activity_id');
    $title = $this->input->post('title');
    $date = $this->input->post('date');
    $in_charge_ids = $this->input->post('in_charge_ids'); // JSON array or comma-separated string
    $files_to_be_removed = $this->input->post('files_to_be_removed'); // Array of attachment_files IDs, e.g., "[2,5,1,7]"

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

    // Validate attachment exists and is active
    $this->db->where('id', $id)->where('is_active', 1);
    $attachment = $this->db->get('attachments')->row_array();
    if (!$attachment) {
        return $this->output->set_content_type('application/json')->set_status_header(400)
            ->set_output(json_encode(['success' => false, 'message' => 'ATTACHMENT_NOT_FOUND']));
    }

    // Validate user
    $this->db->where('id', $user_id)->where('is_active', 1);
    if ($this->db->get('users')->num_rows() == 0) {
        return $this->output->set_content_type('application/json')->set_status_header(400)
            ->set_output(json_encode(['success' => false, 'message' => 'INVALID_USER_ID']));
    }

    // Check entity IDs: if provided, ensure exactly one and validate it
    $ids_provided = array_filter([$activity_id, $sub_activity_id, $follow_up_activity_id], function ($id) {
        return !empty($id);
    });
    if (count($ids_provided) > 1) {
        return $this->output->set_content_type('application/json')->set_status_header(400)
            ->set_output(json_encode(['success' => false, 'message' => 'MULTIPLE_ENTITY_IDS_PROVIDED']));
    }

    // Validate the provided entity exists if changed
    if ($activity_id && $activity_id != $attachment['activity_id']) {
        $this->db->where('id', $activity_id)->where('is_active', 1);
        if ($this->db->get('activities')->num_rows() == 0) {
            return $this->output->set_content_type('application/json')->set_status_header(400)
                ->set_output(json_encode(['success' => false, 'message' => 'ACTIVITY_NOT_FOUND']));
        }
    } elseif ($sub_activity_id && $sub_activity_id != $attachment['sub_activity_id']) {
        $this->db->where('id', $sub_activity_id)->where('is_active', 1);
        if ($this->db->get('sub_activities')->num_rows() == 0) {
            return $this->output->set_content_type('application/json')->set_status_header(400)
                ->set_output(json_encode(['success' => false, 'message' => 'SUB_ACTIVITY_NOT_FOUND']));
        }
    } elseif ($follow_up_activity_id && $follow_up_activity_id != $attachment['follow_up_activity_id']) {
        $this->db->where('id', $follow_up_activity_id)->where('is_active', 1);
        if ($this->db->get('follow_up_activities')->num_rows() == 0) {
            return $this->output->set_content_type('application/json')->set_status_header(400)
                ->set_output(json_encode(['success' => false, 'message' => 'FOLLOW_UP_ACTIVITY_NOT_FOUND']));
        }
    }

    // Parse and validate in_charge_ids if provided
    $in_charge_array = [];
    if ($in_charge_ids !== null) {
        $parsed_ids = json_decode($in_charge_ids, true);
        if (is_array($parsed_ids)) {
            $in_charge_array = array_filter(array_map('intval', $parsed_ids));
        } else {
            $ids = explode(',', str_replace(['[', ']', '"'], '', $in_charge_ids));
            $in_charge_array = array_filter(array_map('trim', $ids), 'strlen');
            $in_charge_array = array_map('intval', $in_charge_array);
        }

        if (!empty($in_charge_array)) {
            $this->db->where_in('id', $in_charge_array)->where('is_active', 1);
            $users_exist = $this->db->get('users')->num_rows() === count($in_charge_array);
            if (!$users_exist) {
                return $this->output->set_content_type('application/json')->set_status_header(400)
                    ->set_output(json_encode(['success' => false, 'message' => 'INVALID_IN_CHARGE_IDS']));
            }
        }
    }

    // Parse files_to_be_removed if provided (for folder attachments)
    $files_to_remove_array = [];
    if ($files_to_be_removed !== null && $attachment['type'] === 'folder') {
        $parsed_files = json_decode($files_to_be_removed, true);
        if (is_array($parsed_files)) {
            $files_to_remove_array = array_filter(array_map('intval', $parsed_files));
        } else {
            $ids = explode(',', str_replace(['[', ']', '"'], '', $files_to_be_removed));
            $files_to_remove_array = array_filter(array_map('trim', $ids), 'strlen');
            $files_to_remove_array = array_map('intval', $files_to_remove_array);
        }

        if (!empty($files_to_remove_array)) {
            // Validate that all provided file IDs belong to this attachment and are active
            $this->db->where('attachment_id', $id)->where_in('id', $files_to_remove_array)->where('is_active', 1);
            $valid_files_count = $this->db->get('attachment_files')->num_rows();
            if ($valid_files_count !== count($files_to_remove_array)) {
                return $this->output->set_content_type('application/json')->set_status_header(400)
                    ->set_output(json_encode(['success' => false, 'message' => 'INVALID_FILES_TO_REMOVE']));
            }
        }
    } elseif ($files_to_be_removed !== null && $attachment['type'] !== 'folder') {
        return $this->output->set_content_type('application/json')->set_status_header(400)
            ->set_output(json_encode(['success' => false, 'message' => 'FILES_TO_REMOVE_NOT_APPLICABLE_FOR_SINGLE_FILE']));
    }

    // Prepare update data
    $update_data = [
        'updated_by' => $user_id
    ];
    if ($activity_id) $update_data['activity_id'] = $activity_id;
    if ($sub_activity_id) $update_data['sub_activity_id'] = $sub_activity_id;
    if ($follow_up_activity_id) $update_data['follow_up_activity_id'] = $follow_up_activity_id;
    if ($title) $update_data['title'] = $title;
    if ($date) $update_data['date'] = $date;
    if (!empty($in_charge_array)) $update_data['in_charge_ids'] = json_encode($in_charge_array);

    // Check for file uploads
    $has_single_file = !empty($_FILES['file']['name']);
    $has_multiple_files = !empty($_FILES['files']) && is_array($_FILES['files']['name']) && !empty($_FILES['files']['name'][0]);
    if ($has_single_file && $has_multiple_files) {
        return $this->output->set_content_type('application/json')->set_status_header(400)
            ->set_output(json_encode(['success' => false, 'message' => 'AMBIGUOUS_FILE_INPUT']));
    }

    $directory = 'attachments';
    if (!file_exists($directory)) {
        mkdir($directory, 0777, true);
    }

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

    // Handle file replacement or addition
    if ($has_single_file && $attachment['type'] !== 'folder') {
        $result = $this->handle_single_file_upload('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(['success' => false, 'message' => $result['message']]));
        }
        $update_data['url'] = $result['file_url'];
        $update_data['size'] = $result['file_size'];
        $update_data['type'] = $result['file_extension'];
    } elseif ($has_multiple_files && $attachment['type'] === 'folder') {
        $result = $this->handle_multiple_file_uploads_attachments($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(['success' => false, 'message' => $result['message']]));
        }
    } elseif (($has_single_file && $attachment['type'] === 'folder') || ($has_multiple_files && $attachment['type'] !== 'folder')) {
        return $this->output->set_content_type('application/json')->set_status_header(400)
            ->set_output(json_encode(['success' => false, 'message' => 'FILE_TYPE_MISMATCH']));
    }

    // Handle file deletion for folder attachments
    if (!empty($files_to_remove_array) && $attachment['type'] === 'folder') {
        // Fetch URLs of files to delete for potential filesystem cleanup
        $this->db->select('url');
        $this->db->where('attachment_id', $id)->where_in('id', $files_to_remove_array);
        $files_to_delete = $this->db->get('attachment_files')->result_array();
        $file_urls = array_column($files_to_delete, 'url');

        // Delete the specified files from attachment_files (permanent delete)
        $this->db->where('attachment_id', $id)->where_in('id', $files_to_remove_array);
        $this->db->delete('attachment_files');

        // Optionally delete files from the filesystem
        foreach ($file_urls as $file_url) {
            $file_path = FCPATH . str_replace(base_url(), '', $file_url); // Convert URL to server path
            if (file_exists($file_path)) {
                unlink($file_path); // Remove file from server
            }
        }
    }

    // Update attachment
    $this->db->where('id', $id);
    $this->db->update('attachments', $update_data);

    // Commit transaction
    $this->db->trans_complete();
    if ($this->db->trans_status() === FALSE) {
        return $this->output->set_content_type('application/json')->set_status_header(400)
            ->set_output(json_encode(['success' => false, 'message' => 'TRANSACTION_FAILED']));
    }

    // Fetch updated data
    $response_data = $this->get_attachment_data($id);
    return $this->output->set_content_type('application/json')->set_status_header(200)
        ->set_output(json_encode(['success' => true, 'message' => 'ATTACHMENT_UPDATED', 'data' => $response_data]));
}

public function delete_attachment()
{
    // Get input data
    $user_id = $this->input->get('user_id');
    $attachment_id = $this->input->get('attachment_id');
    $delete_type = $this->input->get('delete_type') ?? 'soft'; // Default to soft delete

    // Validate required fields
    if (empty($user_id)) {
        return $this->output->set_content_type('application/json')->set_status_header(400)
            ->set_output(json_encode(['success' => false, 'message' => 'INVALID_USER_ID']));
    }
    if (empty($attachment_id) || !is_numeric($attachment_id)) {
        return $this->output->set_content_type('application/json')->set_status_header(400)
            ->set_output(json_encode(['success' => false, 'message' => 'INVALID_ATTACHMENT_ID']));
    }
    if (!in_array($delete_type, ['soft', 'hard'])) {
        return $this->output->set_content_type('application/json')->set_status_header(400)
            ->set_output(json_encode(['success' => false, 'message' => 'INVALID_DELETE_TYPE']));
    }

    // Validate user
    $this->db->where('id', $user_id)->where('is_active', 1);
    if ($this->db->get('users')->num_rows() == 0) {
        return $this->output->set_content_type('application/json')->set_status_header(400)
            ->set_output(json_encode(['success' => false, 'message' => 'INVALID_USER_ID']));
    }

    // Check if attachment exists and is active
    $this->db->where('id', $attachment_id)->where('is_active', 1);
    $attachment = $this->db->get('attachments')->row_array();
    if (!$attachment) {
        return $this->output->set_content_type('application/json')->set_status_header(400)
            ->set_output(json_encode(['success' => false, 'message' => 'ATTACHMENT_NOT_FOUND']));
    }

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

    if ($delete_type === 'soft') {
        // Soft delete attachment
        $this->db->where('id', $attachment_id);
        $this->db->update('attachments', [
            'is_active' => 0,
            'deleted_at' => date('Y-m-d H:i:s'),
            'updated_by' => $user_id
        ]);

        // Soft delete related attachment_files
        $this->db->where('attachment_id', $attachment_id)->where('is_active', 1);
        $this->db->update('attachment_files', [
            'is_active' => 0,
            'deleted_at' => date('Y-m-d H:i:s'),
            'updated_by' => $user_id
        ]);
    } else {
        // Hard delete attachment_files
        $this->db->where('attachment_id', $attachment_id);
        $this->db->delete('attachment_files');

        // Hard delete attachment
        $this->db->where('id', $attachment_id);
        $this->db->delete('attachments');
    }

    // Commit transaction
    $this->db->trans_complete();
    if ($this->db->trans_status() === FALSE) {
        return $this->output->set_content_type('application/json')->set_status_header(400)
            ->set_output(json_encode(['success' => false, 'message' => 'TRANSACTION_FAILED']));
    }

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


// Helper: Fetch Attachment Data
    private function get_attachment_data($attachment_id)
    {
        $this->db->where('a.id', $attachment_id)->where('a.is_active', 1);
        $attachment = $this->db->get('attachments a')->row_array();

        if (!$attachment) return null;

        $data = [
            'id' => (string)$attachment['id'],
            'type' => $attachment['type'],
            'title' => $attachment['title'],
            'date' => $attachment['date']
        ];

        if ($attachment['type'] === 'folder') {
            $this->db->where('attachment_id', $attachment_id)->where('is_active', 1);
            $files = $this->db->get('attachment_files')->result_array();
            $data['files'] = array_map(function ($file) {
                return [
                    'id' => (string)$file['id'],
                    'name' => $file['name'],
                    'type' => $file['type'],
                    'url' => $file['url'],
                    'date' => $file['date'],
                    'size' => $file['size']
                ];
            }, $files);
        } else {
            $data['url'] = $attachment['url'];
            $data['size'] = $attachment['size'];
            $data['files'] = [];
        }

        // Fetch in_charge details
        $in_charge_ids = json_decode($attachment['in_charge_ids'], true) ?: [];
        $data['team'] = [
            'name' => 'Attachment Team', // Consistent with your "Activity Team" naming
            'members' => $this->get_in_charge_details($in_charge_ids)
        ];

        return $data;
    }


private function get_in_charge_details($in_charge_ids)
    {
        $details = [];
        if (!empty($in_charge_ids)) {
            $this->db->select('id, first_name, image as avatar');
            $this->db->where_in('id', $in_charge_ids);
            $this->db->where('is_active', 1);
            $users = $this->db->get('users')->result_array();
            foreach ($users as $user) {
                $details[] = [
                    'id' => (string)$user['id'],
                    'first_name' => $user['first_name'],
                    'avatar' => $user['avatar'] ?? ''
                ];
            }
        }
        return $details;
    }

}