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

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

        $this->load->helper('form');
        $this->load->library('upload');
    }

    
    
    public function add_feedback(){
        // create the logic
        
        $json_data = json_decode(@file_get_contents('php://input'), true);

        $data = array(
            'user_id' => $json_data['userId'],
            'message' => $json_data['message'],
            'user_email' => $json_data['userEmail'],
            'rating' => $json_data['rating']
        );

        if ($this->db->insert('feedback', $data)) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(array(
                    'success' => true,
                    'message' => 'FEEDBACK_ADDED_SUCCESSFULLY'
                )));
        } else {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => 'FEEDBACK_NOT_ADDED'
                )));
    
        }
        
    }
    
 public function get_feedback()
{
    // Query to get specific columns from feedback
    $this->db->select('f.id, f.user_id, f.user_email, f.message, f.rating, f.created_at');
    $this->db->from('feedback f');
    $this->db->order_by('f.created_at', 'desc'); // Order by most recent feedback
    $query = $this->db->get();
    
    if ($query->num_rows() > 0) {
        $feedback = $query->result_array();
        
        // Reshape the data to nest user as an object
        $formatted_data = array_map(function($row) {
            return [
                'id' => $row['id'],
                'message' => $row['message'],
                'rating' => $row['rating'],
                'created_at' => $row['created_at'],
                'user' => [
                    'id' => $row['user_id'],
                    'email' => $row['user_email']
                ]
            ];
        }, $feedback);
        
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(200)
            ->set_output(json_encode(array(
                'success' => true,
                'message' => 'FEEDBACK_RETRIEVED_SUCCESSFULLY',
                'data' => $formatted_data
            )));
    } else {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(200)
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'NO_FEEDBACK_FOUND'
            )));
    }
}
    // function to add programme
    public function add_programme()
    {
        // add programme code here
        $title = $this->input->post('title');
        $check_title = $this->db->where('title', $title)->get('programmes')->row();

        if (($check_title != null)) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => "PROGRAMME_EXISTS",
                    
                )));
            
        } 
        // add programme
        $data = array(
            'title' => $this->input->post('title'),
            'description' => $this->input->post('description'),
            'duration' => $this->input->post('duration'),
            'country' => $this->input->post('country'),
            'created_by' => $this->input->post('created_by'),
           
        );
    // check if image is attached
    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_ATTACH_PROGRAMME_IMAGE'
            )));
    }

    //image upload
    $image_url = $this->upload_image($_FILES["image"]['name'], "image", "programmes");
    $data['image'] = $image_url;

    if ($this->db->insert('programmes', $data)) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(200)
            ->set_output(json_encode(array(
                'success' => true,
                'message' => 'PROGRAMME_ADDED_SUCCESSFULLY'
            )));
    } else {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(200)
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'PROGRAMME_NOT_ADDED'
            )));

    }
    }


 
    // function to get programme by id

    public function get_programme($id)
    {
        // get programme by id code here
        // this later will have the performance metrics attached to the programme
        // annual perfomance
        // quarterly perfomances

        $programme = $this->db->where('id', $id)->get('programmes')->row();
        // fetch all the performance metrics for the programme
         // annual perfomance
        // quarterly perfomances

        //TODO: fetch all the performance metrics for the programme
        // annual perfomance
        // quarterly perfomances

        if ($programme != null) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(array(
                    'success' => true,
                    'programme' => $programme
                )));
        } else {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => 'PROGRAMME_NOT_FOUND'
                )));
        }
        
    }

    // function to edit programme
    
    public function edit_programme($id)
    {
        // edit programme code here
       
        $programme = $this->db->where('id', $id)->get('programmes')->row();

        if (($programme == null)) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => "PROGRAMME_NOT_FOUND",
                    
                )));
            
        }
        // edit programme
        $data = array(
            'title' => $this->input->post('title'),
            'description' => $this->input->post('description'),
            'duration' => $this->input->post('duration'),
            'country' => $this->input->post('country'),
            'created_by' => $this->input->post('created_by'),
           
        );
    // check if image is attached
    if (!empty($_FILES['image']['name'])) {
        $image_url = $this->upload_image($_FILES["image"]['name'], "image", "programmes");
        $data['image'] = $image_url;
         // first delete the old image file
         // explode the image url to get the image name then unlink /programes/old_image_name
         

    }
   
   
 

    if ($this->db->where('id', $id)->update('programmes', $data)) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(200)
            ->set_output(json_encode(array(
                'success' => true,
                'message' => 'PROGRAMME_UPDATED_SUCCESSFULLY'
            )));
    } else {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(200)
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'PROGRAMME_NOT_UPDATED'
            )));

    }

   
}
        


    // function to delete programme
    public function delete_programme($id)
    {
        
    }

    // function to get all programmes
    public function get_all_programmes()
    {
        
    }


    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'],
                'country' => $_POST['country'],
                'image'=>$image_url,
                'phone' => $_POST['phone'],
                'salutation' => $_POST['salutation'],
                'gender' => $_POST['gender'],
                '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 {

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

      // function to upload images
      public function upload_image($image_name, $field_name,$directory)
      {
  
          $config['upload_path'] = "./$directory/";
          $config['allowed_types'] = 'gif|jpg|png|jpeg';
          $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;
      }
    

}