<?php
defined('BASEPATH') or exit('No direct script access allowed');
class OutcomeStatements 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'");
    }
  

/**
 * Upload a new outcome statement document
 * POST /api/outcome-statements
 */
public function upload_outcome_statement()
{
    // Get form data
    $name = $this->input->post('name'); // Optional custom name, will use filename if not provided
    $year = $this->input->post('year') ?? date('Y'); // Default to current year
    $description = $this->input->post('description'); // Optional description
    $progress_marker_id = $this->input->post('progress_marker_id'); // Optional progress marker association
    $user_id = $this->input->post('user_id');

    // 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' => 'User ID is required'
            ]));
    }

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

    // Validate year format (4 digits)
    if (!preg_match('/^\d{4}$/', $year)) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400)
            ->set_output(json_encode([
                'success' => false,
                'message' => 'Year must be a 4-digit number'
            ]));
    }

    // Check if file was uploaded
    if (empty($_FILES['file']['name'])) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400)
            ->set_output(json_encode([
                'success' => false,
                'message' => 'File is required'
            ]));
    }

    // Validate file upload
    if ($_FILES['file']['error'] !== UPLOAD_ERR_OK) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400)
            ->set_output(json_encode([
                'success' => false,
                'message' => 'File upload failed'
            ]));
    }

    // Get file information
    $file_name = $_FILES['file']['name'];
    $file_size = $_FILES['file']['size'];
    $file_tmp = $_FILES['file']['tmp_name'];
    $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

    // Validate file extension (allow common document types)
    $allowed_extensions = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt'];
    if (!in_array($file_ext, $allowed_extensions)) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400)
            ->set_output(json_encode([
                'success' => false,
                'message' => 'Invalid file type. Allowed types: ' . implode(', ', $allowed_extensions)
            ]));
    }

    // Validate file size (max 10MB)
    $max_file_size = 10 * 1024 * 1024; // 10MB in bytes
    if ($file_size > $max_file_size) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400)
            ->set_output(json_encode([
                'success' => false,
                'message' => 'File size exceeds 10MB limit'
            ]));
    }

    // Create upload directory if it doesn't exist
    $upload_dir = 'uploads/outcome_statements/' . $year . '/';
    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0755, true);
    }

    // Generate unique filename to prevent conflicts
    $unique_filename = time() . '_' . $user_id . '_' . uniqid() . '.' . $file_ext;
    $upload_path = $upload_dir . $unique_filename;

    // Move uploaded file
    if (!move_uploaded_file($file_tmp, $upload_path)) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(500)
            ->set_output(json_encode([
                'success' => false,
                'message' => 'Failed to save uploaded file'
            ]));
    }

    // Generate URL for the uploaded file
    $file_url = base_url($upload_path);

    // Use custom name if provided, otherwise use original filename
    $statement_name = !empty($name) ? $name : $file_name;

    // Prepare data for insertion
    $data = [
        'name' => $statement_name,
        'type' => $file_ext,
        'url' => $file_url,
        'file_size' => $file_size,
        'user_id' => $user_id,
        'year' => $year,
        'description' => $description,
        'progress_marker_id' => $progress_marker_id,
        'is_active' => 1,
        'created_at' => date('Y-m-d H:i:s'),
        'updated_at' => date('Y-m-d H:i:s')
    ];

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

    // Insert the outcome statement
    $insert = $this->db->insert('outcome_statements', $data);
    if (!$insert) {
        // Delete uploaded file if database insert fails
        if (file_exists($upload_path)) {
            unlink($upload_path);
        }
        
        $this->db->trans_rollback();
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(500)
            ->set_output(json_encode([
                'success' => false,
                'message' => 'Failed to save outcome statement to database'
            ]));
    }

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

    // Commit the transaction
    $this->db->trans_complete();

    if ($this->db->trans_status() === FALSE) {
        // Delete uploaded file if transaction fails
        if (file_exists($upload_path)) {
            unlink($upload_path);
        }
        
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(500)
            ->set_output(json_encode([
                'success' => false,
                'message' => 'Transaction failed'
            ]));
    }

    // Prepare response data
    $response_data = [
        'id' => $outcome_statement_id,
        'name' => $statement_name,
        'progress_marker_id' => $progress_marker_id,
        'type' => $file_ext,
        'url' => $file_url,
        'file_size' => $file_size,
        'user_id' => $user_id,
        'year' => $year,
        'description' => $description,
        'comments' => [], // Empty comments array for new statements
        'created_at' => $data['created_at'],
        'updated_at' => $data['updated_at']
    ];

    return $this->output
        ->set_content_type('application/json')
        ->set_status_header(201)
        ->set_output(json_encode([
            'success' => true,
            'message' => 'Outcome statement uploaded successfully',
            'data' => $response_data
        ]));
}

/**
 * Get outcome statements for a specific year and user
 * GET /api/outcome-statements?user_id={user_id}&year={year}
 */
public function get_outcome_statements1()
{
    // Get query parameters
    $user_id = $this->input->get('user_id');
    $year = $this->input->get('year') ?? date('Y'); // Default to current year

    // 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' => 'User ID is required'
            ]));
    }

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

    // Validate year format (4 digits)
    if (!preg_match('/^\d{4}$/', $year)) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400)
            ->set_output(json_encode([
                'success' => false,
                'message' => 'Year must be a 4-digit number'
            ]));
    }

    try {
        // Get outcome statements with their comments
        $this->db->select('os.*, u.first_name, u.last_name, u.image');
        $this->db->from('outcome_statements os');
        $this->db->join('users u', 'os.user_id = u.id', 'left');
        // $this->db->where('os.user_id', $user_id);
        $this->db->where('os.year', $year);
        $this->db->where('os.is_active', 1);
        $this->db->order_by('os.created_at', 'DESC');
        
        $statements = $this->db->get()->result_array();

        // Get comments for each statement
        foreach ($statements as &$statement) {
            $this->db->select('osc.*, u.first_name, u.last_name, u.image');
            $this->db->from('outcome_statement_comments osc');
            $this->db->join('users u', 'osc.user_id = u.id', 'left');
            $this->db->where('osc.outcome_statement_id', $statement['id']);
            $this->db->where('osc.is_active', 1);
            $this->db->order_by('osc.created_at', 'ASC');
            
            $comments = $this->db->get()->result_array();
            
            // Format comments to match frontend structure
            $formatted_comments = [];
            foreach ($comments as $comment) {
                $formatted_comments[] = [
                    'id' => (int)$comment['id'],
                    'body' => $comment['body'],
                    'created_at' => $comment['created_at'],
                    'updated_at' => $comment['updated_at'],
                    'user' => [
                        'id' => (int)$comment['user_id'],
                        'first_name' => $comment['first_name'],
                        'last_name' => $comment['last_name'],
                        'avatar' => $comment['image']
                    ]
                ];
            }
            
            $statement['comments'] = $formatted_comments;
            
            // Clean up statement data
            unset($statement['first_name'], $statement['last_name'], $statement['avatar']);
            $statement['id'] = (string)$statement['id']; // Convert to string to match frontend
            $statement['user_id'] = (int)$statement['user_id'];
            $statement['file_size'] = (int)$statement['file_size'];
        }

        // Format response to match frontend expectation
        $response_data = [
            'statements' => $statements
        ];

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

    } catch (Exception $e) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(500)
            ->set_output(json_encode([
                'success' => false,
                'message' => 'Failed to fetch outcome statements: ' . $e->getMessage()
            ]));
    }
}

public function get_outcome_statements()
{
    // Get query parameters
    $user_id = $this->input->get('user_id');
    $year = $this->input->get('year') ?? date('Y'); // Default to current year

    // 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' => 'User ID is required'
            ]));
    }

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

    // Validate year format (4 digits)
    if (!preg_match('/^\d{4}$/', $year)) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400)
            ->set_output(json_encode([
                'success' => false,
                'message' => 'Year must be a 4-digit number'
            ]));
    }

    try {
        // Get outcome statements with their comments and progress markers
        $this->db->select('os.*, u.first_name, u.last_name, u.image, pm.id as pm_id, pm.level, pm.year as pm_year, pm.annual_progress_markers, pm.country_specific_indicators, pm.thematic_basket_indicators');
        $this->db->from('outcome_statements os');
        $this->db->join('users u', 'os.user_id = u.id', 'left');
        $this->db->join('progress_markers pm', 'os.progress_marker_id = pm.id', 'left');
        // $this->db->where('os.user_id', $user_id);
        $this->db->where('os.year', $year);
        $this->db->where('os.is_active', 1);
        $this->db->order_by('os.created_at', 'DESC');
        
        $statements = $this->db->get()->result_array();

        // Get comments for each statement
        foreach ($statements as &$statement) {
            $this->db->select('osc.*, u.first_name, u.last_name, u.image');
            $this->db->from('outcome_statement_comments osc');
            $this->db->join('users u', 'osc.user_id = u.id', 'left');
            $this->db->where('osc.outcome_statement_id', $statement['id']);
            $this->db->where('osc.is_active', 1);
            $this->db->order_by('osc.created_at', 'ASC');
            
            $comments = $this->db->get()->result_array();
            
            // Format comments to match frontend structure
            $formatted_comments = [];
            foreach ($comments as $comment) {
                $formatted_comments[] = [
                    'id' => (int)$comment['id'],
                    'body' => $comment['body'],
                    'created_at' => $comment['created_at'],
                    'updated_at' => $comment['updated_at'],
                    'user' => [
                        'id' => (int)$comment['user_id'],
                        'first_name' => $comment['first_name'],
                        'last_name' => $comment['last_name'],
                        'avatar' => $comment['image']
                    ]
                ];
            }
            
            $statement['comments'] = $formatted_comments;
            
            // Add progress marker information if available
            if (!empty($statement['progress_marker_id']) && !empty($statement['pm_id'])) {
                $statement['progress_marker'] = [
                    'id' => (int)$statement['pm_id'],
                    'level' => $statement['level'],
                    'year' => $statement['pm_year'],
                    'annualProgressMarkers' => $statement['annual_progress_markers'],
                    'countrySpecificIndicators' => $statement['country_specific_indicators'],
                    'thematicBasketIndicators' => $statement['thematic_basket_indicators']
                ];
            }
            
            // Clean up statement data
            unset($statement['first_name'], $statement['last_name'], $statement['avatar'], 
                  $statement['pm_id'], $statement['level'], $statement['pm_year'], 
                  $statement['annual_progress_markers'], $statement['thematic_basket_indicators'], 
                  $statement['thematic_basket_indicators']);
            $statement['id'] = (string)$statement['id']; // Convert to string to match frontend
            $statement['user_id'] = (int)$statement['user_id'];
            $statement['file_size'] = (int)$statement['file_size'];
            $statement['progress_marker_id'] = !empty($statement['progress_marker_id']) ? (int)$statement['progress_marker_id'] : null;
        }

        // Format response to match frontend expectation
        $response_data = [
            'statements' => $statements
        ];

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

    } catch (Exception $e) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(500)
            ->set_output(json_encode([
                'success' => false,
                'message' => 'Failed to fetch outcome statements: ' . $e->getMessage()
            ]));
    }
}

/**
 * Update an existing outcome statement
 * PUT /api/outcome-statements/{id}
 */
public function edit_outcome_statement()
{
    // Get form data from JSON input
    $json_data = json_decode(@file_get_contents('php://input'), true);
    $outcome_statement_id = $json_data['id'];
    $name = $json_data['name'];
    $description = $json_data['description'];
    $year = $json_data['year'];
    $user_id = $json_data['user_id'];
    $progress_marker_id = $json_data['progress_marker_id'];

    // Validate required fields
    if (empty($user_id) || empty($outcome_statement_id)) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400)
            ->set_output(json_encode([
                'success' => false,
                'message' => 'User ID and Outcome Statement ID are required'
            ]));
    }

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

    // Validate outcome statement exists and belongs to user
    $this->db->where('id', $outcome_statement_id);
    // $this->db->where('user_id', $user_id);
    $this->db->where('is_active', 1);
    $existing_statement = $this->db->get('outcome_statements')->row_array();

    if (empty($existing_statement)) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(404)
            ->set_output(json_encode([
                'success' => false,
                'message' => 'Outcome statement not found or you do not have permission to update it'
            ]));
    }

    // Validate year format if provided
    if (!empty($year) && !preg_match('/^\d{4}$/', $year)) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400)
            ->set_output(json_encode([
                'success' => false,
                'message' => 'Year must be a 4-digit number'
            ]));
    }

    // Prepare data for update
    $data = [
        'updated_at' => date('Y-m-d H:i:s')
    ];

    // Update fields only if provided
    if (!empty($name)) {
        $data['name'] = $name;
    }
    if (!empty($description)) {
        $data['description'] = $description;
    }
    if (!empty($year)) {
        $data['year'] = $year;
    }
    
    // Update progress_marker_id (allow null to remove association)
    if (isset($progress_marker_id)) {
        $data['progress_marker_id'] = !empty($progress_marker_id) ? $progress_marker_id : null;
    }


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

    // Update the outcome statement
    $this->db->where('id', $outcome_statement_id);
    $update = $this->db->update('outcome_statements', $data);

    if (!$update) {
        $this->db->trans_rollback();
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(500)
            ->set_output(json_encode([
                'success' => false,
                'message' => 'Failed to update outcome statement'
            ]));
    }

    // Commit the transaction
    $this->db->trans_complete();

    if ($this->db->trans_status() === FALSE) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(500)
            ->set_output(json_encode([
                'success' => false,
                'message' => 'Transaction failed'
            ]));
    }

    // Get updated statement data
    $this->db->where('id', $outcome_statement_id);
    $updated_statement = $this->db->get('outcome_statements')->row_array();

    return $this->output
        ->set_content_type('application/json')
        ->set_status_header(200)
        ->set_output(json_encode([
            'success' => true,
            'message' => 'Outcome statement updated successfully',
            'data' => $updated_statement
        ]));
}

/**
 * Delete (soft delete) an outcome statement
 * DELETE /api/outcome-statements/{id}
 */
public function delete_outcome_statement()
{
    // Get form data from JSON input
    $json_data = json_decode(@file_get_contents('php://input'), true);
    $outcome_statement_id = $json_data['id'];
    $user_id = $json_data['user_id'];

    // Validate required fields
    if (empty($user_id) || empty($outcome_statement_id)) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400)
            ->set_output(json_encode([
                'success' => false,
                'message' => 'User ID and Outcome Statement ID are required'
            ]));
    }

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

    // Validate outcome statement exists and belongs to user
    $this->db->where('id', $outcome_statement_id);
    $this->db->where('user_id', $user_id);
    $this->db->where('is_active', 1);
    $existing_statement = $this->db->get('outcome_statements')->row_array();

    if (empty($existing_statement)) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(404)
            ->set_output(json_encode([
                'success' => false,
                'message' => 'Outcome statement not found or you do not have permission to delete it'
            ]));
    }

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

    // Soft delete the outcome statement
    $this->db->where('id', $outcome_statement_id);
    $delete = $this->db->update('outcome_statements', [
        'is_active' => 0,
        'updated_at' => date('Y-m-d H:i:s')
    ]);

    if (!$delete) {
        $this->db->trans_rollback();
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(500)
            ->set_output(json_encode([
                'success' => false,
                'message' => 'Failed to delete outcome statement'
            ]));
    }

    // Also soft delete associated comments
    $this->db->where('outcome_statement_id', $outcome_statement_id);
    $this->db->update('outcome_statement_comments', [
        'is_active' => 0,
        'updated_at' => date('Y-m-d H:i:s')
    ]);

    // Commit the transaction
    $this->db->trans_complete();

    if ($this->db->trans_status() === FALSE) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(500)
            ->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' => 'Outcome statement deleted successfully'
        ]));
}

/**
 * Add a comment to an outcome statement
 * POST /api/outcome-statements/{id}/comments
 */
public function add_outcome_statement_comment()
{
    // Get form data from JSON input
    $json_data = json_decode(@file_get_contents('php://input'), true);
    $outcome_statement_id = $json_data['outcome_statement_id'];
    $body = $json_data['body'];
    $user_id = $json_data['user_id'];

    // Validate required fields
    if (empty($user_id) || empty($outcome_statement_id) || empty($body)) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400)
            ->set_output(json_encode([
                'success' => false,
                'message' => 'User ID, Outcome Statement ID, and comment body are required'
            ]));
    }

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

    // Validate outcome statement exists
    $this->db->where('id', $outcome_statement_id);
    $this->db->where('is_active', 1);
    $statement_exists = $this->db->get('outcome_statements')->num_rows() > 0;

    if (!$statement_exists) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(404)
            ->set_output(json_encode([
                'success' => false,
                'message' => 'Outcome statement not found'
            ]));
    }

    // Prepare data for insertion
    $data = [
        'outcome_statement_id' => $outcome_statement_id,
        'user_id' => $user_id,
        'body' => $body,
        'is_active' => 1,
        'created_at' => date('Y-m-d H:i:s'),
        'updated_at' => date('Y-m-d H:i:s')
    ];

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

    // Insert the comment
    $insert = $this->db->insert('outcome_statement_comments', $data);
    if (!$insert) {
        $this->db->trans_rollback();
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(500)
            ->set_output(json_encode([
                'success' => false,
                'message' => 'Failed to add comment'
            ]));
    }

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

    // Commit the transaction
    $this->db->trans_complete();

    if ($this->db->trans_status() === FALSE) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(500)
            ->set_output(json_encode([
                'success' => false,
                'message' => 'Transaction failed'
            ]));
    }

    // Get user details for response
    $this->db->where('id', $user_id);
    $user = $this->db->get('users')->row_array();

    // Prepare response data
    $response_data = [
        'id' => $comment_id,
        'body' => $body,
        'created_at' => $data['created_at'],
        'updated_at' => $data['updated_at'],
        'user' => [
            'id' => (int)$user['id'],
            'first_name' => $user['first_name'],
            'last_name' => $user['last_name'],
            'avatar' => $user['image']
        ]
    ];

    return $this->output
        ->set_content_type('application/json')
        ->set_status_header(201)
        ->set_output(json_encode([
            'success' => true,
            'message' => 'Comment added successfully',
            'data' => $response_data
        ]));
        
        
}

public function update_outcome_statement_comment()
{
    // Get form data from JSON input
    $json_data = json_decode(@file_get_contents('php://input'), true);
    $comment_id = $json_data['id'];
    $body = $json_data['body'];
    $user_id = $json_data['user_id'];

    // Validate required fields
    if (empty($user_id) || empty($comment_id) || empty($body)) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(400)
            ->set_output(json_encode([
                'success' => false,
                'message' => 'User ID, Comment ID, and comment body are required'
            ]));
    }

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

    // Validate comment exists and belongs to user
    $this->db->where('id', $comment_id);
    $this->db->where('user_id', $user_id);
    $this->db->where('is_active', 1);
    $existing_comment = $this->db->get('outcome_statement_comments')->row_array();

    if (empty($existing_comment)) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(404)
            ->set_output(json_encode([
                'success' => false,
                'message' => 'Comment not found or you do not have permission to update it'
            ]));
    }

    // Prepare data for update
    $data = [
        'body' => $body,
        'updated_at' => date('Y-m-d H:i:s')
    ];

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

    // Update the comment
    $this->db->where('id', $comment_id);
    $update = $this->db->update('outcome_statement_comments', $data);

    if (!$update) {
        $this->db->trans_rollback();
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(500)
            ->set_output(json_encode([
                'success' => false,
                'message' => 'Failed to update comment'
            ]));
    }

    // Commit the transaction
    $this->db->trans_complete();

    if ($this->db->trans_status() === FALSE) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(500)
            ->set_output(json_encode([
                'success' => false,
                'message' => 'Transaction failed'
            ]));
    }

    // Get user details for response
    $this->db->where('id', $user_id);
    $user = $this->db->get('users')->row_array();

    // Prepare response data
    $response_data = [
        'id' => (int)$comment_id,
        'body' => $body,
        'created_at' => $existing_comment['created_at'],
        'updated_at' => $data['updated_at'],
        'user' => [
            'id' => (int)$user['id'],
            'first_name' => $user['first_name'],
            'last_name' => $user['last_name'],
            'avatar' => $user['avatar']
        ]
    ];

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

/**
 * Delete (soft delete) an outcome statement comment
 * DELETE /api/outcome-statements/comments/{id}
 */
public function delete_outcome_statement_comment()
{
    // Get form data from JSON input
    $json_data = json_decode(@file_get_contents('php://input'), true);
    $comment_id = $json_data['id'];
    $user_id = $json_data['user_id'];

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

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

    // Validate comment exists and belongs to user
    $this->db->where('id', $comment_id);
    $this->db->where('user_id', $user_id);
    $this->db->where('is_active', 1);
    $existing_comment = $this->db->get('outcome_statement_comments')->row_array();

    if (empty($existing_comment)) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(404)
            ->set_output(json_encode([
                'success' => false,
                'message' => 'Comment not found or you do not have permission to delete it'
            ]));
    }

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

    // Soft delete the comment
    $this->db->where('id', $comment_id);
    $delete = $this->db->update('outcome_statement_comments', [
        'is_active' => 0,
        'updated_at' => date('Y-m-d H:i:s')
    ]);

    if (!$delete) {
        $this->db->trans_rollback();
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(500)
            ->set_output(json_encode([
                'success' => false,
                'message' => 'Failed to delete comment'
            ]));
    }

    // Commit the transaction
    $this->db->trans_complete();

    if ($this->db->trans_status() === FALSE) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(500)
            ->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' => 'Comment deleted successfully'
        ]));
}


}