<?php
defined('BASEPATH') or exit('No direct script access allowed');
class User 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');
        $method = $_SERVER['REQUEST_METHOD'];
        if ($method == "OPTIONS") {
            die();
        }

        $this->load->helper('form');
        $this->load->helper(['jwt', 'authorization']);
        // $this->db->query("SET time_zone = '+03:00'");
       
    }

    

    public function verify_token()
    {

        $headers = $this->input->request_headers();
        // Extract the token
        $token = $headers['Authorization'];

        try {
            // Validate the token
            // Successfull validation will return the decoded user data else returns false
            $data = AUTHORIZATION::validateTimestamp($token);
            if ($data === false) {

                print "not valid token";
                exit();
            } else {
                print_r($data);
            }
        } catch (Exception $e) {
            // Token is invalid
            // Send the unathorized access message
            print "unthorized access message";
        }
    }
    
   
    
    
    // public function send_sms($users){
    public function send_sms(){    
        // function to send sms
        // after success save the sent sms in the sent sms table
        // indicating the body
        
        $users = array(
           
          [
        'phone'=>'256703657397',
        'surname'=>'Kimbowa',
        'firstname'=>'Andrew',
        'student_number'=>'110002'
        ],
          [
        'phone'=>'256702196808',
        'surname'=>'Luwaga',
        'firstname'=>'Innocent',
        'student_number'=>'110003'
        ],
        
      
        );
        
        foreach($users as $user ){
        
        $post = [
            'action'=> "send-sms",
        'api_key'=>"YWRtaW46YWRtaW4ucGFzc3dvcmQ=",
        'to'=>$user['phone'],
        'from'=>"BUDDOSS",
        'sms'=>"Dear Parent, we've added more content on www.elearning.buddoss.com; SIGNUP now to keep learning with us. Keep your EMAIL & PASSWORD to Login at any time. Thanks"
        ];
        
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL,'https://greenmondayinc.org/apps/sms/sms/api');
  
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
  $response = curl_exec($ch);
  $result = json_decode($response);
  curl_close($ch); // Close the connection
  
  if($result->message =='Successfully Send'){
      // store the details
      $data = array(
     'firstname'=>$user['firstname'],
      'surname'=>$user['surname'],
      'phone'=>$user['phone'],
      'student_number'=>$user['student_number'],
      'date_sent'=>time()
      
      );
      
      $this->db->insert('buddoss_sent_sms', $data);
      
  }
 
 }
              return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(array(
                    'success' => true,
                    'message' => $result,
                    
                )));
    }
    
    public function send_sms_test(){
         
        $post = [
            'action'=> "send-sms",
        'api_key'=>"YWRtaW46YWRtaW4ucGFzc3dvcmQ=",
        'to'=>'256703657397',
        'from'=>"BUDDOSS",
        'sms'=>"Dear Parent, we've added more content on www.elearning.buddoss.com; SIGNUP now to keep learning with us. Keep your EMAIL & PASSWORD to Login at any time. Thanks"
        ];
        
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL,'https://greenmondayinc.org/apps/sms/sms/api');
  
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
  $response = curl_exec($ch);
  $result = json_decode($response);
  curl_close($ch); // Close the connection
  if($result->message =='Successfully Send'){
   return $this->output
  
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(array(
                    'success' => true,
                    'response' => $result,
                    
                )));
  
    }
    }
    
    public function phone_update($student_number,$phone){
        
        if(strlen($phone)==11){
         
          $new_number ='256'. substr($phone,strpos($phone,'7'));
          // update table with new number
          $this->db->where('student_number',$student_number);
          $this->db->set('phone',$new_number);
          if($this->db->update('buddoss_students')){
             return true; 
          }else{
              return false;
          }
          
     }
    }
    
    public function register_user()
    {

        // $json_data = json_decode(@file_get_contents('php://input'), true);


        // To be used later in the new API update


        $options = [ 'cost' => 12, ];
       

        // check if email exists first
        


        // $email = $json_data['email'];
        $email = $_POST['email'];
        // $check_email =  $result = $this->db->query('SELECT * FROM user WHERE email = "' . $email . '"  ');
        // $check_phone = $result1 = $this->db->query('SELECT * FROM user WHERE phone_no = "' . $phone . '"  ');

        $check_email =   $this->db->get_where('users', array("email" => $email))->row();
        
    
        
        if (($check_email != null)) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => "ACCOUNT_EXISTS",
                    
                )));
            
        } else {


        // check if the user uploaded a photo
         if (empty($_FILES['image']['name'])) {
             return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => "PLEASE_UPLOAD_USER_PHOTO",
                    
                )));
         }

             $image_url =  $this->upload_image($_FILES["image"]['name'], "image","users");


            // $verificaton_code = date('his');
            $user_info = array(

                'first_name' => $_POST['first_name'],
                'last_name' => $_POST['last_name'],
                'date_of_birth' => $_POST['date_of_birth'],
                'email' => $_POST['email'],
                'role' => $_POST['role'],
                'system_role' => $_POST['system_role'],
                'country_id' => $_POST['country_id'],
                'image'=>$image_url,
                'phone' => $_POST['phone'],
                'salutation' => $_POST['salutation'],
                'main_office'=>$_POST['main_office'],
                // 'programmes'=>$_POST['programmes'],
                'gender' => $_POST['gender'],
                'description'=>$_POST['description'],
                'password' =>password_hash( $_POST['password'], PASSWORD_BCRYPT, $options ),
                'created_at' => date('Y-m-d\TH:i:s.u\Z')

            );


            if ($this->db->insert('users', $user_info)) {
          

                //  $user_info+=["id"=>$this->db->insert_id()];
    
        // Set HTTP status code
        
        //user subjects
       
            //     // send email with verification code from here.
            //   $config = array(
            //         'protocol' => 'sendmail',
            //         'smtp_host' => 'evrythingirly.com',
            //         'smtp_keepalive'=>TRUE,
            //         'smtp_port' => 656,
            //         'validate'=>FALSE,
            //         'smtp_user' => 'no-reply@evrythingirly.com',
            //         'smtp_pass' => 'noreply@evrythingirly',
            //         'mailtype' => 'html',
            //         'charset' => 'iso-8859-1'
            //     );
                
            //     $this->load->library('email');
            //     $this->email->set_header('Content-Type', 'text/html');
            //     $this->email->from('no-reply@evrythingirly.com', 'Evrythingirly');
            //     $this->email->to($json_data['email']);


            //     $message = "
            //   <html>
            //      <head>
            //       <title>Evrythingirly</title>
            //      </head>
            //      <body>
            //       <p>Hello,</p>
            //       <p> An account has been created successfully</p>
                   
            //       <p>Here is the verification code required to verify that this is a valid email address.</p>

            //       <h1>$verificaton_code</h1>
                   
                   
            //       <p>Thank you.</p>
            //       <p>Regards</p>
            //       <p>Evrythingirly</p>
                    
            //      </body>
            //   </html>";


            //     $this->email->subject('Account Verification Code');
            //     $this->email->message($message);
               
                 
            //   if ($this->email->send()) {
            
            //   }else{
                   
            //      return $this->output
            //         ->set_content_type('application/json')
            //         ->set_status_header(200)
            //         ->set_output(json_encode(array(
            //             'success' => false,
            //             'message' => 'Account not created'
            //         )));  
                   
            //   }
            
             return $this->output
                        ->set_content_type('application/json')
                        ->set_status_header(200)
                        ->set_output(json_encode(array(
                            'success' => true,
                            'message' => 'ACCOUNT_CREATED_SUCCESSFULLY'

                        )));
                
            } else {
                    $db_error = $this->db->error();

                return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(200)
                    ->set_output(json_encode(array(
                        'success' => false,
                        'message' => 'Account not created',
                         'error_code' => $db_error['code'],
            'error_message' => $db_error['message'],
            'last_query' => $this->db->last_query()
                    )));
            }
        }
    }
    
     // function to upload images
    public function upload_image($image_name, $field_name,$directory)
    {

        $config['upload_path'] = "./$directory/";
        $config['allowed_types'] = '*';
        $new_name = time() . '-' . $image_name;
        $config['file_name'] = $new_name;

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

        if (!$this->upload->do_upload($field_name) && !empty($image_name)) {
            $error = array('error' => $this->upload->display_errors());
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode($error));
        }


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

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

//  public function get_users() {
//     // Select all columns except 'password'
//   $this->db->select("id, first_name, last_name, country, image, role,system_role email, is_active, programmes,main_office,date_of_birth,created_at");

//     $users = $this->db->from("users")->get()->result_array();

//     return $this->output
//         ->set_content_type('application/json')
//         ->set_status_header(200)
//         ->set_output(json_encode(array(
//             'success' => true,
//             'message' => "FETCHED_SUCCESSFULLY",
//             'count' => count($users),
//             'users' => array_reverse($users)
//         )));
// }

    public function edit_user($user_id){
        
        $json_data = json_decode(@file_get_contents('php://input'), true);


        // To be used later in the new API update


        $options = [ 'cost' => 12, ];
       

        // check if email exists first
        


        // $email = $json_data['email'];
        $email = $_POST['email'];
        // $check_email =  $result = $this->db->query('SELECT * FROM user WHERE email = "' . $email . '"  ');
        // $check_phone = $result1 = $this->db->query('SELECT * FROM user WHERE phone_no = "' . $phone . '"  ');

        $user =   $this->db->get_where('users', array("id" => $user_id))->row();
        
    
        
        if (($user == null)) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(array(
                    'success' => false,
                    'error' => "USER_NOT_FOUND",
                    
                )));
            
        } else {
            
            
             // $verificaton_code = date('his');
            $user_info = array(

                'first_name' => $_POST['first_name'],
                'last_name' => $_POST['last_name'],
               
'date_of_birth' => DateTime::createFromFormat('d/m/Y', $_POST['date_of_birth'])->format('Y-m-d'),
'email' => $_POST['email'],
                'role' => $_POST['role'],
                'country' => $_POST['country'],
                'phone' => $_POST['phone'],
                'salutation' => $_POST['salutation'],
                'gender' => $_POST['gender'],
                'description'=>$_POST['description'],
                'updated_at' => date('Y-m-d\TH:i:s.u\Z')

            );
            // if user submits a image
           if (!empty($_FILES['image']['name'])) {
               $image_url =  $this->upload_image($_FILES["image"]['name'], "image","users");
               
               $user_info['image']= $image_url;
               
           }
           


           

               $this->db->where("id",$user_id);
            if ($this->db->update('users', $user_info)) {
          

             return $this->output
                        ->set_content_type('application/json')
                        ->set_status_header(200)
                        ->set_output(json_encode(array(
                            'success' => true,
                            'message' => 'USER_EDITED_SUCCESSFULLY'

                        )));
                
            } else {

                return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(200)
                    ->set_output(json_encode(array(
                        'success' => false,
                        'message' => 'USER_NOT_EDITED'
                    )));
            }
        }
        
    }
    
    public function delete_user($user_id){
         $check_user = $this->db->get_where("users",array("id"=>$user_id))->row();
        if($check_user==null){
             return $this->output
                        ->set_content_type('application/json')
                        ->set_status_header(200)
                        ->set_output(json_encode(array(
                            'success' => false,
                            'message' => 'USER_NOT_FOUND',

                        )));
        }
        $this->db->where("id",$user_id);
        if($this->db->delete("users")){
             return $this->output
                        ->set_content_type('application/json')
                        ->set_status_header(200)
                        ->set_output(json_encode(array(
                            'success' => true,
                            'message' => 'USER_DELETED_SUCCESSFULLY',

                        )));
        }
        
    }
    
    public function register_user1()
    {

        $json_data = json_decode(@file_get_contents('php://input'), true);


        // To be used later in the new API update


        $options = [ 'cost' => 12, ];
       

        // check if email exists first
        


        // $email = $json_data['email'];
        $email = $json_data['email'];
        // $check_email =  $result = $this->db->query('SELECT * FROM user WHERE email = "' . $email . '"  ');
        // $check_phone = $result1 = $this->db->query('SELECT * FROM user WHERE phone_no = "' . $phone . '"  ');

        $check_email =   $this->db->get_where('users', array("email" => $email))->row();
        
        if (($check_email != null)) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(array(
                    'success' => false,
                    'error' => "An account with $email exists, please use another",
                    
                )));
            
        } else {



            $verificaton_code = date('his');
            $user_info = array(

                'lastname' => $json_data['lastname'],
                'firstname' => $json_data['firstname'],
                'email' => $json_data['email'],
                'password' =>password_hash( $json_data['password'], PASSWORD_BCRYPT, $options ),
                'date_joined' => time(),
                'verification_code' => $verificaton_code,
                // 'account_verified' => 0

            );


            if ($this->db->insert('users', $user_info)) {
          

                 $user_info+=["id"=>$this->db->insert_id()];
        $token = AUTHORIZATION::generateToken(['timestamp'=>time(),'data'=>$user_info]);
        // Set HTTP status code
        
        //user subjects
       
                // send email with verification code from here.
               $config = array(
                    'protocol' => 'sendmail',
                    'smtp_host' => 'evrythingirly.com',
                    'smtp_keepalive'=>TRUE,
                    'smtp_port' => 656,
                    'validate'=>FALSE,
                    'smtp_user' => 'no-reply@evrythingirly.com',
                    'smtp_pass' => 'noreply@evrythingirly',
                    'mailtype' => 'html',
                    'charset' => 'iso-8859-1'
                );
                
                $this->load->library('email');
                $this->email->set_header('Content-Type', 'text/html');
                $this->email->from('no-reply@evrythingirly.com', 'Evrythingirly');
                $this->email->to($json_data['email']);


                $message = "
               <html>
                 <head>
                   <title>Evrythingirly</title>
                 </head>
                 <body>
                   <p>Hello,</p>
                   <p> An account has been created successfully</p>
                   
                   <p>Here is the verification code required to verify that this is a valid email address.</p>

                   <h1>$verificaton_code</h1>
                   
                   
                   <p>Thank you.</p>
                   <p>Regards</p>
                   <p>Evrythingirly</p>
                    
                 </body>
               </html>";


                $this->email->subject('Account Verification Code');
                $this->email->message($message);
               
                 
               if ($this->email->send()) {
             return $this->output
                        ->set_content_type('application/json')
                        ->set_status_header(200)
                        ->set_output(json_encode(array(
                            'success' => true,
                            'id'=>$this->db->insert_id(),
                            'message' => 'account created successfully',
                            'lastname'=>$json_data['lastname'],
                            'firstname'=>$json_data['firstname'],
                             'date_joined'=>$user_info['date_joined'],
                            'email'=>$json_data['email'],
                      
                         
                            'token'=>$token

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

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

    public function verify_account()
    {
        // use the email, and the verification sent along
        // verify the user's account
        $json_data = json_decode(@file_get_contents('php://input'), true);

        $result =  $this->db->get_where('users', array('email' => $json_data['email'],  'verification_code' => $json_data['verification_code']))->row();

        if ($result == null) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => 'wrong verification code'
                )));
        } else {
            $this->db->where('email', $json_data['email']);
            $this->db->set('account_verified', 1);
            if ($this->db->update('users')) {
                return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(200)
                    ->set_output(json_encode(array(
                        'success' => true,
                        'message' => 'Account verified successfully'
                    )));
            } else {
                return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(200)
                    ->set_output(json_encode(array(
                        'success' => false,
                        'message' => 'verification failed'
                    )));
            }
        }
    }

    public function forgot_password()
    {
        // send a verification code
        // to the email sent along
        $json_data = json_decode(@file_get_contents('php://input'), true);

        $result =  $this->db->get_where('users', array('email' => $json_data['email']))->row();

        if ($result == null) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => 'No account found for this email address'
                )));
        } else {
          
            // generate a password reset code
            // send the code to the user email sent along
            // store the password reset code in the user table
            $reset_code = date('his');
            $this->db->where('email', $json_data['email']);
            $this->db->set('password_reset_code', $reset_code);
            if ($this->db->update('users')) {
                // email the code here
                
                
                    
                $config = array(
                    'protocol' => 'sendmail',
                    'smtp_host' => 'evrythingirly.com',
                    'smtp_keepalive'=>TRUE,
                    'smtp_port' => 656,
                    'validate'=>FALSE,
                    'smtp_user' => 'no-reply@evrythingirly.com',
                    'smtp_pass' => 'noreply@evrythingirly',
                    'mailtype' => 'html',
                    'charset' => 'iso-8859-1'
                );
                
                $this->load->library('email');
                // prepare email
// $this->email
//     ->from('no-reply@evrythingirly.com', 'Example Inc.')
//     ->to($json_data['email'])
//     ->subject('Hello from Example Inc.')
//     ->message('Hello, We are <strong>Example Inc.</strong>')
//     ->set_mailtype('html');

// send email
// $this->email->send();

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

                $this->email->set_header('Content-Type', 'text/html');
                $this->email->from('no-reply@evrythingirly.com', 'Evrythingirly');
                $this->email->to($json_data['email']);


                $message = "
              <html>
                 <head>
                  <title>Evrythingirly</title>
                 </head>
                 <body>
                  <p>Hello,</p>
                  <p>We forget sometimes!</p>
                   
                  <p>Here is the password reset code required to reset your password and also verify that this is your email address.</p>

                  <h1>$reset_code</h1>
                   
                   
                  <p>Thank you.</p>
                  <p>Regards</p>
                  <p>Evrythingirly</p>
                    
                 </body>
              </html>";


                $this->email->subject('Password Reset Code');
                $this->email->message($message);
                if ($this->email->send()) {

                    return $this->output
                        ->set_content_type('application/json')
                        ->set_status_header(200)
                        ->set_output(json_encode(array(
                            'success' => true,
                            'message' => 'password reset code sent successfully'
                        )));
                } else {
                    return $this->output
                        ->set_content_type('application/json')
                        ->set_status_header(200)
                        ->set_output(json_encode(array(
                            'success' => false,
                            'message' => 'password reset code not sent successfully'
                        )));
                }
            }
    }
    }
    

    public function reset_password()
    {
        // use the email and update password of the user
        $json_data = json_decode(@file_get_contents('php://input'), true);

        $result =  $this->db->get_where('users', array('email' => $json_data['email'], 'password_reset_code' => $json_data['password_reset_code']))->row();

        if ($result == null) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => 'wrong password reset code'
                )));
        } else {
            $options = [ 'cost' => 12, ];
            $this->db->where('email', $json_data['email']);
            
            $this->db->set('password', password_hash( $json_data['new_password'], PASSWORD_BCRYPT, $options ));
            if ($this->db->update('users')) {
                
                return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(200)
                    ->set_output(json_encode(array(
                        'success' => true,
                        'message' => 'password reset successfully'
                    )));
            } else {
                return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(200)
                    ->set_output(json_encode(array(
                        'success' => false,
                        'message' => 'password reset failed'
                    )));
            }
        }
    }
    // check email

    public function check_email()
    {
        // check if a username exists
        $json_data = json_decode(@file_get_contents('php://input'), true);
        $email = $json_data['email'];
        $check_email =  $this->db->query('SELECT * FROM user WHERE email = "' . $email . '"  ');
        if ($check_email->num_rows() > 0) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(array(
                    'emailNotTaken' => false
                )));
        } else {

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

                    'emailNotTaken' => true
                )));
        }
    }

    public function check_username()
    {
        // check if a username exists
        $json_data = json_decode(@file_get_contents('php://input'), true);
        $username = $json_data['username'];
        $check_username =  $result = $this->db->query('SELECT * FROM user WHERE username = "' . $username . '"  ');
        if ($check_username->num_rows() > 0) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => 'username exists '
                )));
        } else {

            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(array(
                    'success' => true,
                    'message' => "username doesn't exists "
                )));
        }
    }


//   public function login()
//     {

//         $json_data = json_decode(@file_get_contents('php://input'), true);
//         $email = $json_data['username'];
//         $password = $json_data['password'];

//         // check if email exists first

        
//         $check_email =  $result = $this->db->query('SELECT * FROM users WHERE email = "' . $email . '"  ');

//         if ($check_email->num_rows() == 0) {
//             return $this->output
//                 ->set_content_type('application/json')
//                 ->set_status_header(200)
//                 ->set_output(json_encode(array(
//                     'success' => false,
//                     'message' => "USER_NOT_FOUND"
//                 )));
//         } else {

//             // if we have an email
            
           
//             $user =  $this->db->get_where('users', array('email' => $email))->row();
            
            
                
        
//             // if (trim($password)==trim($user->password)) {
//                 if (password_verify(trim($password), $user->password)) {
//                 $token = AUTHORIZATION::generateToken(['timestamp'=>time(),'data'=>$user]);
//                 // update the last_login_ip and last_login_at
//                 $this->db->where('email', $email);
//                 $this->db->set('last_login_ip', $_SERVER['REMOTE_ADDR']);
//                 // replace time with date('Y-m-d\TH:i:s.u\Z')
//                 $this->db->set('last_login_at', time());
//                 // check if user is logging in for the first time
//                 if($user->is_first_time_login==1){
//                     $this->db->set('is_first_time_login',0);
//                 }
//                 $this->db->update('users');
                    
//                 return $this->output
//                     ->set_content_type('application/json')
//                     ->set_status_header(200)
//                     ->set_output(json_encode(array(
//                         'success' => true,
//                         'is_first_time_login'=>$user->is_first_time_login,
//                         'token'=>$token,
//                         'message' => 'LOGIN_SUCCESSFUL'
//                     )));
//             } else {
//                 return $this->output
//                     ->set_content_type('application/json')
//                     ->set_status_header(200)
//                     ->set_output(json_encode(array(
//                         'success' => false,
//                         'message' => 'WRONG_PASSWORD'
//                     )));
//             }
//         }
//     }
    
    
    public function login()
{
    // Get form data from JSON input
    $json_data = json_decode(@file_get_contents('php://input'), true);
    $email = $json_data['username'];
    $password = $json_data['password'];

    // Check if email exists
    $this->db->where('email', $email);
    $check_email = $this->db->get('users');

    if ($check_email->num_rows() == 0) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(200)
            ->set_output(json_encode(array(
                'success' => false,
                'message' => "USER_NOT_FOUND"
            )));
    } else {
        // Retrieve user with country information
        $this->db->select('u.*, c.code as country_code, c.name as country'); // Include country details
        $this->db->from('users u');
        $this->db->join('countries c', 'u.country_id = c.id', 'left'); // Left join in case country_id is NULL
        $this->db->where('u.email', $email);
        $user = $this->db->get()->row();

        // Verify password
        if (password_verify(trim($password), $user->password)) {
             // Force user ID 28(Wilber) to be a short term expert
            // if ((string)$user->id === '28') {
            //     $user->isShortTermExpert = '0';
            // }
            $token = AUTHORIZATION::generateToken(['timestamp' => time(), 'data' => $user]);

            // Update the last_login_ip and last_login_at
            $this->db->where('email', $email);
            $this->db->set('last_login_ip', $_SERVER['REMOTE_ADDR']);
            $this->db->set('last_login_at', date('Y-m-d\TH:i:s.u\Z')); // Updated to use ISO 8601 format as requested
            // Check if user is logging in for the first time
            if ($user->is_first_time_login == 1) {
                $this->db->set('is_first_time_login', 0);
            }
            $this->db->update('users');

            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(array(
                    'success' => true,
                    'is_first_time_login' => $user->is_first_time_login,
                    'token' => $token,
                    'country' => $user->country_code, // Include country code in the response
                    'message' => 'LOGIN_SUCCESSFUL'
                )));
        } else {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => 'WRONG_PASSWORD'
                )));
        }
    }
}

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

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

//     // Get all users, excluding those with "admin" in their role
//     $this->db->select('id, first_name, image as avatar, role'); // Include role for filtering
//     $this->db->where('is_active', 1); // Assuming soft delete with is_active
//     $this->db->where("system_role NOT LIKE '%ADMIN%'", NULL, FALSE); // Exclude roles containing "admin"
//     $users = $this->db->get('users')->result_array();

//     // Prepare the response data
//     $users_data = [];
//     foreach ($users as $user) {
//         $users_data[] = [
//             'id' => (string)$user['id'], // Convert to string to match your response format
//             'first_name' => $user['first_name'],
//             'avatar' => $user['avatar'] ?? '' // Default to empty string if avatar is NULL
//         ];
//     }

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

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

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

    // Get programme code from input (optional)
    $programme_code = $this->input->get('programme');

    // Get country code from input (optional)
    $country_code = $this->input->get('country');

    // Get all users, excluding those with "ADMIN" in their system_role, and optionally filter by programme and/or country
    $this->db->select('u.id, u.first_name, u.image as avatar, u.system_role'); // Include system_role for filtering
    $this->db->where('u.is_active', 1); // Assuming soft delete with is_active
    $this->db->where("u.system_role NOT LIKE '%SUPER_ADMIN%'", NULL, FALSE); // Exclude roles containing "ADMIN"
    

    // Filter by programme if provided (using user_programmes junction table)
    if (!empty($programme_code)) {
        $this->db->join('user_programmes up', 'u.id = up.user_id', 'left');
        $this->db->join('programmes p', 'up.programme_id = p.id', 'left');
        $this->db->where('p.code', $programme_code);
        $this->db->where('p.is_active', 1); // Assuming soft delete with is_active for programmes
    }

    // Filter by country if provided (using country_id in users)
    if (!empty($country_code)) {
        $this->db->join('countries c', 'u.country_id = c.id', 'left');
        $this->db->where('c.code', $country_code);
        $this->db->where('c.is_active', 1); // Assuming soft delete with is_active for countries
    }

    $users = $this->db->get('users u')->result_array();

    // Prepare the response data
    $users_data = [];
    foreach ($users as $user) {
        $users_data[] = [
            'id' => (string)$user['id'], // Convert to string to match your response format
            'first_name' => $user['first_name'],
            'avatar' => $user['avatar'] ?? '' // Default to empty string if avatar is NULL
        ];
    }

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

//this only gets programme users
// public function get_all_users()
// {
//     // Validate user_id (assuming it's passed via GET or session for authentication)
//     $user_id = $this->input->get('user_id') ?? $this->session->userdata('user_id');
//     if (empty($user_id)) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(401) // Unauthorized
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_USER_ID'
//             )));
//     }

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

//     // Get programme code from input (optional)
//     $programme_code = $this->input->get('programme');

//     // Get country code from input (optional)
//     $country_code = $this->input->get('country');

//     // Select user fields
//     $this->db->select('u.id, u.first_name, u.last_name, u.phone, u.system_role, c.name as country, u.salutation, u.main_office, u.description');
//     $this->db->where('u.is_active', 1); // Only active users
//     $this->db->where("u.system_role NOT LIKE '%SUPER_ADMIN%'", NULL, FALSE); // Exclude SUPER_ADMIN roles

//     // Join with countries table for country name
//     $this->db->join('countries c', 'u.country_id = c.id', 'left');
//     $this->db->where('c.is_active', 1); // Only active countries

//     // Filter by programme if provided
//     if (!empty($programme_code)) {
//         $this->db->join('user_programmes up', 'u.id = up.user_id', 'left');
//         $this->db->join('programmes p', 'up.programme_id = p.id', 'left');
//         $this->db->where('p.code', $programme_code);
//         $this->db->where('p.is_active', 1); // Only active programmes
//     }

//     // Filter by country if provided
//     if (!empty($country_code)) {
//         $this->db->where('c.code', $country_code);
//     }

//     // Get users
//     $users = $this->db->get('users u')->result_array();

//     // Prepare response data
//     $users_data = [];
//     foreach ($users as $user) {
//         // Fetch programmes for this user
//         $this->db->select('p.id, p.code');
//         $this->db->join('programmes p', 'up.programme_id = p.id', 'left');
//         $this->db->where('up.user_id', $user['id']);
//         $this->db->where('p.is_active', 1);
//         $programmes = $this->db->get('user_programmes up')->result_array();

//         $users_data[] = [
//             'id' => (string)$user['id'], // Convert to string
//             'first_name' => $user['first_name'] ?? '',
//             'last_name' => $user['last_name'] ?? '',
//             'phone' => $user['phone'] ?? '',
//             'role' => $user['system_role'] ?? '',
//             'country' => $user['country'] ?? '',
//             'salutation' => $user['salutation'] ?? '',
//             'main_office' => $user['main_office'] ?? '',
//             'description' => $user['description'] ?? '',
//             'programmes' => array_map(function($prog) {
//                 return [
//                     'id' => (string)$prog['id'],
//                     'code' => $prog['code']
//                 ];
//             }, $programmes)
//         ];
//     }

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


public function get_all_users()
{
    // Validate user_id (assuming it's passed via GET or session for authentication)
    $user_id = $this->input->get('user_id') ?? $this->session->userdata('user_id');
    if (empty($user_id)) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(401) // Unauthorized
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'INVALID_USER_ID'
            )));
    }

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

    // Get programme code from input (optional)
    $programme_code = $this->input->get('programme');

    // Get country code from input (optional)
    $country_code = $this->input->get('country');

    // Select user fields, including image as avatar and is_active as isActive
    $this->db->select('u.id, u.first_name, u.last_name, u.phone, u.role,  u.email, c.name as country, u.salutation, u.main_office, u.description, u.last_login_at, u.image as avatar, u.is_active as isActive');
    // $this->db->where('u.is_active', 1); // Only active users
    $this->db->where("u.system_role NOT LIKE '%SUPER_ADMIN%'", NULL, FALSE); // Exclude SUPER_ADMIN roles
    //  $this->db->where("u.country_id  LIKE '%6%'", NULL, FALSE);
    //  $this->db->where("u.role NOT LIKE '%finance%'", NULL, FALSE);
    // Join with countries table for country name
    $this->db->join('countries c', 'u.country_id = c.id', 'left');
    $this->db->where('c.is_active', 1); // Only active countries

    // Filter by country if provided
    if (!empty($country_code)) {
        $this->db->where('c.code', $country_code);
    }

    // Get all users
    $users = $this->db->get('users u')->result_array();

    // Prepare response data
    $users_data = [];
    foreach ($users as $user) {
        // Fetch programmes for this user
        $this->db->select('p.id, p.code');
        $this->db->join('programmes p', 'up.programme_id = p.id', 'left'); // Use LEFT JOIN to include users without programmes
        $this->db->where('up.user_id', $user['id']);
        $this->db->where('p.is_active', 1, FALSE); // Only active programmes, allow NULL for users without programmes

        // Apply programme filter if provided
        if (!empty($programme_code)) {
            $this->db->where('p.code', $programme_code);
        }

        $programmes = $this->db->get('user_programmes up')->result_array();

        // Filter out NULL programme rows (from LEFT JOIN)
        $programmes = array_filter($programmes, function($prog) {
            return !is_null($prog['id']) && !is_null($prog['code']);
        });

        $users_data[] = [
            'id' => (string)$user['id'], // Convert to string
            'first_name' => $user['first_name'] ?? '',
            'last_name' => $user['last_name'] ?? '',
            'phone' => $user['phone'] ?? '',
            'email' => $user['email'] ?? '',
            'role' => $user['role'] ?? '',
            'country' => $user['country'] ?? '',
            'salutation' => $user['salutation'] ?? '',
            'main_office' => $user['main_office'] ?? '',
            'description' => $user['description'] ?? '',
            'last_login_at' => $user['last_login_at'] ? date('Y-m-d H:i:s', strtotime($user['last_login_at'])) : '', // Format or empty string
            'avatar' => $user['avatar'] ?? '', // Include avatar, default to empty string if NULL
            'isActive' => (bool)$user['isActive'], // Convert to boolean
            'programmes' => array_map(function($prog) {
                return [
                    'id' => (string)$prog['id'],
                    'code' => $prog['code']
                ];
            }, $programmes)
        ];
    }

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

public function get_all_users_aim()
{
    // Validate user_id (assuming it's passed via GET or session for authentication)
    $user_id = $this->input->get('user_id') ?? $this->session->userdata('user_id');
    if (empty($user_id)) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(401) // Unauthorized
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'INVALID_USER_ID'
            )));
    }

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

    // Get programme code from input (optional)
    $programme_code = $this->input->get('programme');

    // Get country code from input (optional)
    $country_code = $this->input->get('country');

    // Select user fields, including image as avatar and is_active as isActive
    $this->db->select('u.id, u.first_name, u.last_name, u.phone, u.role,  u.email, c.name as country, u.salutation, u.main_office, u.description, u.last_login_at, u.image as avatar, u.is_active as isActive');
    // $this->db->where('u.is_active', 1); // Only active users
    $this->db->where("u.system_role NOT LIKE '%SUPER_ADMIN%'", NULL, FALSE); // Exclude SUPER_ADMIN roles
     $this->db->where("u.country_id  LIKE '%6%'", NULL, FALSE);
     $this->db->where("u.role NOT LIKE '%finance%'", NULL, FALSE);
     $this->db->where("u.role NOT LIKE '%human%'", NULL, FALSE);
     $this->db->where("u.isShortTermExpert NOT LIKE '%finance%'", NULL, FALSE);
    // Join with countries table for country name
    $this->db->join('countries c', 'u.country_id = c.id', 'left');
    $this->db->where('c.is_active', 1); // Only active countries
    $this->db->where('u.isShortTermExpert', 0);
    // $this->db->where('u.id !=', 28);

    // Filter by country if provided
    if (!empty($country_code)) {
        $this->db->where('c.code', $country_code);
    }

    // Get all users
    $users = $this->db->get('users u')->result_array();

    // Prepare response data
    $users_data = [];
    foreach ($users as $user) {
        // Fetch programmes for this user
        $this->db->select('p.id, p.code');
        $this->db->join('programmes p', 'up.programme_id = p.id', 'left'); // Use LEFT JOIN to include users without programmes
        $this->db->where('up.user_id', $user['id']);
        $this->db->where('p.is_active', 1, FALSE); // Only active programmes, allow NULL for users without programmes

        // Apply programme filter if provided
        if (!empty($programme_code)) {
            $this->db->where('p.code', $programme_code);
        }

        $programmes = $this->db->get('user_programmes up')->result_array();

        // Filter out NULL programme rows (from LEFT JOIN)
        $programmes = array_filter($programmes, function($prog) {
            return !is_null($prog['id']) && !is_null($prog['code']);
        });

        $users_data[] = [
            'id' => (string)$user['id'], // Convert to string
            'first_name' => $user['first_name'] ?? '',
            'last_name' => $user['last_name'] ?? '',
            'phone' => $user['phone'] ?? '',
            'email' => $user['email'] ?? '',
            'role' => $user['role'] ?? '',
            'country' => $user['country'] ?? '',
            'salutation' => $user['salutation'] ?? '',
            'main_office' => $user['main_office'] ?? '',
            'description' => $user['description'] ?? '',
            'last_login_at' => $user['last_login_at'] ? date('Y-m-d H:i:s', strtotime($user['last_login_at'])) : '', // Format or empty string
            'avatar' => $user['avatar'] ?? '', // Include avatar, default to empty string if NULL
            'isActive' => (bool)$user['isActive'], // Convert to boolean
            'programmes' => array_map(function($prog) {
                return [
                    'id' => (string)$prog['id'],
                    'code' => $prog['code']
                ];
            }, $programmes)
        ];
    }

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

public function get_all_users_aim_experts()
{
    // Validate user_id (assuming it's passed via GET or session for authentication)
    $user_id = $this->input->get('user_id') ?? $this->session->userdata('user_id');
    if (empty($user_id)) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(401) // Unauthorized
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'INVALID_USER_ID'
            )));
    }

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

    // Get programme code from input (optional)
    $programme_code = $this->input->get('programme');

    // Get country code from input (optional)
    $country_code = $this->input->get('country');

    // Select user fields, including image as avatar and is_active as isActive
    $this->db->select('u.id, u.first_name, u.last_name, u.phone, u.role,  u.email, c.name as country, u.salutation, u.main_office, u.description, u.last_login_at, u.image as avatar, u.is_active as isActive');
    // $this->db->where('u.is_active', 1); // Only active users
    // $this->db->where("u.system_role NOT LIKE '%SUPER_ADMIN%'", NULL, FALSE); // Exclude SUPER_ADMIN roles
     $this->db->where("u.country_id  LIKE '%6%'", NULL, FALSE);
     $this->db->where("u.role NOT LIKE '%finance%'", NULL, FALSE);
    // Join with countries table for country name
    $this->db->join('countries c', 'u.country_id = c.id', 'left');
    $this->db->where('c.is_active', 1); // Only active countries
    $this->db->where('u.isShortTermExpert', 1); // Only short term experts users
    // $this->db->where('u.id', 28);

    // Filter by country if provided
    if (!empty($country_code)) {
        $this->db->where('c.code', $country_code);
    }

    // Get all users
    $users = $this->db->get('users u')->result_array();

    // Prepare response data
    $users_data = [];
    foreach ($users as $user) {
        // Fetch programmes for this user
        $this->db->select('p.id, p.code');
        $this->db->join('programmes p', 'up.programme_id = p.id', 'left'); // Use LEFT JOIN to include users without programmes
        $this->db->where('up.user_id', $user['id']);
        $this->db->where('p.is_active', 1, FALSE); // Only active programmes, allow NULL for users without programmes

        // Apply programme filter if provided
        if (!empty($programme_code)) {
            $this->db->where('p.code', $programme_code);
        }

        $programmes = $this->db->get('user_programmes up')->result_array();

        // Filter out NULL programme rows (from LEFT JOIN)
        $programmes = array_filter($programmes, function($prog) {
            return !is_null($prog['id']) && !is_null($prog['code']);
        });

        $users_data[] = [
            'id' => (string)$user['id'], // Convert to string
            'first_name' => $user['first_name'] ?? '',
            'last_name' => $user['last_name'] ?? '',
            'phone' => $user['phone'] ?? '',
            'email' => $user['email'] ?? '',
            'role' => $user['role'] ?? '',
            'country' => $user['country'] ?? '',
            'salutation' => $user['salutation'] ?? '',
            'main_office' => $user['main_office'] ?? '',
            'description' => $user['description'] ?? '',
            'last_login_at' => $user['last_login_at'] ? date('Y-m-d H:i:s', strtotime($user['last_login_at'])) : '', // Format or empty string
            'avatar' => $user['avatar'] ?? '', // Include avatar, default to empty string if NULL
            'isActive' => (bool)$user['isActive'], // Convert to boolean
            'programmes' => array_map(function($prog) {
                return [
                    'id' => (string)$prog['id'],
                    'code' => $prog['code']
                ];
            }, $programmes)
        ];
    }

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

// public function get_user_details()
// {
//     // Validate authenticated user_id (assuming it's passed via GET or session)
//     $auth_user_id = $this->input->get('auth_user_id') ?? $this->session->userdata('user_id');
//     if (empty($auth_user_id)) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(401) // Unauthorized
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_AUTH_USER_ID'
//             )));
//     }

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

//     if (!$auth_user_exists) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(401) // Unauthorized
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_AUTH_USER_ID'
//             )));
//     }

//     // Get target user_id from input
//     $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' => 'MISSING_USER_ID'
//             )));
//     }

//     // Select user fields
//     $this->db->select('u.id, u.first_name, u.last_name, u.phone, u.role, c.name as country, u.salutation, u.main_office, u.description, u.last_login_at, u.image as avatar, u.is_active as isActive');
//     $this->db->where('u.id', $user_id);
//     $this->db->where('u.is_active', 1); // Only active users
//     $this->db->where("u.system_role NOT LIKE '%SUPER_ADMIN%'", NULL, FALSE); // Exclude SUPER_ADMIN roles

//     // Join with countries table for country name
//     $this->db->join('countries c', 'u.country_id = c.id', 'left');
//     $this->db->where('c.is_active', 1); // Only active countries

//     // Get user
//     $user = $this->db->get('users u')->row_array();

//     // Check if user exists
//     if (!$user) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(404) // Not Found
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'USER_NOT_FOUND'
//             )));
//     }

//     // Fetch programmes for this user
//     $this->db->select('p.id, p.code');
//     $this->db->join('programmes p', 'up.programme_id = p.id', 'left'); // Use LEFT JOIN to include users without programmes
//     $this->db->where('up.user_id', $user['id']);
//     $this->db->where('p.is_active', 1, FALSE); // Only active programmes, allow NULL for users without programmes

//     $programmes = $this->db->get('user_programmes up')->result_array();

//     // Filter out NULL programme rows (from LEFT JOIN)
//     $programmes = array_filter($programmes, function($prog) {
//         return !is_null($prog['id']) && !is_null($prog['code']);
//     });

//     // Prepare response data
//     $user_data = [
//         'id' => (string)$user['id'], // Convert to string
//         'first_name' => $user['first_name'] ?? '',
//         'last_name' => $user['last_name'] ?? '',
//         'phone' => $user['phone'] ?? '',
//         'role' => $user['role'] ?? '',
//         'country' => $user['country'] ?? '',
//         'salutation' => $user['salutation'] ?? '',
//         'main_office' => $user['main_office'] ?? '',
//         'description' => $user['description'] ?? '',
//         'last_login_at' => $user['last_login_at'] ? date('Y-m-d H:i:s', strtotime($user['last_login_at'])) : '', // Format or empty string
//         'avatar' => $user['avatar'] ?? '', // Include avatar, default to empty string if NULL
//         'isActive' => (bool)$user['isActive'], // Convert to boolean
//         'programmes' => array_map(function($prog) {
//             return [
//                 'id' => (string)$prog['id'],
//                 'code' => $prog['code']
//             ];
//         }, $programmes)
//     ];

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

// public function get_user_details()
// {
//     // Validate authenticated user_id (assuming it's passed via GET or session)
//     $auth_user_id = $this->input->get('auth_user_id') ?? $this->session->userdata('user_id');
//     if (empty($auth_user_id)) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(401) // Unauthorized
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_AUTH_USER_ID'
//             )));
//     }

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

//     if (!$auth_user_exists) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(401) // Unauthorized
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'INVALID_AUTH_USER_ID'
//             )));
//     }

//     // Get target user_id from input
//     $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' => 'MISSING_USER_ID'
//             )));
//     }

//     // Select user fields
//     $this->db->select('u.id, u.first_name, u.last_name, u.phone, u.role, c.name as country, u.salutation, u.main_office, u.description, u.last_login_at, u.image as avatar, u.is_active as isActive');
//     $this->db->where('u.id', $user_id);
//     $this->db->where('u.is_active', 1); // Only active users
//     $this->db->where("u.system_role NOT LIKE '%SUPER_ADMIN%'", NULL, FALSE); // Exclude SUPER_ADMIN roles

//     // Join with countries table for country name
//     $this->db->join('countries c', 'u.country_id = c.id', 'left');
//     $this->db->where('c.is_active', 1); // Only active countries

//     // Get user
//     $user = $this->db->get('users u')->row_array();

//     // Check if user exists
//     if (!$user) {
//         return $this->output
//             ->set_content_type('application/json')
//             ->set_status_header(404) // Not Found
//             ->set_output(json_encode(array(
//                 'success' => false,
//                 'message' => 'USER_NOT_FOUND'
//             )));
//     }

//     // Fetch programmes for this user
//     $this->db->select('p.id, p.code');
//     $this->db->join('programmes p', 'up.programme_id = p.id', 'left'); // Use LEFT JOIN to include users without programmes
//     $this->db->where('up.user_id', $user['id']);
//     $this->db->where('p.is_active', 1, FALSE); // Only active programmes, allow NULL for users without programmes
//     $programmes = $this->db->get('user_programmes up')->result_array();

//     // Filter out NULL programme rows (from LEFT JOIN)
//     $programmes = array_filter($programmes, function($prog) {
//         return !is_null($prog['id']) && !is_null($prog['code']);
//     });

//     // Fetch activities where user is in inCharges
//     $activities_query = "SELECT a.id, a.name, a.outcome_id, q.quarter AS quarter
//                         FROM activities a
//                         JOIN outcomes o ON a.outcome_id = o.id AND o.is_active = 1
//                         LEFT JOIN quarters q ON o.quarter_id = q.id AND q.is_active = 1
//                         WHERE a.is_active = 1
//                         AND a.inCharges IS NOT NULL
//                         AND a.inCharges != ''
//                         AND (
//                             (JSON_VALID(a.inCharges) AND JSON_CONTAINS(a.inCharges, ?))
//                             OR a.inCharges LIKE ?
//                         )";
//     $activities = $this->db->query($activities_query, [
//         $user['id'],
//         "%[$user[id]]%"
//     ])->result_array();

//     // Fetch sub_activities where user is in inCharges
//     $sub_activities_query = "SELECT sa.id, sa.name, sa.parent_activity_id
//                             FROM sub_activities sa
//                             WHERE sa.is_active = 1
//                             AND sa.inCharges IS NOT NULL
//                             AND sa.inCharges != ''
//                             AND (
//                                 (JSON_VALID(sa.inCharges) AND JSON_CONTAINS(sa.inCharges, ?))
//                                 OR sa.inCharges LIKE ?
//                             )";
//     $sub_activities = $this->db->query($sub_activities_query, [
//         $user['id'],
//         "%[$user[id]]%"
//     ])->result_array();

//     // Fetch follow_up_activities where user is in inCharges
//     $follow_up_activities_query = "SELECT fa.id, fa.name, fa.parent_activity_id
//                                   FROM follow_up_activities fa
//                                   WHERE fa.is_active = 1
//                                   AND fa.inCharges IS NOT NULL
//                                   AND fa.inCharges != ''
//                                   AND (
//                                       (JSON_VALID(fa.inCharges) AND JSON_CONTAINS(fa.inCharges, ?))
//                                       OR fa.inCharges LIKE ?
//                                   )";
//     $follow_up_activities = $this->db->query($follow_up_activities_query, [
//         $user['id'],
//         "%[$user[id]]%"
//     ])->result_array();

//     // Fetch sub_activity_follow_up_activities where user is in inCharges
//     $safa_query = "SELECT safa.id, safa.name, safa.parent_sub_activity_id
//                   FROM sub_activity_follow_up_activities safa
//                   WHERE safa.is_active = 1
//                   AND safa.inCharges IS NOT NULL
//                   AND safa.inCharges != ''
//                   AND (
//                       (JSON_VALID(safa.inCharges) AND JSON_CONTAINS(safa.inCharges, ?))
//                       OR safa.inCharges LIKE ?
//                   )";
//     $sub_activity_follow_up_activities = $this->db->query($safa_query, [
//         $user['id'],
//         "%[$user[id]]%"
//     ])->result_array();

//     // Fetch products where user is in in_charge_ids
//     $products_query = "SELECT p.id, p.name, p.activity_id, p.status, p.in_charge_ids AS inCharges, 
//                              a.id AS activity_id, a.code AS activity_code, a.name AS activity_name, q.quarter AS activity_quarter
//                       FROM products p
//                       LEFT JOIN activities a ON p.activity_id = a.id AND a.is_active = 1
//                       LEFT JOIN outcomes o ON a.outcome_id = o.id AND o.is_active = 1
//                       LEFT JOIN quarters q ON o.quarter_id = q.id AND q.is_active = 1
//                       WHERE p.is_active = 1
//                       AND p.in_charge_ids IS NOT NULL
//                       AND p.in_charge_ids != ''
//                       AND (
//                           (JSON_VALID(p.in_charge_ids) AND JSON_CONTAINS(p.in_charge_ids, ?))
//                           OR p.in_charge_ids LIKE ?
//                       )";
//     $products = $this->db->query($products_query, [
//         $user['id'],
//         "%[$user[id]]%"
//     ])->result_array();

//     // Fetch sub_activity_products where user is in in_charge_ids
//     $sub_activity_products_query = "SELECT sap.id, sap.name, sap.sub_activity_id, sap.status, sap.in_charge_ids AS inCharges,
//                                           sa.id AS sub_activity_id, sa.name AS sub_activity_name, sa.parent_activity_id
//                                   FROM sub_activity_products sap
//                                   LEFT JOIN sub_activities sa ON sap.sub_activity_id = sa.id AND sa.is_active = 1
//                                   WHERE sap.is_active = 1
//                                   AND sap.in_charge_ids IS NOT NULL
//                                   AND sap.in_charge_ids != ''
//                                   AND (
//                                       (JSON_VALID(sap.in_charge_ids) AND JSON_CONTAINS(sap.in_charge_ids, ?))
//                                       OR sap.in_charge_ids LIKE ?
//                                   )";
//     $sub_activity_products = $this->db->query($sub_activity_products_query, [
//         $user['id'],
//         "%[$user[id]]%"
//     ])->result_array();

//     // Fetch attachments for all relevant entities


//     // Prepare response data
//     $user_data = [
//         'id' => (string)$user['id'], // Convert to string
//         'first_name' => $user['first_name'] ?? '',
//         'last_name' => $user['last_name'] ?? '',
//         'phone' => $user['phone'] ?? '',
//         'role' => $user['role'] ?? '',
//         'country' => $user['country'] ?? '',
//         'salutation' => $user['salutation'] ?? '',
//         'main_office' => $user['main_office'] ?? '',
//         'description' => $user['description'] ?? '',
//         'last_login_at' => $user['last_login_at'] ? date('Y-m-d H:i:s', strtotime($user['last_login_at'])) : '', // Format or empty string
//         'avatar' => $user['avatar'] ?? '', // Include avatar, default to empty string if NULL
//         'isActive' => (bool)$user['isActive'], // Convert to boolean
//         'programmes' => array_map(function($prog) {
//             return [
//                 'id' => (string)$prog['id'],
//                 'code' => $prog['code']
//             ];
//         }, $programmes),
//         'activities' => array_map(function($activity) {
//             return [
//                 'id' => (string)$activity['id'],
//                 'name' => $activity['name'] ?? '',
//                 'outcome_id' => (string)$activity['outcome_id'],
//                 'quarter' => $activity['quarter'] ?? ''
//             ];
//         }, $activities),
//         'sub_activities' => array_map(function($sub_activity) {
//             return [
//                 'id' => (string)$sub_activity['id'],
//                 'name' => $sub_activity['name'] ?? '',
//                 'parent_activity_id' => (string)$sub_activity['parent_activity_id']
//             ];
//         }, $sub_activities),
//         'follow_up_activities' => array_map(function($follow_up) {
//             return [
//                 'id' => (string)$follow_up['id'],
//                 'name' => $follow_up['name'] ?? '',
//                 'parent_activity_id' => (string)$follow_up['parent_activity_id']
//             ];
//         }, $follow_up_activities),
//         'sub_activity_follow_up_activities' => array_map(function($safa) {
//             return [
//                 'id' => (string)$safa['id'],
//                 'name' => $safa['name'] ?? '',
//                 'parent_sub_activity_id' => (string)$safa['parent_sub_activity_id']
//             ];
//         }, $sub_activity_follow_up_activities),
//         'products' => array_map(function($product) {
//             $activity = $product['activity_id'] ? [
//                 'id' => (string)$product['activity_id'],
//                 'code' => $product['activity_code'] ?? '',
//                 'name' => $product['activity_name'] ?? '',
//                 'quarter' => $product['activity_quarter'] ?? ''
//             ] : null;
//             return [
//                 'id' => (string)$product['id'],
//                 'name' => $product['name'] ?? '',
//                 'activity_id' => $product['activity_id'] ? (string)$product['activity_id'] : null,
//                 'status' => $product['status'] ?? '',
//                 'inCharges' => $product['inCharges'] ?? '',
//                 'activity' => $activity
//             ];
//         }, $products),
//         'sub_activity_products' => array_map(function($sap) {
//             $sub_activity = $sap['sub_activity_id'] ? [
//                 'id' => (string)$sap['sub_activity_id'],
//                 'name' => $sap['sub_activity_name'] ?? '',
//                 'parent_activity_id' => (string)$sap['parent_activity_id']
//             ] : null;
//             return [
//                 'id' => (string)$sap['id'],
//                 'name' => $sap['name'] ?? '',
//                 'sub_activity_id' => $sap['sub_activity_id'] ? (string)$sap['sub_activity_id'] : null,
//                 'status' => $sap['status'] ?? '',
//                 'inCharges' => $sap['inCharges'] ?? '',
//                 'sub_activity' => $sub_activity
//             ];
//         }, $sub_activity_products),
//         'attachments' => []
//     ];

//     return $this->output
//         ->set_content_type('application/json')
//         ->set_status_header(200)
//         ->set_output(json_encode(array(
//             'success' => true,
//             'message' => 'USER_RETRIEVED_SUCCESSFULLY',
//             'data' => $user_data
//         )));
// }
// 
    public function get_user_details1()
    {
        // Validate authenticated user_id (assuming it's passed via GET or session)
        $auth_user_id = $this->input->get('auth_user_id') ?? $this->session->userdata('user_id');
        if (empty($auth_user_id)) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(401) // Unauthorized
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => 'INVALID_AUTH_USER_ID'
                )));
        }

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

        if (!$auth_user_exists) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(401) // Unauthorized
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => 'INVALID_AUTH_USER_ID'
                )));
        }

        // Get target user_id from input
        $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' => 'MISSING_USER_ID'
                )));
        }

        // Select user fields
        $this->db->select('u.id, u.first_name, u.last_name, u.phone, u.role, c.name as country, u.salutation, u.main_office, u.description, u.last_login_at, u.image as avatar, u.is_active as isActive');
        $this->db->where('u.id', $user_id);
        $this->db->where('u.is_active', 1); // Only active users
        $this->db->where("u.system_role NOT LIKE '%SUPER_ADMIN%'", NULL, FALSE); // Exclude SUPER_ADMIN roles

        // Join with countries table for country name
        $this->db->join('countries c', 'u.country_id = c.id', 'left');
        $this->db->where('c.is_active', 1); // Only active countries

        // Get user
        $user = $this->db->get('users u')->row_array();

        // Check if user exists
        if (!$user) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(404) // Not Found
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => 'USER_NOT_FOUND'
                )));
        }

        // Fetch programmes for this user
        $this->db->select('p.id, p.code');
        $this->db->join('programmes p', 'up.programme_id = p.id', 'left'); // Use LEFT JOIN to include users without programmes
        $this->db->where('up.user_id', $user['id']);
        $this->db->where('p.is_active', 1, FALSE); // Only active programmes, allow NULL for users without programmes
        $programmes = $this->db->get('user_programmes up')->result_array();

        // Filter out NULL programme rows (from LEFT JOIN)
        $programmes = array_filter($programmes, function($prog) {
            return !is_null($prog['id']) && !is_null($prog['code']);
        });

        // Fetch activities where user is in inCharges
        $activities_query = "SELECT a.id, a.code, a.name, a.outcome_id, a.status, a.inCharges, q.quarter AS quarter
                            FROM activities a
                            JOIN outcomes o ON a.outcome_id = o.id AND o.is_active = 1
                            LEFT JOIN quarters q ON o.quarter_id = q.id AND q.is_active = 1
                            WHERE a.is_active = 1
                            AND a.inCharges IS NOT NULL
                            AND a.inCharges != ''
                            AND (
                                (JSON_VALID(a.inCharges) AND JSON_CONTAINS(a.inCharges, ?))
                                OR a.inCharges LIKE ?
                            )";
        $activities = $this->db->query($activities_query, [
            $user['id'],
            "%[$user[id]]%"
        ])->result_array();

        // Fetch sub_activities where user is in inCharges and parent_activity_id is not null
        $sub_activities_query = "SELECT sa.id, sa.name, sa.status, sa.inCharges, sa.parent_activity_id,
                                       a.id AS activity_id, a.code AS activity_code, a.name AS activity_name, q.quarter AS activity_quarter
                                FROM sub_activities sa
                                INNER JOIN activities a ON sa.parent_activity_id = a.id AND a.is_active = 1
                                LEFT JOIN outcomes o ON a.outcome_id = o.id AND o.is_active = 1
                                LEFT JOIN quarters q ON o.quarter_id = q.id AND q.is_active = 1
                                WHERE sa.is_active = 1
                                AND sa.inCharges IS NOT NULL
                                AND sa.inCharges != ''
                                AND (
                                    (JSON_VALID(sa.inCharges) AND JSON_CONTAINS(sa.inCharges, ?))
                                    OR sa.inCharges LIKE ?
                                )";
        $sub_activities = $this->db->query($sub_activities_query, [
            $user['id'],
            "%[$user[id]]%"
        ])->result_array();

        // Fetch follow_up_activities where user is in inCharges
        $follow_up_activities_query = "SELECT fa.id, fa.name, fa.inCharges, fa.parent_activity_id
                                      FROM follow_up_activities fa
                                      WHERE fa.is_active = 1
                                      AND fa.inCharges IS NOT NULL
                                      AND fa.inCharges != ''
                                      AND (
                                          (JSON_VALID(fa.inCharges) AND JSON_CONTAINS(fa.inCharges, ?))
                                          OR fa.inCharges LIKE ?
                                      )";
        $follow_up_activities = $this->db->query($follow_up_activities_query, [
            $user['id'],
            "%[$user[id]]%"
        ])->result_array();

        // Fetch sub_activity_follow_up_activities where user is in inCharges
        $safa_query = "SELECT safa.id, safa.name, safa.inCharges, safa.parent_sub_activity_id,
                              sa.id AS sub_activity_id, sa.name AS sub_activity_name, sa.status AS sub_activity_status,
                              a.id AS activity_id, a.code AS activity_code, a.name AS activity_name, q.quarter AS activity_quarter
                       FROM sub_activity_follow_up_activities safa
                       LEFT JOIN sub_activities sa ON safa.parent_sub_activity_id = sa.id AND sa.is_active = 1
                       LEFT JOIN activities a ON sa.parent_activity_id = a.id AND a.is_active = 1
                       LEFT JOIN outcomes o ON a.outcome_id = o.id AND o.is_active = 1
                       LEFT JOIN quarters q ON o.quarter_id = q.id AND q.is_active = 1
                       WHERE safa.is_active = 1
                       AND safa.inCharges IS NOT NULL
                       AND safa.inCharges != ''
                       AND (
                           (JSON_VALID(safa.inCharges) AND JSON_CONTAINS(safa.inCharges, ?))
                           OR safa.inCharges LIKE ?
                       )";
        $sub_activity_follow_up_activities = $this->db->query($safa_query, [
            $user['id'],
            "%[$user[id]]%"
        ])->result_array();

        // Fetch products where user is in in_charge_ids and activity_id is not null
        $products_query = "SELECT p.id, p.name, p.activity_id, p.status, p.type, p.url, p.group, p.in_charge_ids AS inCharges, 
                                 p.date_submitted, p.last_updated,
                                 a.id AS activity_id, a.code AS activity_code, a.name AS activity_name, q.quarter AS activity_quarter
                          FROM products p
                          LEFT JOIN activities a ON p.activity_id = a.id AND a.is_active = 1
                          LEFT JOIN outcomes o ON a.outcome_id = o.id AND o.is_active = 1
                          LEFT JOIN quarters q ON o.quarter_id = q.id AND q.is_active = 1
                          WHERE p.is_active = 1
                          AND p.in_charge_ids IS NOT NULL
                          AND p.in_charge_ids != ''
                          AND p.activity_id IS NOT NULL
                          AND (
                              (JSON_VALID(p.in_charge_ids) AND JSON_CONTAINS(p.in_charge_ids, ?))
                              OR p.in_charge_ids LIKE ?
                          )";
        $products = $this->db->query($products_query, [
            $user['id'],
            "%[$user[id]]%"
        ])->result_array();

        // Fetch sub_activity_products where user is in in_charge_ids
        $sub_activity_products_query = "SELECT sap.id, sap.name, sap.sub_activity_id, sap.status,sap.type, sap.group, sap.url, sap.in_charge_ids AS inCharges,
                                              sa.id AS sub_activity_id, sa.name AS sub_activity_name, sa.parent_activity_id,
                                              a.id AS activity_id, a.code AS activity_code, a.name AS activity_name, q.quarter AS activity_quarter
                                       FROM sub_activity_products sap
                                       LEFT JOIN sub_activities sa ON sap.sub_activity_id = sa.id AND sa.is_active = 1
                                       LEFT JOIN activities a ON sa.parent_activity_id = a.id AND a.is_active = 1
                                       LEFT JOIN outcomes o ON a.outcome_id = o.id AND o.is_active = 1
                                       LEFT JOIN quarters q ON o.quarter_id = q.id AND q.is_active = 1
                                       WHERE sap.is_active = 1
                                       AND sap.in_charge_ids IS NOT NULL
                                       AND sap.in_charge_ids != ''
                                       AND (
                                           (JSON_VALID(sap.in_charge_ids) AND JSON_CONTAINS(sap.in_charge_ids, ?))
                                           OR sap.in_charge_ids LIKE ?
                                       )";
        $sub_activity_products = $this->db->query($sub_activity_products_query, [
            $user['id'],
            "%[$user[id]]%"
        ])->result_array();

        // Prepare response data
        $user_data = [
            'id' => (string)$user['id'], // Convert to string
            'first_name' => $user['first_name'] ?? '',
            'last_name' => $user['last_name'] ?? '',
            'phone' => $user['phone'] ?? '',
            'role' => $user['role'] ?? '',
            'country' => $user['country'] ?? '',
            'salutation' => $user['salutation'] ?? '',
            'main_office' => $user['main_office'] ?? '',
            'description' => $user['description'] ?? '',
            'last_login_at' => $user['last_login_at'] ? date('Y-m-d H:i:s', strtotime($user['last_login_at'])) : '', // Format or empty string
            'avatar' => $user['avatar'] ?? '', // Include avatar, default to empty string if NULL
            'isActive' => (bool)$user['isActive'], // Convert to boolean
            'programmes' => array_map(function($prog) {
                return [
                    'id' => (string)$prog['id'],
                    'code' => $prog['code']
                ];
            }, $programmes),
            'activities' => array_map(function($activity) {
                $in_charge_ids = json_decode($activity['inCharges'], true) ?: [];
                return [
                    'id' => (string)$activity['id'],
                    'code' => $activity['code'] ?? '',
                    'name' => $activity['name'] ?? '',
                    'status' => $activity['status'] ?? '',
                    'outcome_id' => (string)$activity['outcome_id'],
                    'quarter' => $activity['quarter'] ?? '',
                    'inCharges' => $this->get_in_charge_details($in_charge_ids),
                    'months' => $this->get_activity_months($activity['id'])
                ];
            }, $activities),
            'sub_activities' => array_map(function($sub_activity) {
                $in_charge_ids = json_decode($sub_activity['inCharges'], true) ?: [];
                $activity = [
                    'id' => (string)$sub_activity['activity_id'],
                    'code' => $sub_activity['activity_code'] ?? '',
                    'name' => $sub_activity['activity_name'] ?? '',
                    'quarter' => $sub_activity['activity_quarter'] ?? ''
                ];
                return [
                    'id' => (string)$sub_activity['id'],
                    'name' => $sub_activity['name'] ?? '',
                    'status' => $sub_activity['status'] ?? '',
                    'inCharges' => $this->get_in_charge_details($in_charge_ids),
                    'months' => $this->get_sub_activity_months($sub_activity['id']),
                    'activity' => $activity
                ];
            }, $sub_activities),
            'follow_up_activities' => array_map(function($follow_up) {
                $in_charge_ids = json_decode($follow_up['inCharges'], true) ?: [];
                return [
                    'id' => (string)$follow_up['id'],
                    'name' => $follow_up['name'] ?? '',
                    'inCharges' => $this->get_in_charge_details($in_charge_ids),
                    'parent_activity_id' => (string)$follow_up['parent_activity_id']
                ];
            }, $follow_up_activities),
            'sub_activity_follow_up_activities' => array_map(function($safa) {
                $in_charge_ids = json_decode($safa['inCharges'], true) ?: [];
                $activity = $safa['activity_id'] ? [
                    'id' => (string)$safa['activity_id'],
                    'code' => $safa['activity_code'] ?? '',
                    'name' => $safa['activity_name'] ?? '',
                    'quarter' => $safa['activity_quarter'] ?? ''
                ] : null;
                $sub_activity = $safa['sub_activity_id'] ? [
                    'id' => (string)$safa['sub_activity_id'],
                    'name' => $safa['sub_activity_name'] ?? '',
                    'status' => $safa['sub_activity_status'] ?? '',
                    'activity' => $activity
                ] : null;
                return [
                    'id' => (string)$safa['id'],
                    'name' => $safa['name'] ?? '',
                    'inCharges' => $this->get_in_charge_details($in_charge_ids),
                    'sub_activity' => $sub_activity
                ];
            }, $sub_activity_follow_up_activities),
            'products' => array_map(function($product) {
    $in_charge_ids = json_decode($product['inCharges'], true) ?: [];
    $activity = $product['activity_id'] ? [
        'id' => (string)$product['activity_id'],
        'code' => $product['activity_code'] ?? '',
        'name' => $product['activity_name'] ?? '',
        'quarter' => $product['activity_quarter'] ?? ''
    ] : null;

    // Base product data without files
    $product_data = [
        'id' => (string)$product['id'],
        'name' => $product['name'] ?? '',
        'activity_id' => (string)$product['activity_id'],
        'status' => $product['status'] ?? '',
        'type' => $product['type'] ?? '',
        'url' => $product['url'] ?? '',
        'group'=>$product['group'],
        'comments'=>$product['group'] === 'general'? $this->get_comments('activity_product',$product['id']): $this->get_comments('activity_output_product',$product['id']),
        'inCharges' => $this->get_in_charge_details($in_charge_ids),
        'date_submitted' => $product['date_submitted'] ? date('Y-m-d H:i:s', strtotime($product['date_submitted'])) : '',
        'last_updated' => $product['last_updated'] ? date('Y-m-d H:i:s', strtotime($product['last_updated'])) : '',
        'activity' => $activity
    ];

    // Add files array only if type is folder
    if ($product['type'] === 'folder') {
        $this->db->where('product_id', $product['id']);
        $this->db->where('is_active', 1); // Assuming soft delete with is_active
        $files_data = $this->db->get('product_files')->result_array();
        $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_data);
        $product_data['files'] = $files;
    }

    return $product_data;
}, $products),
           'sub_activity_products' => array_map(function($sap) {
    $in_charge_ids = json_decode($sap['inCharges'], true) ?: [];
    $sub_activity = $sap['sub_activity_id'] ? [
        'id' => (string)$sap['sub_activity_id'],
        'name' => $sap['sub_activity_name'] ?? '',
        'parent_activity_id' => (string)$sap['parent_activity_id']
    ] : null;
    $activity = $sap['activity_id'] ? [
        'id' => (string)$sap['activity_id'],
        'code' => $sap['activity_code'] ?? '',
        'name' => $sap['activity_name'] ?? '',
        'quarter' => $sap['activity_quarter'] ?? ''
    ] : null;

    // Base sub-activity product data without files
    $sap_data = [
        'id' => (string)$sap['id'],
        'name' => $sap['name'] ?? '',
        'type' => $sap['type'] ?? '',
        'url' => $sap['url'] ?? '',
        'sub_activity_id' => $sap['sub_activity_id'] ? (string)$sap['sub_activity_id'] : null,
        'status' => $sap['status'] ?? '',
        'inCharges' => $this->get_in_charge_details($in_charge_ids),
        'comments'=>$this->get_comments('sub_activity_product', $sap['id']),
        'sub_activity' => $sub_activity,
        'activity' => $activity
    ];

    // Add files array only if type is folder
    if ($sap['type'] === 'folder') {
        $this->db->where('product_id', $sap['id']);
        $this->db->where('is_active', 1); // Assuming soft delete with is_active
        $files_data = $this->db->get('sub_activity_product_files')->result_array();
        $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_data);
        $sap_data['files'] = $files;
    }

    return $sap_data;
}, $sub_activity_products),
            'attachments' => $this->get_attachments_for_user($user_id)
        ];

        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(200)
            ->set_output(json_encode(array(
                'success' => true,
                'message' => 'USER_RETRIEVED_SUCCESSFULLY',
                'data' => $user_data
            )));
    }
    
    // trying to omit not active activities
    
      public function get_user_details()
    {
        // Validate authenticated user_id (assuming it's passed via GET or session)
        $auth_user_id = $this->input->get('auth_user_id') ?? $this->session->userdata('user_id');
        if (empty($auth_user_id)) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(401) // Unauthorized
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => 'INVALID_AUTH_USER_ID'
                )));
        }

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

        if (!$auth_user_exists) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(401) // Unauthorized
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => 'INVALID_AUTH_USER_ID'
                )));
        }

        // Get target user_id from input
        $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' => 'MISSING_USER_ID'
                )));
        }

        // Select user fields
        $this->db->select('u.id, u.first_name, u.last_name, u.phone, u.role, c.name as country, u.salutation, u.main_office, u.description, u.last_login_at, u.image as avatar, u.is_active as isActive');
        $this->db->where('u.id', $user_id);
        $this->db->where('u.is_active', 1); // Only active users
        $this->db->where("u.system_role NOT LIKE '%SUPER_ADMIN%'", NULL, FALSE); // Exclude SUPER_ADMIN roles

        // Join with countries table for country name
        $this->db->join('countries c', 'u.country_id = c.id', 'left');
        $this->db->where('c.is_active', 1); // Only active countries

        // Get user
        $user = $this->db->get('users u')->row_array();

        // Check if user exists
        if (!$user) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(404) // Not Found
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => 'USER_NOT_FOUND'
                )));
        }

        // Fetch programmes for this user
        $this->db->select('p.id, p.code');
        $this->db->join('programmes p', 'up.programme_id = p.id', 'left'); // Use LEFT JOIN to include users without programmes
        $this->db->where('up.user_id', $user['id']);
        $this->db->where('p.is_active', 1, FALSE); // Only active programmes, allow NULL for users without programmes
        $programmes = $this->db->get('user_programmes up')->result_array();

        // Filter out NULL programme rows (from LEFT JOIN)
        $programmes = array_filter($programmes, function($prog) {
            return !is_null($prog['id']) && !is_null($prog['code']);
        });

        // Fetch activities where user is in inCharges
        $activities_query = "SELECT a.id, a.code, a.name, a.outcome_id, a.status, a.inCharges, q.quarter AS quarter
                            FROM activities a
                            JOIN outcomes o ON a.outcome_id = o.id AND o.is_active = 1
                            LEFT JOIN quarters q ON o.quarter_id = q.id AND q.is_active = 1
                            WHERE a.is_active = 1
                            AND a.inCharges IS NOT NULL
                            AND a.inCharges != ''
                            AND (
                                (JSON_VALID(a.inCharges) AND JSON_CONTAINS(a.inCharges, ?))
                                OR a.inCharges LIKE ?
                            )";
        $activities = $this->db->query($activities_query, [
            $user['id'],
            "%[$user[id]]%"
        ])->result_array();

        // Fetch sub_activities where user is in inCharges and parent_activity_id is not null
        $sub_activities_query = "SELECT sa.id, sa.name, sa.status, sa.inCharges, sa.parent_activity_id,
                                       a.id AS activity_id, a.code AS activity_code, a.name AS activity_name, q.quarter AS activity_quarter
                                FROM sub_activities sa
                                INNER JOIN activities a ON sa.parent_activity_id = a.id AND a.is_active = 1
                                LEFT JOIN outcomes o ON a.outcome_id = o.id AND o.is_active = 1
                                LEFT JOIN quarters q ON o.quarter_id = q.id AND q.is_active = 1
                                WHERE sa.is_active = 1
                                AND sa.inCharges IS NOT NULL
                                AND sa.inCharges != ''
                                AND (
                                    (JSON_VALID(sa.inCharges) AND JSON_CONTAINS(sa.inCharges, ?))
                                    OR sa.inCharges LIKE ?
                                )";
        $sub_activities = $this->db->query($sub_activities_query, [
            $user['id'],
            "%[$user[id]]%"
        ])->result_array();

        // Fetch follow_up_activities where user is in inCharges
        $follow_up_activities_query = "SELECT fa.id, fa.name, fa.due_date, fa.inCharges, fa.parent_activity_id
                                      FROM follow_up_activities fa
                                      WHERE fa.is_active = 1
                                      AND fa.inCharges IS NOT NULL
                                      AND fa.inCharges != ''
                                      AND (
                                          (JSON_VALID(fa.inCharges) AND JSON_CONTAINS(fa.inCharges, ?))
                                          OR fa.inCharges LIKE ?
                                      )";
        $follow_up_activities = $this->db->query($follow_up_activities_query, [
            $user['id'],
            "%[$user[id]]%"
        ])->result_array();

        // Fetch sub_activity_follow_up_activities where user is in inCharges
        $safa_query = "SELECT safa.id, safa.name, safa.due_date, safa.inCharges, safa.parent_sub_activity_id,
                              sa.id AS sub_activity_id, sa.name AS sub_activity_name, sa.status AS sub_activity_status,
                              a.id AS activity_id, a.code AS activity_code, a.name AS activity_name, q.quarter AS activity_quarter
                       FROM sub_activity_follow_up_activities safa
                       LEFT JOIN sub_activities sa ON safa.parent_sub_activity_id = sa.id AND sa.is_active = 1
                       LEFT JOIN activities a ON sa.parent_activity_id = a.id AND a.is_active = 1
                       LEFT JOIN outcomes o ON a.outcome_id = o.id AND o.is_active = 1
                       LEFT JOIN quarters q ON o.quarter_id = q.id AND q.is_active = 1
                       WHERE safa.is_active = 1
                       AND safa.inCharges IS NOT NULL
                       AND safa.inCharges != ''
                       AND (
                           (JSON_VALID(safa.inCharges) AND JSON_CONTAINS(safa.inCharges, ?))
                           OR safa.inCharges LIKE ?
                       )";
        $sub_activity_follow_up_activities = $this->db->query($safa_query, [
            $user['id'],
            "%[$user[id]]%"
        ])->result_array();

        // Fetch products where user is in in_charge_ids and activity exists and is active
        $products_query = "SELECT p.id, p.name, p.activity_id, p.status, p.type, p.url, p.group, p.in_charge_ids AS inCharges, 
                                 p.date_submitted, p.last_updated,
                                 a.id AS activity_id, a.code AS activity_code, a.name AS activity_name, q.quarter AS activity_quarter
                          FROM products p
                          INNER JOIN activities a ON p.activity_id = a.id AND a.is_active = 1
                          LEFT JOIN outcomes o ON a.outcome_id = o.id AND o.is_active = 1
                          LEFT JOIN quarters q ON o.quarter_id = q.id AND q.is_active = 1
                          WHERE p.is_active = 1
                          AND p.in_charge_ids IS NOT NULL
                          AND p.in_charge_ids != ''
                          AND p.activity_id IS NOT NULL
                          AND (
                              (JSON_VALID(p.in_charge_ids) AND JSON_CONTAINS(p.in_charge_ids, ?))
                              OR p.in_charge_ids LIKE ?
                          )";
        $products = $this->db->query($products_query, [
            $user['id'],
            "%[$user[id]]%"
        ])->result_array();

        // Fetch sub_activity_products where user is in in_charge_ids and parent activity exists and is active
        $sub_activity_products_query = "SELECT sap.id, sap.name, sap.sub_activity_id, sap.status, sap.last_updated, sap.type, sap.group, sap.url, sap.in_charge_ids AS inCharges,
                                              sa.id AS sub_activity_id, sa.name AS sub_activity_name, sa.parent_activity_id,
                                              a.id AS activity_id, a.code AS activity_code, a.name AS activity_name, q.quarter AS activity_quarter
                                       FROM sub_activity_products sap
                                       LEFT JOIN sub_activities sa ON sap.sub_activity_id = sa.id AND sa.is_active = 1
                                       INNER JOIN activities a ON sa.parent_activity_id = a.id AND a.is_active = 1
                                       LEFT JOIN outcomes o ON a.outcome_id = o.id AND o.is_active = 1
                                       LEFT JOIN quarters q ON o.quarter_id = q.id AND q.is_active = 1
                                       WHERE sap.is_active = 1
                                       AND sap.in_charge_ids IS NOT NULL
                                       AND sap.in_charge_ids != ''
                                       AND sa.parent_activity_id IS NOT NULL
                                       AND (
                                           (JSON_VALID(sap.in_charge_ids) AND JSON_CONTAINS(sap.in_charge_ids, ?))
                                           OR sap.in_charge_ids LIKE ?
                                       )";
        $sub_activity_products = $this->db->query($sub_activity_products_query, [
            $user['id'],
            "%[$user[id]]%"
        ])->result_array();

        // Prepare response data
        $user_data = [
            'id' => (string)$user['id'], // Convert to string
            'first_name' => $user['first_name'] ?? '',
            'last_name' => $user['last_name'] ?? '',
            'phone' => $user['phone'] ?? '',
            'role' => $user['role'] ?? '',
            'country' => $user['country'] ?? '',
            'salutation' => $user['salutation'] ?? '',
            'main_office' => $user['main_office'] ?? '',
            'description' => $user['description'] ?? '',
            'last_login_at' => $user['last_login_at'] ? date('Y-m-d H:i:s', strtotime($user['last_login_at'])) : '', // Format or empty string
            'avatar' => $user['avatar'] ?? '', // Include avatar, default to empty string if NULL
            'isActive' => (bool)$user['isActive'], // Convert to boolean
            'programmes' => array_map(function($prog) {
                return [
                    'id' => (string)$prog['id'],
                    'code' => $prog['code']
                ];
            }, $programmes),
            'activities' => array_map(function($activity) {
                $in_charge_ids = json_decode($activity['inCharges'], true);
                if (json_last_error() !== JSON_ERROR_NONE) {
                    $in_charge_ids = [];
                }
                return [
                    'id' => (string)$activity['id'],
                    'code' => $activity['code'] ?? '',
                    'name' => $activity['name'] ?? '',
                    'status' => $activity['status'] ?? '',
                    'outcome_id' => (string)$activity['outcome_id'],
                    'quarter' => $activity['quarter'] ?? '',
                    'inCharges' => $this->get_in_charge_details($in_charge_ids),
                    'months' => $this->get_activity_months($activity['id'])
                ];
            }, $activities),
            'sub_activities' => array_map(function($sub_activity) {
                $in_charge_ids = json_decode($sub_activity['inCharges'], true);
                if (json_last_error() !== JSON_ERROR_NONE) {
                    $in_charge_ids = [];
                }
                $activity = [
                    'id' => (string)$sub_activity['activity_id'],
                    'code' => $sub_activity['activity_code'] ?? '',
                    'name' => $sub_activity['activity_name'] ?? '',
                    'quarter' => $sub_activity['activity_quarter'] ?? ''
                ];
                return [
                    'id' => (string)$sub_activity['id'],
                    'name' => $sub_activity['name'] ?? '',
                    'status' => $sub_activity['status'] ?? '',
                    'inCharges' => $this->get_in_charge_details($in_charge_ids),
                    'months' => $this->get_sub_activity_months($sub_activity['id']),
                    'activity' => $activity
                ];
            }, $sub_activities),
            'follow_up_activities' => array_map(function($follow_up) {
                $in_charge_ids = json_decode($follow_up['inCharges'], true);
                if (json_last_error() !== JSON_ERROR_NONE) {
                    $in_charge_ids = [];
                }
                return [
                    'id' => (string)$follow_up['id'],
                    'name' => $follow_up['name'] ?? '',
                    'due_date' => $follow_up['due_date'] ?? '',
                    'inCharges' => $this->get_in_charge_details($in_charge_ids),
                    'parent_activity_id' => (string)$follow_up['parent_activity_id']
                ];
            }, $follow_up_activities),
            'sub_activity_follow_up_activities' => array_map(function($safa) {
                $in_charge_ids = json_decode($safa['inCharges'], true);
                if (json_last_error() !== JSON_ERROR_NONE) {
                    $in_charge_ids = [];
                }
                $activity = $safa['activity_id'] ? [
                    'id' => (string)$safa['activity_id'],
                    'code' => $safa['activity_code'] ?? '',
                    'name' => $safa['activity_name'] ?? '',
                    'quarter' => $safa['activity_quarter'] ?? ''
                ] : null;
                $sub_activity = $safa['sub_activity_id'] ? [
                    'id' => (string)$safa['sub_activity_id'],
                    'name' => $safa['sub_activity_name'] ?? '',
                    'status' => $safa['sub_activity_status'] ?? '',
                    'activity' => $activity
                ] : null;
                return [
                    'id' => (string)$safa['id'],
                    'name' => $safa['name'] ?? '',
                     'due_date' => $safa['due_date'] ?? '',
                    'inCharges' => $this->get_in_charge_details($in_charge_ids),
                    'sub_activity' => $sub_activity
                ];
            }, $sub_activity_follow_up_activities),
            'products' => array_map(function($product) {
                $in_charge_ids = json_decode($product['inCharges'], true);
                if (json_last_error() !== JSON_ERROR_NONE) {
                    $in_charge_ids = [];
                }
                $activity = $product['activity_id'] ? [
                    'id' => (string)$product['activity_id'],
                    'code' => $product['activity_code'] ?? '',
                    'name' => $product['activity_name'] ?? '',
                    'quarter' => $product['activity_quarter'] ?? ''
                ] : null;

                // Base product data without files
                $product_data = [
                    'id' => (string)$product['id'],
                    'name' => $product['name'] ?? '',
                    'activity_id' => (string)$product['activity_id'],
                    'status' => $product['status'] ?? '',
                    'type' => $product['type'] ?? '',
                    'url' => $product['url'] ?? '',
                    'group' => $product['group'],
                    'comments' => $product['group'] === 'general' ? $this->get_comments('activity_product', $product['id']) : $this->get_comments('activity_output_product', $product['id']),
                    'inCharges' => $this->get_in_charge_details($in_charge_ids),
                    'date_submitted' => $product['date_submitted'] ? date('Y-m-d H:i:s', strtotime($product['date_submitted'])) : '',
                    'last_updated' => $product['last_updated'] ? date('Y-m-d H:i:s', strtotime($product['last_updated'])) : '',
                    'activity' => $activity
                ];

                // Add files array only if type is folder
                if ($product['type'] === 'folder') {
                    $this->db->where('product_id', $product['id']);
                    $this->db->where('is_active', 1); // Assuming soft delete with is_active
                    $files_data = $this->db->get('product_files')->result_array();
                    $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_data);
                    $product_data['files'] = $files;
                }

                return $product_data;
            }, $products),
            'sub_activity_products' => array_map(function($sap) {
                $in_charge_ids = json_decode($sap['inCharges'], true);
                if (json_last_error() !== JSON_ERROR_NONE) {
                    $in_charge_ids = [];
                }
                $sub_activity = $sap['sub_activity_id'] ? [
                    'id' => (string)$sap['sub_activity_id'],
                    'name' => $sap['sub_activity_name'] ?? '',
                    'parent_activity_id' => (string)$sap['parent_activity_id']
                ] : null;
                $activity = $sap['activity_id'] ? [
                    'id' => (string)$sap['activity_id'],
                    'code' => $sap['activity_code'] ?? '',
                    'name' => $sap['activity_name'] ?? '',
                    'quarter' => $sap['activity_quarter'] ?? ''
                ] : null;

                // Base sub-activity product data without files
                $sap_data = [
                    'id' => (string)$sap['id'],
                    'name' => $sap['name'] ?? '',
                    'type' => $sap['type'] ?? '',
                    'url' => $sap['url'] ?? '',
                    'sub_activity_id' => $sap['sub_activity_id'] ? (string)$sap['sub_activity_id'] : null,
                    'status' => $sap['status'] ?? '',
                    'last_updated' => $sap['last_updated'] ?? '',
                    'inCharges' => $this->get_in_charge_details($in_charge_ids),
                    'comments' => $this->get_comments('sub_activity_product', $sap['id']),
                    'sub_activity' => $sub_activity,
                    'activity' => $activity
                ];

                // Add files array only if type is folder
                if ($sap['type'] === 'folder') {
                    $this->db->where('product_id', $sap['id']);
                    $this->db->where('is_active', 1); // Assuming soft delete with is_active
                    $files_data = $this->db->get('sub_activity_product_files')->result_array();
                    $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_data);
                    $sap_data['files'] = $files;
                }

                return $sap_data;
            }, $sub_activity_products),
            'attachments' => $this->get_attachments_for_user($user_id)
        ];

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


public function get_all_notifications(){
    $all_notifications = $this->db->get('notifications')->result_array();
      return $this->output
        ->set_content_type('application/json')
        ->set_status_header(200)
        ->set_output(json_encode(array(
            'success' => true,
            'message' => 'NOTIFICATIONS_RETRIEVED_SUCCESSFULLY',
            'data' => $all_notifications
        )));
    
}

    public function update_profile_pic(){
        
            $config['upload_path'] = './profiles/';
            $config['allowed_types'] = 'jpg|png|JPEG|jpeg|PNG|JPG';
            $new_name = time() . '-' . $_FILES["photo"]['name'];
            $config['file_name'] = $new_name;

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

            if (!$this->upload->do_upload('photo') && !empty($_FILES['photo']['name'])) {
                $error = array('error' => $this->upload->display_errors());
                return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(200)
                    ->set_output(json_encode(
                        $error
                    ));
            }
            $upload_data = $this->upload->data();
            // $this->resize_image($upload_data);
          
            // $pic_url = base_url() . "profiles/" . $upload_data['file_name'];
// first check if an old photo exists
    $user = $this->db->get_where('users',array('id'=>$_POST['user_id']))->row();
    if($user->photo !=null){
        // delete the photo
       $photo_location = 'profiles/new/' . explode('profiles/new/', $user->photo)[1];
       
       // check if location exists
       //then delete
       if(file_exists($photo_location)){
          //delete
           unlink($photo_location);
          
       }
        
    }
            $data = array( 
                'photo' => $this->resize_image($upload_data),
                'last_updated' => time()
            );
            
            // here process uploaded image and 
            $this->db->where('id',$_POST['user_id']);
            if ($this->db->update('users', $data)) {
                return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(200)
                    ->set_output(json_encode(array(
                        'success' => true,
                        'photo'=>$data['photo'],
                        'message' => 'profile picture updated successfully'
                    )));
            } else {
                return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(200)
                    ->set_output(json_encode(array(
                        'success' => false,
                        'message' => 'profile picture not updated'
                    )));
            }
    }
    
    
public function resize_image($image_data){
    // print $image_data['full_path'];
   
 
    $w = $image_data['image_width']; // original image's width
    $h = $image_data['image_height']; // original images's height

    $n_w = 500; // destination image's width
    $n_h = 500; // destination image's height

    $source_ratio = $w / $h;
    $new_ratio = $n_w / $n_h;
    if($source_ratio != $new_ratio){

        $config['image_library'] = 'gd2';
        $config['source_image'] = base_url() . "profiles/" . $image_data['file_name'];
        $config['maintain_ratio'] = FALSE;
        if($new_ratio > $source_ratio || (($new_ratio == 1) && ($source_ratio < 1))){
            $config['width'] = $w;
            $config['height'] = round($w/$new_ratio);
            $config['y_axis'] = round(($h - $config['height'])/2);
            $config['x_axis'] = 0;

        } else {

            $config['width'] = round($h * $new_ratio);
            $config['height'] = $h;
            $size_config['x_axis'] = round(($w - $config['width'])/2);
            $size_config['y_axis'] = 0;

        }
        $this->load->library('image_lib');
        $this->image_lib->initialize($config);
        $this->image_lib->crop();
        $this->image_lib->clear();
    }
   
    $config['source_image'] = './profiles/'.$image_data['file_name'];
    $config['new_image'] = "./profiles/new/";
    $config['maintain_ratio'] = TRUE;
    $config['width'] = $n_w;
    $config['height'] = $n_h;
     $config['image_library'] = 'gd2';
    $this->image_lib->initialize($config);

    if (!$this->image_lib->resize()){

        echo $this->image_lib->display_errors();

    } else {
        // unlink/ delete the source image
         unlink($config['source_image']);
        

      return base_url()."profiles/new/".$image_data['file_name'];

    }
}

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

private function get_activity_months($activity_id)
{
    $this->db->select('month');
    $this->db->where('activity_id', $activity_id);
    $this->db->where('is_active', 1);
    
    $months = $this->db->get('activity_months')->result_array();

    // Define the order of months (1-based index for sorting)
    $month_order = [
        'January' => 1,
        'February' => 2,
        'March' => 3,
        'April' => 4,
        'May' => 5,
        'June' => 6,
        'July' => 7,
        'August' => 8,
        'September' => 9,
        'October' => 10,
        'November' => 11,
        'December' => 12
    ];

    // Extract month names from the result
    $month_names = array_column($months, 'month');

    // Sort months based on their numerical order
    usort($month_names, function($a, $b) use ($month_order) {
        return $month_order[$a] - $month_order[$b];
    });

    return $month_names;
}

private function get_sub_activity_months($sub_activity_id)
{
    $this->db->select('month');
    $this->db->where('sub_activity_id', $sub_activity_id);
    $months = $this->db->get('sub_activity_months')->result_array();

    $month_order = [
        'January' => 1, 'February' => 2, 'March' => 3, 'April' => 4,
        'May' => 5, 'June' => 6, 'July' => 7, 'August' => 8,
        'September' => 9, 'October' => 10, 'November' => 11, 'December' => 12
    ];

    $month_names = array_column($months, 'month');
    usort($month_names, function($a, $b) use ($month_order) {
        return $month_order[$a] - $month_order[$b];
    });

    return $month_names;
}


 // Helper method to fetch all comments for an entity
    private function get_comments($entity_type, $entity_id, $time_frame = 'quarterly')
    {
       
        $this->db->select('c.id, c.body, c.created_at, c.updated_at, c.is_quarterly, u.id as user_id, u.first_name, u.last_name, u.image as avatar');
        $this->db->from('comments c');
        $this->db->join('users u', 'u.id = c.created_by', 'left');
        $this->db->where('c.entity_type', $entity_type);
        $this->db->where('c.entity_id', $entity_id);
        $this->db->where('c.is_quarterly', ($time_frame === 'quarterly') ? 1 : 0);
        $this->db->where('c.is_active', 1);
        $this->db->order_by('c.created_at', 'DESC'); // Latest first
        $comments = $this->db->get()->result_array();

        return array_map(function ($comment) {
            return [
                'id' => (string)$comment['id'],
                'body' => $comment['body'],
                'created_at' => $comment['created_at'],
                'updated_at' => $comment['updated_at'],
                'time_frame' => $comment['is_quarterly'] ? 'quarterly' : 'yearly',
                'user' => [
                    'id' => (string)$comment['user_id'],
                    'first_name' => $comment['first_name'],
                    'last_name' => $comment['last_name'],
                    'avatar' => $comment['avatar'] ? $comment['avatar'] : ''
                ]
            ];
        }, $comments);
    }
    
    
        // Helper method to fetch comment details with user info
    private function get_comment_details($comment_id)
    {
        $this->db->select('c.id, c.body, c.created_at, c.updated_at, c.is_quarterly, u.id as user_id, u.first_name, u.last_name, u.image as avatar');
        $this->db->from('comments c');
        $this->db->join('users u', 'u.id = c.created_by', 'left');
        $this->db->where('c.id', $comment_id);
        $this->db->where('c.is_active', 1);
        $comment = $this->db->get()->row_array();

        if ($comment) {
            return [
                'id' => (string)$comment['id'],
                'body' => $comment['body'],
                'created_at' => $comment['created_at'],
                'updated_at' => $comment['updated_at'],
                'time_frame' => $comment['is_quarterly'] ? 'quarterly' : 'yearly', // Return as string
                'user' => [
                    'id' => (string)$comment['user_id'],
                    'first_name' => $comment['first_name'],
                    'last_name' => $comment['last_name'],
                    'avatar' => $comment['avatar'] ? $comment['avatar'] : ''
                ]
            ];
        }
        return null;
    }
    
 private function get_attachments_for_user($user_id)
{
    $this->db->where('created_by', $user_id)->where('is_active', 1);
    $attachments = $this->db->get('attachments')->result_array();
    return array_map(function ($attachment) {
        // Determine entity type based on non-null ID fields
        $entity = null;
        if (!empty($attachment['sub_activity_id'])) {
            $entity = 'sub_activity_attachment';
        } elseif (!empty($attachment['activity_id'])) {
            $entity = 'activity_attachment';
        } elseif (!empty($attachment['follow_up_activity_id'])) {
            $entity = 'follow_up_activity_attachment';
        }elseif (!empty($attachment['activity_id'])) {
            $entity = 'activity';
        }

        return $this->get_attachment_data($attachment['id'], $entity);
    }, $attachments);
}
    
    // Helper method to fetch attachment data (consistent with add_attachment)
private function get_attachment_data($attachment_id, $entity="activity")
{
    $this->db->where('a.id', $attachment_id);
    $this->db->where('a.is_active', 1);
    $attachment = $this->db->get('attachments a')->row_array();

    if (!$attachment) return null;
    
    $entity_type = 'attachment'; // Default
    if ($entity === 'sub_activity_attachment') {
        $entity_type = 'sub_activity_attachment';
    } elseif ($entity === 'followup_activity_attachment') {
        $entity_type = 'followup_activity_attachment';
    }

    $data = [
        'id' => (string)$attachment['id'],
        'type' => $attachment['type'],
        'title' => $attachment['title'],
        'date' => $attachment['date'],
        'comments'=>  $this->get_comments($entity_type, $attachment['id'])
    ];

    if ($attachment['type'] === 'folder') {
        $this->db->where('attachment_id', $attachment_id);
        $this->db->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);
        $data['url'] = null;
        $data['size'] = null;
    } else {
        $data['url'] = $attachment['url'];
        $data['size'] = $attachment['size'];
        $data['files'] = [];
    }

    $in_charge_ids = json_decode($attachment['in_charge_ids'], true) ?: [];
    $data['team'] = [
        'name' => 'Attachment Team',
        'members' => $this->get_in_charge_details($in_charge_ids)
    ];

    return $data;
}

    public function update_profile(){
        $json_data = json_decode(@file_get_contents('php://input'), true);
        
        $user= $this->db->get_where('users',array('id'=>$json_data['user_id']))->row();
        
        
               // obtain the subjects
                if($json_data['level'] =='Olevel' && ($json_data['class']=='S.1'||$json_data['class']=="S.2")){
                
                   
              $this->db->select('id,subject_name');
                // $this->db->where('optional',0); // send all 
                $this->db->where('level',2);
               $query = $this->db->get('subjects');
               $compulsory_subjects = $query->result_array(); 
               $optionals = array();
               
               // if the user's class is S.3 /S.4/S.5/S.6 delete the their optionals
               
               if($user->class == "S.3"|| $user->class =="S.4"|| $user->class =="S.5"||$user->class =="S.6"){
                 
                   $user_optionals = $this->db->get_where('user_optional_subjects',array("user_id"=>$user->id))->result_array();
                   
                   if($user_optionals!=null){
                       // user has optionals therefore delete
                       $this->db->where('user_id',$json_data['user_id']);
                       $this->db->delete('user_optional_subjects');
                   }
               }
               
               $this->do_update($json_data,$compulsory_subjects,$optionals);
               
            }else if($json_data['level'] =='Olevel' && ($json_data['class']=="S.3" ||$json_data['class']=="S.4")){
                //     print "tuli wanno 680";
                // return;
               
                
                // first check if the user has been in Alevel/any other level
                // if($user->class == "S.5" || $user->class == "S.6" || $user->class=="S.1" || $user->class =="S.2" || $user->level=="Primary") {
                    // then delete the optionals
                 $user_optionals = $this->db->get_where('user_optional_subjects',array("user_id"=>$user->id))->result_array();
                   
                   if($user_optionals!=null &&($user->class != $json_data['class'])){
                       // user has optionals therefore delete
                       $this->db->where('user_id',$json_data['user_id']);
                       $this->db->delete('user_optional_subjects');
                   }
                
                $this->db->select('id,subject_name');
                $this->db->where('optional',0);
                $this->db->where('level',2);
               $query = $this->db->get('subjects');
               $compulsory_subjects = $query->result_array(); 
               
               // check if the user has optional subjects
             $user_subjects = $this->db->get_where('user_optional_subjects',array('user_id'=>$json_data['user_id']))->result_array();
               
               $optionals = array();
               foreach($user_subjects as $subject){
                   $this->db->select('id,subject_name');
                $this->db->where('id',$subject['subject_id']);
               $query = $this->db->get('subjects');
               array_push($optionals,$query->row());
               }
                //
                $this->do_update($json_data,$compulsory_subjects,$optionals);
                
                
               
            } else if($json_data['level'] =="Alevel" && ($json_data['class'] == "S.5" || $json_data['class'] == "S.6" )) {
                // Alevel 
                   
                    
                $this->db->select('id,subject_name');
                $this->db->where('level',3);
                $this->db->where('optional',0);
                $query = $this->db->get('subjects');
                $compulsory_subjects = $query->result_array(); 
               
               // check if the user has optional subjects
              $user_subjects = $this->db->get_where('user_optional_subjects',array('user_id'=>$json_data['user_id']))->result_array();
               
               $optionals = array();
               foreach($user_subjects as $subject){
                   $this->db->select('id,subject_name');
                $this->db->where('id',$subject['subject_id']);
               $query = $this->db->get('subjects');
               array_push($optionals,$query->row());
               }

               $this->do_update($json_data,$compulsory_subjects,$optionals);
            }else if($json_data['level'] =='Alevel' && ($user->class == "S.1"||$user->class == "S.2"|| $user->class == "S.3"|| $user->class == "S.4")) {
                // Alevel 
                // is the user in olevel and they update to Alevel
                
               
                
                $this->db->select('id,subject_name');
                $this->db->where('level',3);
                $this->db->where('optional',0);
                $query = $this->db->get('subjects');
                $compulsory_subjects = $query->result_array(); 
                
                $optionals = array();

                $this->do_update($json_data,$compulsory_subjects,$optionals);
                 
            }else if($json_data['level']=="Primary"){
                
               
               
                 $this->db->select('id,subject_name');
                 $this->db->where('level',1);
                 $this->db->where('optional',0);
               $query = $this->db->get('subjects');
               $compulsory_subjects = $query->result_array(); 
               $optionals = array();
               
               
               
                // if the user's class is S.3 or S.4 delete the their optionals
               
               if($user->class == "S.3"||$user->class == "S.4"||$user->class == "S.5"||$user->class == "S.6"){
                   
                   $user_optionals = $this->db->get_where('user_optional_subjects',array("user_id"=>$user->id))->result_array();
                   
                   if($user_optionals!=null){
                       // user has optionals therefore delete
                       $this->db->where('user_id',$json_data['user_id']);
                       $this->db->delete('user_optional_subjects');
                   }
               }
               $this->do_update($json_data,$compulsory_subjects,$optionals);
            
            
      
            }
                //else
         
            
    }

    public function do_update($json_data,$compulsory_subjects,$optionals){
     // then proceed to update
       
     $data = array(
        'firstname'=>$json_data['firstname'],
        'surname'=>$json_data['surname'],
        'class'=>$json_data['class'],
        'level'=>$json_data['level'],
        'sex'=>$json_data['sex'],
        'address'=>$json_data['address']
        
        );
        $this->db->where('id',$json_data['user_id']);
        if($this->db->update('users',$data)){
            
     
              return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(array(
                    'success' => true,
                    'compulsory_subjects'=>$compulsory_subjects,
                    'optional_subjects'=>$optionals,
                    'message' => 'profile information updated successfully'
                )));
        }else{
              return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => 'update failed'
                )));
        }
    }
    
    public function update_user_subjects(){
        
        $json_data = json_decode(@file_get_contents('php://input'), true);
        // first check if the array length is greater than 2 , this also covers alevel students
        
        $user_optionals = $this->db->get_where('user_optional_subjects',array('user_id'=>$json_data['user_id']))->result_array();
        
        if(count($user_optionals) >2){
            // first delete every record there
            $this->db->where('user_id',$json_data['user_id']);
            $this->db->delete('user_optional_subjects');
            
        }
      
        
        foreach($json_data['user_optional_subjects'] as $subject){
              $optional_subject=  $this->db->get_where('user_optional_subjects',array('user_id'=>$json_data['user_id'],'subject_id'=>$subject))->row();
              // first check if this subject doesn't exist for the user's optional
                if($optional_subject == null){
                $this->db->insert('user_optional_subjects',array('user_id'=>$json_data['user_id'],'subject_id'=>$subject,'time_added'=>time()));
                }
            }
            // also obtain subjects
            
            $user = $this->db->get_where('users',array('id'=>$json_data['user_id']))->row();
            
            if($user->level =='Olevel'){
                
         $this->db->select('id,subject_name');
                $this->db->where('optional',0);
                $this->db->where('level',2);
               $query = $this->db->get('subjects');
               $compulsory_subjects = $query->result_array(); 
            }else if($user->level =='Alevel') {
                // Alevel and primary
                $this->db->select('id,subject_name');
                $this->db->where('level',3);
                $this->db->where('optional',0);
               $query = $this->db->get('subjects');
               $compulsory_subjects = $query->result_array(); 
            }else{
                 $this->db->select('id,subject_name');
                 $this->db->where('level',1);
                 $this->db->where('optional',0);
               $query = $this->db->get('subjects');
               $compulsory_subjects = $query->result_array(); 
            }
            
            $optionals = array();
            foreach($json_data['user_optional_subjects'] as $subject){
             $this->db->select('id,subject_name');
                $this->db->where('id',$subject);
               $query = $this->db->get('subjects');
               array_push($optionals,$query->row());
            }
            
              return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(200)
                    ->set_output(json_encode(array(
                        'success' => true,
                        'compulsory_subjects'=>$compulsory_subjects,
                        'optional_subjects'=>$optionals,
                        'message' => 'subjects updated successfully'
                    )));
            
            
    }
    
    
    public function compare_info(){
        // check if the student is a valid buddoss_student
        $json_data = json_decode(@file_get_contents('php://input'), true);
        $user = $this->db->get_where('users',array('id'=>$json_data['user_id']))->row();
        // compare IF this info is for a Buddo ss student
        if($json_data['school']=='Buddo SS'){
        $compare = $this->db->get_where('buddoss_students',array('firstname'=>strtoupper($user->firstname),'surname'=>strtoupper($user->surname),'student_number'=>$json_data['student_number'],'stream'=>$json_data['stream']))->row();
        
        if($compare != null){
            // update the user's column of school to true
            // also update the user's column of student number 
            
            $this->db->where('id',$json_data['user_id']);
            
            $this->db->set('school',$json_data['school']);
            $this->db->set('student_number',$json_data['student_number']);
            if($this->db->update('users')){
             return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(200)
                    ->set_output(json_encode(array(
                        'success' => true,
                       'school'=>$json_data['school'],
                        'message' => 'Information verified'
                    )));
            }
        }else{
            
           return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(200)
                    ->set_output(json_encode(array(
                        'success' => false,
                       
                        'message' => 'Information not verified'
                    )));  
        }
        
        }else{
            // if a student is from another school
             $this->db->where('id',$json_data['user_id']);
            
            $this->db->set('school',$json_data['school']);
            
            if($this->db->update('users')){
             return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(200)
                    ->set_output(json_encode(array(
                        'success' => true,
                       'school'=>$json_data['school'],
                        'message' => 'Information verified'
                    )));
            }
        }
    }
    
    public function set_pickup_point(){
        
          $json_data = json_decode(@file_get_contents('php://input'), true);
          
          $this->db->where('id',$json_data['user_id']);
          $this->db->set('pickup_point',$json_data['pickup_point']);
          if($this->db->update('users')){
              
               return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(200)
                    ->set_output(json_encode(array(
                        'success' => true,
                        'message' => 'Pickup point updated'
                    )));  
                   
          }else{
               return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(200)
                    ->set_output(json_encode(array(
                        'success' => false,
                        'message' => 'Pickup point not updated'
                    )));  
                   
          }
    }
    
    public function get_pickup_point($user){
        
        $this->db->select('pickup_point');
      $user_info =  $this->db->get_where('users',array('id'=>$user))->row();
        
          return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(200)
                    ->set_output(json_encode(array(
                        'success' => true,
                        'pickup_point' =>$user_info->pickup_point
                    )));  
    }
}
