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

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

        $this->load->helper('form');
        $this->load->library('upload');
    }
    
// public function get_product_types()
// {
//     // // Query to get specific columns (id, name, category) from the product_types table
//     // $this->db->select('id, name, category');
//     // $query = $this->db->get('product_types');
    
//     // if ($query->num_rows() > 0) {
//     //     $product_types = $query->result_array();
        
//     //     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' => $product_types
//     //         )));
//     // } 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 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', $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'
            )));
    }
}


// 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'); // Array of user IDs
//     $user_id = $this->input->post('user_id'); // Assuming user_id is passed in the form

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

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

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

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

//     // Prepare data for insertion
//     $data = array(
//         'activity_id' => $activity_id,
//         'name' => $name,
//         'type' => $type, // Set to 'folder' or 'docx' based on category
//         'url' => '', // Will be set for single files or left empty for folders
//         'status' => $status ? $status : 'Draft',
//         '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) ? $in_charge_ids : json_encode([]),
//         'prod_type' => $prod_type,
//         'created_by' => $user_id,
//         'updated_by' => $user_id
//     );

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

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

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

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

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

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

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

//     // Handle file uploads (single or multiple)
//     $files = [];
//     if ($product_type['category'] === 'folder') {
//         // Handle multiple file uploads for folder products
//         if (!empty($_FILES['files']['name'][0])) {
//             $directory = "products";
//             for ($i = 0; $i < count($_FILES['files']['name']); $i++) {
//                 $file_name = $_FILES['files']['name'][$i];
//                 $file_url = $this->upload_file($file_name, "files[{$i}]", $directory);
//                 if ($file_url) {
//                     // Insert file into product_files table
//                     $file_data = array(
//                         'product_id' => 0, // Will be updated after product insert
//                         'name' => pathinfo($file_name, PATHINFO_FILENAME),
//                         'type' => pathinfo($file_name, PATHINFO_EXTENSION),
//                         'url' => $file_url,
//                         'date' => date('Y-m-d'),
//                         'size' => $_FILES['files']['size'][$i] / 1024 / 1024 . ' MB', // Convert to MB
//                         'created_by' => $user_id,
//                         'updated_by' => $user_id
//                     );
//                     $this->db->insert('product_files', $file_data);
//                     $files[] = $file_data;
//                 }
//             }
//         }
//         $data['url'] = ''; // No URL for folders
//     } else {
//       // Handle single file upload for non-folder products
// if (!empty($_FILES['file']['name'])) {
//     $directory = "products";
//     $file_extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION); // Extract file extension
//     $file_url = $this->upload_file($_FILES['file']['name'], 'file', $directory);
    
//     if ($file_url) {
//         $data['url'] = $file_url;
//         $data['type'] = $file_extension; // Set type as the file extension instead of 'docx'
//         $files = []; // No files array for single files
//     }
// }

//     }

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

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

//         // Update product_id in product_files for folder products
//         if ($product_type['category'] === 'folder' && !empty($files)) {
//             foreach ($files as &$file) {
//                 $this->db->where('id', $file['id']);
//                 $this->db->update('product_files', ['product_id' => $product_id]);
//             }
//         }

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

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

//                               $response_data = [
//                             'success' => true,
//                             'message' => 'PRODUCT_ADDED_SUCCESSFULLY',
//                             'data' => [
//                                 'id' => $product_id,
//                                 'type' => $data['type'],
//                                 'name' => $data['name'],
//                                 'url' => $data['url'],
//                                 'inCharge' => $in_charge_details,
//                                 'status' => $data['status'],
//                                 'dateSubmitted' => $data['date_submitted'],
//                                 'lastUpdated' => $data['last_updated']
//                             ]
//                         ];
                        
//                         // Only include 'files' if category is 'folder'
//                         if ($product_type['category'] === 'folder') {
//                             $response_data['data']['files'] = $product_files;
//                         }
                        
//                         return $this->output
//                             ->set_content_type('application/json')
//                             ->set_status_header(201) // Created
//                             ->set_output(json_encode($response_data));

//     } else {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(200)
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'PRODUCT_NOT_ADDED'
//             )));
//     }
// }


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

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

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

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

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

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

//     // Prepare data for insertion
//     $data = array(
//         'activity_id' => $activity_id,
//         'name' => $name,
//         'type' => $type, // Set to 'folder' or '' based on category (will be updated for single files)
//         'url' => '', // Will be set for single files or left empty for folders
//         'status' => $status ? $status : 'Draft',
//         '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,
//         'created_by' => $user_id,
//         'updated_by' => $user_id
//     );

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

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

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

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

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

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

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

//     // Handle file uploads (single or multiple)
//     $files = [];
//     if ($product_type['category'] === 'folder') {
//         // Handle multiple file uploads for folder products
        
       
//         if (!empty($_FILES['files']['name']) && is_array($_FILES['files']['name'])) {
//             $directory = "products"; // Ensure directory exists or create it
//             // if (!file_exists($directory)) {
//             //     mkdir($directory, 0777, true);
//             // }

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

//                     if ($file_error === UPLOAD_ERR_OK) {
//                         // print "files[{$i}]";
//                         // return;
                        
                        
                        
                        
//                         $file_url = $this->upload_file($file_name, "files[{$i}]", $directory);
//                         if ($file_url) {
//                             // Insert file into product_files table
//                             $file_data = array(
//                                 'product_id' => 0, // Will be updated after product insert
//                                 '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 {
//                             log_message('error', "Failed to upload file: " . $file_name . " - Error in upload_file()");
//                             return $this->output
//                                 ->set_content_type('application/json')
//                                 ->set_status_header(400) // Bad Request
//                                 ->set_output(json_encode(array(
//                                     'success' => false,
//                                     'message' => 'FILE_UPLOAD_FAILED: ' . $file_name
//                                 )));
//                         }
//                     } else {
//                         log_message('error', "File upload error for: " . $file_name . " - Error code: " . $file_error);
//                         return $this->output
//                             ->set_content_type('application/json')
//                             ->set_status_header(400) // Bad Request
//                             ->set_output(json_encode(array(
//                                 'success' => false,
//                                 'message' => 'FILE_UPLOAD_ERROR: ' . $file_name . ' (Error ' . $file_error . ')'
//                             )));
//                     }
//                 }
//             }
//         }else{
//             print "tuli wano";
//             return;
//         }
//         $data['url'] = ''; // No URL for folders
//     } else {
//         // Handle single file upload for non-folder products
//         if (!empty($_FILES['file']['name'])) {
//             $directory = "products";
//             if (!file_exists($directory)) {
//                 mkdir($directory, 0777, true);
//             }
//             $file_extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION); // Extract file extension
//             $file_url = $this->upload_file($_FILES['file']['name'], 'file', $directory);
            
//             if ($file_url) {
//                 $data['url'] = $file_url;
//                 $data['type'] = $file_extension; // Set type as the file extension instead of 'docx'
//                 $files = []; // No files array for single files
//             } else {
//                 log_message('error', "Failed to upload single file: " . $_FILES['file']['name']);
//                 return $this->output
//                     ->set_content_type('application/json')
//                     ->set_status_header(400) // Bad Request
//                     ->set_output(json_encode(array(
//                         'success' => false,
//                         'message' => 'FILE_UPLOAD_FAILED: ' . $_FILES['file']['name']
//                     )));
//             }
//         }
//     }

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

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

//         // Update product_id in product_files for folder products
//         if ($product_type['category'] === 'folder' && !empty($files)) {
//             foreach ($files as $file) {
//                 $this->db->where('id', $file['id']);
//                 $this->db->update('product_files', ['product_id' => $product_id]);
//             }
//         }

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

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

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

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

//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(201) // Created
//             ->set_output(json_encode($response_data));
//     } else {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(200)
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'PRODUCT_NOT_ADDED'
//             )));
//     }
// }

// latest update

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

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

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

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

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

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

    // Prepare data for insertion
    $data = array(
        'activity_id' => $activity_id,
        'name' => $name,
        'type' => $type, // Set to 'folder' or '' based on category (will be updated for single files)
        'url' => '', // Will be set for single files or left empty for folders
        'status' => $status ? $status : 'Draft',
        '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,
        'created_by' => $user_id,
        'updated_by' => $user_id
    );

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

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

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

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

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

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

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

    // Handle file uploads (single or multiple)
    $files = [];
    if ($product_type['category'] === 'folder') {
        // Handle multiple file uploads for folder products
        if (!empty($_FILES['files']) && is_array($_FILES['files']['name'])) {
            $directory = "products"; // Ensure directory exists or create it
            if (!file_exists($directory)) {
                mkdir($directory, 0777, true);
            }

            // Debug: Log $_FILES structure to verify
            log_message('debug', '$_FILES structure for files: ' . print_r($_FILES['files'], true));

            // Handle each file in the files array
            foreach ($_FILES['files']['name'] as $index => $file_name) {
                if (!empty($file_name)) {
                    $file_tmp = $_FILES['files']['tmp_name'][$index];
                    $file_error = $_FILES['files']['error'][$index];
                    $file_size = $_FILES['files']['size'][$index];
                    
                    if ($file_error === UPLOAD_ERR_OK) {
                        $file_url = $this->upload_file($file_name, "files[{$index}]", $directory);
                        if ($file_url) {
                            // Insert file into product_files table
                            $file_data = array(
                                'product_id' => 0, // Will be updated after product insert
                                '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 {
                            log_message('error', "Failed to upload file: $file_name - Check upload_file() logs for details");
                            return $this->output
                                ->set_content_type('application/json')
                                ->set_status_header(400) // Bad Request
                                ->set_output(json_encode(array(
                                    'success' => false,
                                    'message' => 'FILE_UPLOAD_FAILED: ' . $file_name
                                )));
                        }
                    } else {
                        log_message('error', "File upload error for: $file_name - Error code: $file_error");
                        return $this->output
                            ->set_content_type('application/json')
                            ->set_status_header(400) // Bad Request
                            ->set_output(json_encode(array(
                                'success' => false,
                                'message' => 'FILE_UPLOAD_ERROR: ' . $file_name . ' (Error ' . $file_error . ')'
                            )));
                    }
                }
            }
        }
        $data['url'] = ''; // No URL for folders
    } else {
        // Handle single file upload for non-folder products
        if (!empty($_FILES['file']['name'])) {
            $directory = "products";
            if (!file_exists($directory)) {
                mkdir($directory, 0777, true);
            }
            $file_extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION); // Extract file extension
            $file_url = $this->upload_file($_FILES['file']['name'], 'file', $directory);
            
            if ($file_url) {
                $data['url'] = $file_url;
                $data['type'] = $file_extension; // Set type as the file extension instead of ''
                $files = []; // No files array for single files
            } else {
                log_message('error', "Failed to upload single file: " . $_FILES['file']['name']);
                return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(400) // Bad Request
                    ->set_output(json_encode(array(
                        'success' => false,
                        'message' => 'FILE_UPLOAD_FAILED: ' . $_FILES['file']['name']
                    )));
            }
        }
    }

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

    if ($insert) {
        $product_id = $this->db->insert_id();

        // Update product_id in product_files for folder products
        if ($product_type['category'] === 'folder' && !empty($files)) {
            foreach ($files as $file) {
                $this->db->where('id', $file['id']);
                $this->db->update('product_files', ['product_id' => $product_id]);
            }
        }

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

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

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

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

        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(201) // Created
            ->set_output(json_encode($response_data));
    } else {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(200)
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'PRODUCT_NOT_ADDED'
            )));
    }
}




    public 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>")
            {
                
                header('Content-type: application/json');
                http_response_code(200);
                echo json_encode(array(
                    'success' => false,
                    'message' => 'PLEASE_TRY_ANOTHER_IMAGE'
                ));
           
                die;
            }
        }


        $upload_data = $this->upload->data();

        $file_url = base_url() . "$directory/" . $upload_data['file_name'];
        return $file_url;
    }
    
    




}