<?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');
        $this->db->query("SET time_zone = '+03:00'");
    }
  
    
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'
            )));
    }
}



//with isUrgent
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
    $is_urgent = $this->input->post('isUrgent')?? 0;

    // 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,
         'isUrgent' => $is_urgent
    ];

    // 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 = "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');

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

            $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 Sam and Racheal,</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 Sam and Racheal,\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 Sam and Racheal,</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 Sam and Racheal,\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 Sam and Racheal,</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 Sam and Racheal,\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 Sam and Racheal,</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 Sam and Racheal,\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));
}



// // with the isUrgent prop
//  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
//         $is_urgent = $this->input->post('isUrgent') ?? 0; // Default to 0 (non-urgent)

//         // 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 isUrgent
//         if (!in_array($is_urgent, [0, 1])) {
//             return $this->output
//                 ->set_content_type('application/json')
//                 ->set_status_header(400)
//                 ->set_output(json_encode(['success' => false, 'message' => 'INVALID_URGENT_VALUE']));
//         }

//         // 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,
//             'isUrgent' => $is_urgent
//         ];

//         // 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 = "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;">'
//                 . '© 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($email);
//                     }

//                     $notification_type = 'PRODUCT_CREATION';
//                     $notification_title = '';
//                     $notification_message = '';
//                     $email_subject = '';
//                     $email_body = '';
//                     $email_alt_body = '';
//                     $urgency_note = $is_urgent ? ' (Urgent)' : '';
//                     $urgency_email_note = $is_urgent ? '<p style="color: #D32F2F; font-weight: bold; margin: 10px 0;">This product is marked as urgent.</p>' : '';

//                     switch ($data['status']) {
//                         case 'Submitted':
//                             $notification_title = 'New Product Submitted' . $urgency_note;
//                             $notification_message = "A new product \"{$created_product['name']}\" on activity: {$activity_name} has been submitted by {$creator_name}." . ($is_urgent ? ' This product is marked as urgent.' : '');
//                             $email_subject = 'New Product Submitted for Review' . $urgency_note;
//                             $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$urgency_note</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>"
//                                 . "$urgency_email_note"
//                                 . "<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}." . ($is_urgent ? ' This product is marked as urgent.' : '') . "\n\nRegards,\nSmartHub";
//                             break;

//                         case 'In Review':
//                             $notification_title = 'New Product In Review' . $urgency_note;
//                             $notification_message = "A new product \"{$created_product['name']}\" on activity: {$activity_name} is in review by {$creator_name}." . ($is_urgent ? ' This product is marked as urgent.' : '');
//                             $email_subject = 'New Product In Review' . $urgency_note;
//                             $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$urgency_note</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>"
//                                 . "$urgency_email_note"
//                                 . "<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}." . ($is_urgent ? ' This product is marked as urgent.' : '') . "\n\nRegards,\nSmartHub";
//                             break;

//                         case 'Finalised':
//                             $notification_title = 'New Product Finalised' . $urgency_note;
//                             $notification_message = "A new product \"{$created_product['name']}\" on activity: {$activity_name} has been finalised by {$creator_name}." . ($is_urgent ? ' This product was marked as urgent.' : '');
//                             $email_subject = 'New Product Finalised' . $urgency_note;
//                             $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$urgency_note</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>"
//                                 . "$urgency_email_note"
//                                 . "<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}." . ($is_urgent ? ' This product was marked as urgent.' : '') . "\n\nRegards,\nSmartHub";
//                             break;

//                         case 'Declined':
//                             $decline_reason = $this->input->post('decline_reason') ?? 'No reason provided';
//                             $notification_title = 'New Product Declined' . $urgency_note;
//                             $notification_message = "A new product \"{$created_product['name']}\" on activity: {$activity_name} has been declined by {$creator_name}. Reason: " . strip_tags($decline_reason) . ($is_urgent ? ' This product was marked as urgent.' : '');
//                             $email_subject = 'New Product Declined' . $urgency_note;
//                             $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$urgency_note</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>"
//                                 . "$urgency_email_note"
//                                 . "<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) . ($is_urgent ? ' This product was marked as urgent.' : '') . "\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'];
//             $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 = '';
//             $urgency_note = $is_urgent ? ' (Urgent)' : '';
//             $urgency_email_note = $is_urgent ? '<p style="color: #D32F2F; font-weight: bold; margin: 10px 0;">This product is marked as urgent.</p>' : '';

//             switch ($data['status']) {
//                 case 'Submitted':
//                     $notification_title = 'New Product Submitted' . $urgency_note;
//                     $notification_message = "A new product \"{$created_product['name']}\" on activity: {$activity_name} has been submitted by {$creator_name} for review." . ($is_urgent ? ' This product is marked as urgent.' : '');
//                     $email_subject = 'New Product Submitted for Review/Approval' . $urgency_note;
//                     $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$urgency_note</h2>"
//                         . "<p style='margin: 0 0 15px;'>Dear Sam and Racheal,</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>"
//                         . "$urgency_email_note"
//                         . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
//                         . "</td></tr>"
//                         . "<tr><td align='center'>$footer</td></tr>"
//                         . "</table></body></html>";
//                     $email_alt_body = "Dear Sam and Racheal,\n\nA new product, \"{$created_product['name']}\", on activity: {$activity_name} ($activity_link) has been submitted by {$creator_name} for review/approval." . ($is_urgent ? ' This product is marked as urgent.' : '') . "\n\nRegards,\nSmartHub";
//                     break;

//                 case 'In Review':
//                     $notification_title = 'New Product In Review' . $urgency_note;
//                     $notification_message = "A new product \"{$created_product['name']}\" on activity: {$activity_name} is in review by {$creator_name}." . ($is_urgent ? ' This product is marked as urgent.' : '');
//                     $email_subject = 'New Product In Review' . $urgency_note;
//                     $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$urgency_note</h2>"
//                         . "<p style='margin: 0 0 15px;'>Dear Sam and Racheal,</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>"
//                         . "$urgency_email_note"
//                         . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
//                         . "</td></tr>"
//                         . "<tr><td align='center'>$footer</td></tr>"
//                         . "</table></body></html>";
//                     $email_alt_body = "Dear Sam and Racheal,\n\nA new product, \"{$created_product['name']}\", on activity: {$activity_name} ($activity_link) is in review by {$creator_name}." . ($is_urgent ? ' This product is marked as urgent.' : '') . "\n\nRegards,\nSmartHub";
//                     break;

//                 case 'Finalised':
//                     $notification_title = 'New Product Finalised' . $urgency_note;
//                     $notification_message = "A new product \"{$created_product['name']}\" on activity: {$activity_name} has been finalised by {$creator_name}." . ($is_urgent ? ' This product was marked as urgent.' : '');
//                     $email_subject = 'New Product Finalised' . $urgency_note;
//                     $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$urgency_note</h2>"
//                         . "<p style='margin: 0 0 15px;'>Dear Sam and Racheal,</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>"
//                         . "$urgency_email_note"
//                         . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
//                         . "</td></tr>"
//                         . "<tr><td align='center'>$footer</td></tr>"
//                         . "</table></body></html>";
//                     $email_alt_body = "Dear Sam and Racheal,\n\nA new product, \"{$created_product['name']}\", on activity: {$activity_name} ($activity_link) has been finalised by {$creator_name}." . ($is_urgent ? ' This product was marked as urgent.' : '') . "\n\nRegards,\nSmartHub";
//                     break;

//                 case 'Declined':
//                     $decline_reason = $this->input->post('decline_reason') ?? 'No reason provided';
//                     $notification_title = 'New Product Declined' . $urgency_note;
//                     $notification_message = "A new product \"{$created_product['name']}\" on activity: {$activity_name} has been declined by {$creator_name}. Reason: " . strip_tags($decline_reason) . ($is_urgent ? ' This product was marked as urgent.' : '');
//                     $email_subject = 'New Product Declined' . $urgency_note;
//                     $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$urgency_note</h2>"
//                         . "<p style='margin: 0 0 15px;'>Dear Sam and Racheal,</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>"
//                         . "$urgency_email_note"
//                         . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
//                         . "</td></tr>"
//                         . "<tr><td align='center'>$footer</td></tr>"
//                         . "</table></body></html>";
//                     $email_alt_body = "Dear Sam and Racheal,\n\nA new product, \"{$created_product['name']}\", on activity: {$activity_name} ($activity_link) has been declined by {$creator_name}.\n\nReason: " . strip_tags($decline_reason) . ($is_urgent ? ' This product was marked as urgent.' : '') . "\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'],
//                 'isUrgent' => (int)$created_product['isUrgent']
//             ]
//         ];

//         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_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;
}

// with urgency
// 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
//     $is_urgent = $this->input->post('isUrgent'); // Optional, defaults to existing value

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

//     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 = "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');

//             if (!empty($team_emails)) {
//                 foreach ($team_emails as $email) {
//                     $mail->addAddress($email); //  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 Sam and Racheal,</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 Sam and Racheal,\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 Sam and Racheal,</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 Sam and Racheal,\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 Sam and Racheal,</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 Sam and Racheal,\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 Sam and Racheal,</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 Sam and Racheal,\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));
// }


// with urgency + $isRequiredToProceed
public function edit_product($id)
{
    // Get form data
    
    $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
    $is_urgent = $this->input->post('isUrgent'); // Optional, defaults to existing value
    $isRequiredToProceed = $this->input->post('isRequiredToProceed');

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

    // 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);
    $data['isUrgent'] = $is_urgent;
    $data['isRequiredToProceed'] = $isRequiredToProceed;

    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 = "https://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');

            if (!empty($team_emails)) {
                foreach ($team_emails as $email) {
                    $mail->addAddress($email); //  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 Sam and Racheal,</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 Sam and Racheal,\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 Sam and Racheal,</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 Sam and Racheal,\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 Sam and Racheal,</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 Sam and Racheal,\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 Sam and Racheal,</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 Sam and Racheal,\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));
}


//old without annual

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

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

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

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

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

//     // Check if product exists and is active
//     $this->db->where('id', $product_id);
//     $this->db->where('is_active', 1); // Ensure the product is active before deleting
//     $product = $this->db->get('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
//             ]
//         )));
// }

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

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

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

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

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

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

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

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

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

        $this->db->where('id', $product_id);
        $this->db->update('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 : 

// without notifiying team members
// 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');
//     $notify_finance_team = $this->input->post('notify_finance_team'); // New field

//     // 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 and fetch main_office
//     $this->db->select('id, first_name, main_office');
//     $this->db->where('id', $user_id)->where('is_active', 1);
//     $user = $this->db->get('users')->row_array();
//     if (!$user) {
//         return $this->output->set_content_type('application/json')->set_status_header(400)
//             ->set_output(json_encode(['success' => false, 'message' => 'INVALID_USER_ID']));
//     }
//     $creator_name = $user['first_name'];
//     $main_office = strtolower($user['main_office'] ?? '');

//     // 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
//     $type = !empty($_FILES['file']['name']) ? 'file' : 'folder';
//     $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'];
//     }

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

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

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

//         // Determine entity name, link, and type
//         $entity_name = '';
//         $entity_link = '';
//         $entity_type = '';
//         $app_link = "https://www.smarthub.ovalspace.co/ug/programmes";

//         // Determine the activity ID and fetch related data
//         $target_activity_id = $activity_id;
//         if ($sub_activity_id) {
//             $this->db->select('parent_activity_id, name');
//             $this->db->where('id', $sub_activity_id);
//             $sub_activity = $this->db->get('sub_activities')->row_array();
//             $target_activity_id = $sub_activity['parent_activity_id'] ?? null;
//             $entity_name = $sub_activity['name'] ?? 'Unknown Sub-Activity';
//             $entity_type = 'Sub Activity';
//         } elseif ($follow_up_activity_id) {
//             $this->db->select('parent_activity_id, name');
//             $this->db->where('id', $follow_up_activity_id);
//             $follow_up = $this->db->get('follow_up_activities')->row_array();
//             $target_activity_id = $follow_up['parent_activity_id'] ?? null;
//             $entity_name = $follow_up['name'] ?? 'Unknown Follow-Up Activity';
//             $entity_type = 'Follow Up Activity';
//         } elseif ($activity_id) {
//             $this->db->select('name');
//             $this->db->where('id', $activity_id);
//             $activity = $this->db->get('activities')->row_array();
//             $entity_name = $activity['name'] ?? 'Unknown Activity';
//             $entity_type = 'Activity';
//         }

//         // Fetch activity data for the link using target_activity_id
//         if ($target_activity_id) {
//             $this->db->select('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', $target_activity_id);
//             $activity_data = $this->db->get()->row_array();
//             if ($activity_data) {
//                 $programme_code = $activity_data['programme_code'] ?? 'SDLG';
//                 $quarter = $activity_data['quarter'] ?? 'Q1';
//                 $year = $activity_data['year'] ?? '2025';
//                 $entity_link = "$app_link/{$programme_code}/activities/{$quarter}/{$year}/{$target_activity_id}";
//             } else {
//                 $entity_link = "$app_link"; // Fallback if activity data isn't found
//             }
//         } else {
//             $entity_link = "$app_link"; // Fallback if no valid activity ID
//         }

//         // // Define the finance team map
//         // $finance_team_map = [
//         //     'arua' => ['kimbowaandrew@gmail.com'],
//         //     'kampala' => ['kimbowaandrew@gmail.com'],
//         // ];
//         // $default_finance_emails = ['kimbowaandrew@gmail.com'];
//         // $finance_emails = $default_finance_emails;
//         // foreach ($finance_team_map as $office_key => $emails) {
//         //     if (stripos($main_office, $office_key) !== false) {
//         //         $finance_emails = $emails;
//         //         break;
//         //     }
//         // }


// // Define the finance team map
// $finance_team_map = [
//     'arua' => ['topista.oleru@vngi.org', 'paul.bate@vngi.org', 'sam.ejibua@vng.nl', 'racheal.atukwase@vngi.org','nakitende.millen@vngi.org'],
//     'kampala' => ['nakitende.millen@vngi.org', 'paul.bate@vngi.org', 'sam.ejibua@vng.nl', 'racheal.atukwase@vngi.org'],
// ];
// $default_finance_emails = ['paul.bate@vngi.org', 'nakitende.millen@vngi.org', 'sam.ejibua@vng.nl', 'racheal.atukwase@vngi.org'];

//   $finance_emails = $default_finance_emails;
//         foreach ($finance_team_map as $office_key => $emails) {
//             if (stripos($main_office, $office_key) !== false) {
//                 $finance_emails = $emails;
//                 break;
//             }
//         }


//         // Fetch finance team user IDs for notifications table
//         $this->db->select('id, email');
//         $this->db->where_in('email', $finance_emails);
//         $finance_users = $this->db->get('users')->result_array();
//         $finance_user_ids = array_column($finance_users, 'id');

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

//         $notification_title = 'New Attachment Added';
//         $notification_message = "A new attachment \"{$title}\" has been added on the {$entity_type}: \"{$entity_name}\" by {$creator_name}.";
//         $email_subject = 'New Attachment Notification';
//         $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 Attachment Notification</h2>"
//             . "<p style='margin: 0 0 15px;'>Dear Finance Team,</p>"
//             . "<p style='margin: 0 0 15px;'>A new attachment, \"<strong>" . htmlspecialchars($title) . "</strong>\", has been added on the <strong>" . htmlspecialchars($entity_type) . "</strong>: "
//             . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($entity_name) . "</a> "
//             . "by <strong>" . htmlspecialchars($creator_name) . "</strong>.</p>"
//             . "<p style='margin: 0;'>Please review as necessary.</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 Finance Team,\n\nA new attachment, \"{$title}\", has been added on the {$entity_type}: {$entity_name} ($entity_link) by {$creator_name}.\n\nPlease review as necessary.\n\nRegards,\nSmartHub";

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

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

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

// with notifications to team members
   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');
    $notify_finance_team = $this->input->post('notify_finance_team');

    // 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 and fetch main_office
    $this->db->select('id, first_name, main_office');
    $this->db->where('id', $user_id)->where('is_active', 1);
    $user = $this->db->get('users')->row_array();
    if (!$user) {
        return $this->output->set_content_type('application/json')->set_status_header(400)
            ->set_output(json_encode(['success' => false, 'message' => 'INVALID_USER_ID']));
    }
    $creator_name = $user['first_name'];
    $main_office = strtolower($user['main_office'] ?? '');

    // Validate the provided entity exists and fetch in_charge_ids
    $target_activity_id = null;
    $entity_name = '';
    $entity_type = '';
    $entity_in_charge_ids = [];
    if ($activity_id) {
        $this->db->select('id, name, inCharges');
        $this->db->where('id', $activity_id)->where('is_active', 1);
        $activity = $this->db->get('activities')->row_array();
        if (!$activity) {
            return $this->output->set_content_type('application/json')->set_status_header(400)
                ->set_output(json_encode(['success' => false, 'message' => 'ACTIVITY_NOT_FOUND']));
        }
        $target_activity_id = $activity_id;
        $entity_name = $activity['name'] ?? 'Unknown Activity';
        $entity_type = 'Activity';
        $entity_in_charge_ids = json_decode($activity['in_charge_ids'] ?? '[]', true);
    } elseif ($sub_activity_id) {
        $this->db->select('id, parent_activity_id, name, inCharges');
        $this->db->where('id', $sub_activity_id)->where('is_active', 1);
        $sub_activity = $this->db->get('sub_activities')->row_array();
        if (!$sub_activity) {
            return $this->output->set_content_type('application/json')->set_status_header(400)
                ->set_output(json_encode(['success' => false, 'message' => 'SUB_ACTIVITY_NOT_FOUND']));
        }
        $target_activity_id = $sub_activity['parent_activity_id'] ?? null;
        $entity_name = $sub_activity['name'] ?? 'Unknown Sub-Activity';
        $entity_type = 'Sub Activity';
        $entity_in_charge_ids = json_decode($sub_activity['in_charge_ids'] ?? '[]', true);
    } elseif ($follow_up_activity_id) {
        $this->db->select('id, parent_activity_id, name, inCharges');
        $this->db->where('id', $follow_up_activity_id)->where('is_active', 1);
        $follow_up = $this->db->get('follow_up_activities')->row_array();
        if (!$follow_up) {
            return $this->output->set_content_type('application/json')->set_status_header(400)
                ->set_output(json_encode(['success' => false, 'message' => 'FOLLOW_UP_ACTIVITY_NOT_FOUND']));
        }
        $target_activity_id = $follow_up['parent_activity_id'] ?? null;
        $entity_name = $follow_up['name'] ?? 'Unknown Follow-Up Activity';
        $entity_type = 'Follow Up Activity';
        $entity_in_charge_ids = json_decode($follow_up['in_charge_ids'] ?? '[]', true);
    }

    // Parse and validate in_charge_ids (for the attachment itself)
    $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
    $type = !empty($_FILES['file']['name']) ? 'file' : 'folder';
    $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'];
    }

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

    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']));
    }

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

    // Determine entity link
    $app_link = "https://www.smarthub.ovalspace.co/ug/programmes";
    $entity_link = $app_link;
    if ($target_activity_id) {
        $this->db->select('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', $target_activity_id);
        $activity_data = $this->db->get()->row_array();
        if ($activity_data) {
            $programme_code = $activity_data['programme_code'] ?? 'SDLG';
            $quarter = $activity_data['quarter'] ?? 'Q1';
            $year = $activity_data['year'] ?? '2025';
            $entity_link = "$app_link/{$programme_code}/activities/{$quarter}/{$year}/{$target_activity_id}";
        }
    }

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

    // Notify activity team members if submitter is not in the team
    $is_team_member = in_array($user_id, $in_charge_array);
    // print_r($in_charge_array);
    // return;
    if (!$is_team_member && !empty($in_charge_array)) {
        $this->db->select('id, email');
        $this->db->where_in('id', $in_charge_array)->where('is_active', 1);
        $team_members = $this->db->get('users')->result_array();
        $team_emails = array_column($team_members, 'email');
        $team_user_ids = array_column($team_members, 'id');
        
        // print_r($team_emails);
        // return;

        if (!empty($team_emails)) {
            // Activity team notification
            $team_notification_title = 'New Attachment Added';
            $team_notification_message = "A new attachment \"{$title}\" has been added to the {$entity_type}: \"{$entity_name}\" by {$creator_name}.";
            $team_email_subject = 'New Attachment Added';
            $team_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 Attachment Added</h2>"
                . "<p style='margin: 0 0 15px;'>Dear  Team,</p>"
                . "<p style='margin: 0 0 15px;'>A new attachment, \"<strong>" . htmlspecialchars($title) . "</strong>\", has been added to the <strong>" . htmlspecialchars($entity_type) . "</strong>: "
                . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($entity_name) . "</a> "
                . "by <strong>" . htmlspecialchars($creator_name) . "</strong>.</p>"
                . "<p style='margin: 0;'>Please review the attachment and take any necessary actions.</p>"
                . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
                . "</td></tr>"
                . "<tr><td align='center'>$footer</td></tr>"
                . "</table></body></html>";
            $team_email_alt_body = "Dear Team,\n\nA new attachment, \"{$title}\", has been added to the {$entity_type}: {$entity_name} ($entity_link) by {$creator_name}.\n\nPlease review the attachment and take any necessary actions.\n\nRegards,\nSmartHub";

            // Send email to activity team
            foreach ($team_emails as $email) {
                $mail->addAddress($email);
                // $mail->addAddress('kimbowaandrew@gmail.com');
            }
            $mail->Subject = $team_email_subject;
            $mail->Body = $team_email_body;
            $mail->AltBody = $team_email_alt_body;
            if (!$mail->send()) {
                log_message('error', 'Failed to send email to activity team: ' . $mail->ErrorInfo);
            }
            $mail->clearAddresses();

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

    // Notification logic for finance team if notify_finance_team is 1
    if ($notify_finance_team == 1) {
        $finance_team_map = [
            'arua' => ['topista.oleru@vngi.org', 'paul.bate@vngi.org', 'sam.ejibua@vng.nl', 'racheal.atukwase@vngi.org', 'nakitende.millen@vngi.org'],
            'kampala' => ['nakitende.millen@vngi.org', 'paul.bate@vngi.org', 'sam.ejibua@vng.nl', 'racheal.atukwase@vngi.org'],
        ];
        $default_finance_emails = ['paul.bate@vngi.org', 'nakitende.millen@vngi.org', 'sam.ejibua@vng.nl', 'racheal.atukwase@vngi.org'];
        $finance_emails = $default_finance_emails;
        foreach ($finance_team_map as $office_key => $emails) {
            if (stripos($main_office, $office_key) !== false) {
                $finance_emails = $emails;
                break;
            }
        }

        // Fetch finance team user IDs for notifications table
        $this->db->select('id, email');
        $this->db->where_in('email', $finance_emails);
        $finance_users = $this->db->get('users')->result_array();
        $finance_user_ids = array_column($finance_users, 'id');

        // Finance team notification
        $finance_notification_title = 'New Attachment Added';
        $finance_notification_message = "A new attachment \"{$title}\" has been added on the {$entity_type}: \"{$entity_name}\" by {$creator_name}.";
        $finance_email_subject = 'New Attachment Notification';
        $finance_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 Attachment Notification</h2>"
            . "<p style='margin: 0 0 15px;'>Dear Finance Team,</p>"
            . "<p style='margin: 0 0 15px;'>A new attachment, \"<strong>" . htmlspecialchars($title) . "</strong>\", has been added on the <strong>" . htmlspecialchars($entity_type) . "</strong>: "
            . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($entity_name) . "</a> "
            . "by <strong>" . htmlspecialchars($creator_name) . "</strong>.</p>"
            . "<p style='margin: 0;'>Please review as necessary.</p>"
            . "<p style='margin: 0;'>Regards,<br>SmartHub Team</p>"
            . "</td></tr>"
            . "<tr><td align='center'>$footer</td></tr>"
            . "</table></body></html>";
        $finance_email_alt_body = "Dear Finance Team,\n\nA new attachment, \"{$title}\", has been added on the {$entity_type}: {$entity_name} ($entity_link) by {$creator_name}.\n\nPlease review as necessary.\n\nRegards,\nSmartHub";

        // Send email to finance team
        foreach ($finance_emails as $email) {
            $mail->addAddress($email);
            // $mail->addAddress('andrew@ovalspace.co');
        }
        $mail->Subject = $finance_email_subject;
        $mail->Body = $finance_email_body;
        $mail->AltBody = $finance_email_alt_body;
        if (!$mail->send()) {
            log_message('error', 'Failed to send email to finance team: ' . $mail->ErrorInfo);
        }
        $mail->clearAddresses();

        // Store notifications for finance team
        foreach ($finance_user_ids as $finance_user_id) {
            $this->db->insert('notifications', [
                'user_id' => $finance_user_id,
                'type' => 'ATTACHMENT_CREATION',
                'title' => $finance_notification_title,
                'message' => $finance_notification_message,
                'link' => $entity_link,
                'is_read' => 0,
                'created_by' => $user_id
            ]);
        }
    }

    // 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
    $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');
    $files_to_be_removed = $this->input->post('files_to_be_removed');
    $notify_finance_team = $this->input->post('notify_finance_team'); // New field

    // 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 and fetch main_office
    $this->db->select('id, first_name, main_office');
    $this->db->where('id', $user_id)->where('is_active', 1);
    $user = $this->db->get('users')->row_array();
    if (!$user) {
        return $this->output->set_content_type('application/json')->set_status_header(400)
            ->set_output(json_encode(['success' => false, 'message' => 'INVALID_USER_ID']));
    }
    $creator_name = $user['first_name'];
    $main_office = strtolower($user['main_office'] ?? '');

    // Check entity IDs
    $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 entity 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
    $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
    $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)) {
            $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') {
        $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');

        $this->db->where('attachment_id', $id)->where_in('id', $files_to_remove_array);
        $this->db->delete('attachment_files');

        foreach ($file_urls as $file_url) {
            $file_path = FCPATH . str_replace(base_url(), '', $file_url);
            if (file_exists($file_path)) {
                unlink($file_path);
            }
        }
    }

    // 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']));
    }
    
    
    if ($notify_finance_team == 1) {
    $this->load->library('phpmailer_lib');
    $mail = $this->phpmailer_lib->load();
    $mail->isSMTP();
    $mail->Host = 'smarthub.ovalspace.co';
    $mail->SMTPAuth = true;
    $mail->Username = 'notifications@smarthub.ovalspace.co';
    $mail->Password = 'wgw6.)O7sCTy';
    $mail->SMTPSecure = 'ssl';
    $mail->Port = 465;
    $mail->setFrom('notifications@smarthub.ovalspace.co', 'SmartHub Notification');
    $mail->isHTML(true);

    // Determine entity name, link, and type
    $entity_name = '';
    $entity_link = '';
    $entity_type = '';
    $app_link = "https://www.smarthub.ovalspace.co/ug/programmes";

    // Determine the activity ID and fetch related data
    $activity_id = $activity_id ?: $attachment['activity_id'];
    $sub_activity_id = $sub_activity_id ?: $attachment['sub_activity_id'];
    $follow_up_activity_id = $follow_up_activity_id ?: $attachment['follow_up_activity_id'];
    
    $target_activity_id = $activity_id;
    if ($sub_activity_id) {
        $this->db->select('parent_activity_id, name');
        $this->db->where('id', $sub_activity_id);
        $sub_activity = $this->db->get('sub_activities')->row_array();
        $target_activity_id = $sub_activity['parent_activity_id'] ?? null;
        $entity_name = $sub_activity['name'] ?? 'Unknown Sub-Activity';
        $entity_type = 'Sub Activity';
    } elseif ($follow_up_activity_id) {
        $this->db->select('parent_activity_id, name');
        $this->db->where('id', $follow_up_activity_id);
        $follow_up = $this->db->get('follow_up_activities')->row_array();
        $target_activity_id = $follow_up['parent_activity_id'] ?? null;
        $entity_name = $follow_up['name'] ?? 'Unknown Follow-Up Activity';
        $entity_type = 'Follow Up Activity';
    } elseif ($activity_id) {
        $this->db->select('name');
        $this->db->where('id', $activity_id);
        $activity = $this->db->get('activities')->row_array();
        $entity_name = $activity['name'] ?? 'Unknown Activity';
        $entity_type = 'Activity';
    }

    // Fetch activity data for the link using target_activity_id
    if ($target_activity_id) {
        $this->db->select('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', $target_activity_id);
        $activity_data = $this->db->get()->row_array();
        if ($activity_data) {
            $programme_code = $activity_data['programme_code'] ?? 'SDLG';
            $quarter = $activity_data['quarter'] ?? 'Q1';
            $year = $activity_data['year'] ?? '2025';
            $entity_link = "$app_link/{$programme_code}/activities/{$quarter}/{$year}/{$target_activity_id}";
        } else {
            $entity_link = "$app_link"; // Fallback if activity data isn't found
        }
    } else {
        $entity_link = "$app_link"; // Fallback if no valid activity ID
    }

      //     // Finance team emails based on main_office
    //     $finance_emails = (stripos($main_office, 'arua') !== false) 
    // ? ['topista.oleru@vngi.org', 'sam.ejibua@vng.nl']
    // : ['paul.bate@vngi.org', 'nakitende.millen@vngi.org', 'sam.ejibua@vng.nl'];
    
    //  // Finance team emails based on main_office
    //     $finance_emails = (stripos($main_office, 'arua') !== false) 
    // ? ['kimbowaandrew@gmail.com', 'andrew@ovalspace.co']
    // : ['andrewkimbowa2021@gmail.com'];


// Define the finance team map
$finance_team_map = [
    'arua' => ['topista.oleru@vngi.org', 'paul.bate@vngi.org', 'nakitende.millen@vngi.org', 'sam.ejibua@vng.nl', 'racheal.atukwase@vngi.org'],
    'kampala' => ['nakitende.millen@vngi.org', 'paul.bate@vngi.org', 'sam.ejibua@vng.nl', 'racheal.atukwase@vngi.org'],
];
$default_finance_emails = ['paul.bate@vngi.org', 'nakitende.millen@vngi.org', 'sam.ejibua@vng.nl', 'racheal.atukwase@vngi.org'];

$finance_emails = $default_finance_emails;
foreach ($finance_team_map as $office_key => $emails) {
    if (stripos($main_office, $office_key) !== false) {
        $finance_emails = $emails;
        break;
    }
}



        // Fetch finance team user IDs
        $this->db->select('id, email');
        $this->db->where_in('email', $finance_emails);
        $finance_users = $this->db->get('users')->result_array();
        $finance_user_ids = array_column($finance_users, 'id');

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

        $notification_title = 'Attachment Updated';
        $notification_message = "The attachment \"{$title}\" on {$entity_name} has been updated by {$creator_name}.";
        $email_subject = 'Attachment Update Notification';
        $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;'>Attachment Update Notification</h2>"
            . "<p style='margin: 0 0 15px;'>Dear Finance Team,</p>"
            . "<p style='margin: 0 0 15px;'>The attachment, \"<strong>" . htmlspecialchars($title) . "</strong>\", on "
            . "<a href='$entity_link' style='color: #00A1E5; text-decoration: underline;'>" . htmlspecialchars($entity_name) . "</a> "
            . "has been updated by <strong>" . htmlspecialchars($creator_name) . "</strong>.</p>"
            . "<p style='margin: 0;'>Please review as necessary.</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 Finance Team,\n\nThe attachment, \"{$title}\", on {$entity_name} ($entity_link) has been updated by {$creator_name}.\n\nPlease review as necessary.\n\nRegards,\nSmartHub";

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

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

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

public function delete_attachment()
{
    // Get input data
    $user_id = $this->input->get('user_id');
    $isAnnual = $this->input->get('isAnnual');
    $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']));
    }
    
    
    //check is annual
    if($isAnnual =='true'){
     $data = [
            'isActiveOnAnnual' => 0,
            'updated_by' => $user_id,
            'updated_at' => date('Y-m-d H:i:s') // Current timestamp
        ];
        $this->db->where('id', $attachment_id);
        $this->db->update('attachments', $data);
        
        return $this->output
        ->set_content_type('application/json')
        ->set_status_header(200)
        ->set_output(json_encode(array(
            'success' => true,
            'message' => ($delete_type === 'soft' ? 'ATTACHMENT_SOFT_DELETED' : 'ATTACHMENT_HARD_DELETED'),
            'data' => [
                'attachment_id' => $attachment_id,
                'isAnnual'=>'YES',
                'delete_type' => $delete_type
            ]
        )));
    }
    

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

}