<?php

defined('BASEPATH') OR exit('No direct script access allowed');

require APPPATH . '/libraries/REST_Controller.php';

/*
 * Changes:
 * 1. This project contains .htaccess file for windows machine.
 *    Please update as per your requirements.
 *    Samples (Win/Linux): http://stackoverflow.com/questions/28525870/removing-index-php-from-url-in-codeigniter-on-mandriva
 *
 * 2. Change 'encryption_key' in application\config\config.php
 *    Link for encryption_key: http://jeffreybarke.net/tools/codeigniter-encryption-key-generator/
 * 
 * 3. Change 'jwt_key' in application\config\jwt.php
 *
 */

class school_requirement extends REST_Controller
{
    /**
     * URL: http://localhost/CodeIgniter-JWT-Sample/auth/token
     * Method: GET
     */

     function __construct()
    {
        // Construct the parent class
        parent::__construct();
        $this->load->model('school_requirement_model');
        $this->load->library('aws_s3');
       
       
    }

    public function getFilterDistricts_get()
    {
        $result_data = $this->school_requirement_model->getFilterDistricts();
        if(count($result_data))
        {
               
                $data['dataStatus'] = true;
                $data['status'] = REST_Controller::HTTP_OK;
                $data['records'] = $result_data;
                $this->response($data,REST_Controller::HTTP_OK);
        }   
        else
        {
                $data['dataStatus'] = false;
                $data['status'] = REST_Controller::HTTP_NOT_FOUND;
                $data['msg'] = 'No Records Found!';
                $this->response($data,REST_Controller::HTTP_OK);
        }
    }

    public function getFilterSubjetcs_get()
    {
        $result_data = $this->school_requirement_model->selectCustomRecords(array('*'),array(),TEACHER_SUBJECTS);
        if(count($result_data))
        {
               
                $data['dataStatus'] = true;
                $data['status'] = REST_Controller::HTTP_OK;
                $data['records'] = $result_data;
                $this->response($data,REST_Controller::HTTP_OK);
        }   
        else
        {
                $data['dataStatus'] = false;
                $data['status'] = REST_Controller::HTTP_NOT_FOUND;
                $data['msg'] = 'No Records Found!';
                $this->response($data,REST_Controller::HTTP_OK);
        }
    }

    public function getFilterSchools_get()
    {
        $district_id = $this->uri->segment(2);//it may be district id or block id . distinguish by nxt param
        $filter_criteria = $this->uri->segment(3);//1 - filter by block ,empty means by district
        $result_data = $this->school_requirement_model->getFilterSchools($district_id,$filter_criteria);
        if(count($result_data))
        {
               
                $data['dataStatus'] = true;
                $data['status'] = REST_Controller::HTTP_OK;
                $data['records'] = $result_data;
                $this->response($data,REST_Controller::HTTP_OK);
        }   
        else
        {
                $data['dataStatus'] = false;
                $data['status'] = REST_Controller::HTTP_NOT_FOUND;
                $data['msg'] = 'No Records Found!';
                $this->response($data,REST_Controller::HTTP_OK);
        }
    }

     public function getFilterBlocks_get()
    {
        $district_id = $this->uri->segment(2);//echo $district_id;
        $result_data = $this->school_requirement_model->getFilterBlocks($district_id);
        if(count($result_data))
        {
               
                $data['dataStatus'] = true;
                $data['status'] = REST_Controller::HTTP_OK;
                $data['records'] = $result_data;
                $this->response($data,REST_Controller::HTTP_OK);
        }   
        else
        {
                $data['dataStatus'] = false;
                $data['status'] = REST_Controller::HTTP_NOT_FOUND;
                $data['msg'] = 'No Records Found!';
                $this->response($data,REST_Controller::HTTP_OK);
        }
    }

    public function getFilterMaterials_get()
    {
        $result_data = $this->school_requirement_model->getFilterMaterials();
        if(count($result_data))
        {
               
                $data['dataStatus'] = true;
                $data['status'] = REST_Controller::HTTP_OK;
                $data['records'] = $result_data;
                $this->response($data,REST_Controller::HTTP_OK);
        }   
        else
        {
                $data['dataStatus'] = false;
                $data['status'] = REST_Controller::HTTP_NOT_FOUND;
                $data['msg'] = 'No Records Found!';
                $this->response($data,REST_Controller::HTTP_OK);
        }
    }

    public function getSchoolReqList_post()
    {

        $from_date = $this->post('from_date') ? $this->post('from_date') : null;
        $end_date = $this->post('end_date') ? $this->post('end_date') : null;
        $schoold_id = $this->post('schoold_id') ? $this->post('schoold_id') : null;
        $district_id = $this->post('district_id') ? $this->post('district_id') : null;
        $mat_id = $this->post('mat_id') ? $this->post('mat_id') : null;
        $cat_id = $this->post('cat_id') ? $this->post('cat_id') : null;
        $is_featured = $this->post('is_featured') ? $this->post('is_featured') : null;

        $result_data = $this->school_requirement_model->getSchoolReqList($from_date,$end_date,$schoold_id,$district_id,$mat_id,$cat_id,$is_featured);
       // print_r($this->db->last_query());die();
        if(count($result_data))
        {


                //fetch s3 schoo url
                  foreach ($result_data as $key => $value) 
                  {
                     $folder_name = 'School_Profile/'.$value['school_id'].'_1.jpg';
                    // $folder_name = 'https://contribute.tnschools.gov.in/img/'.  .'.jpg';
                     //echo $key;
                     $result_data[$key]['img_url'] = $this->aws_s3->get_s3_url(SCHOOL_BUCKET_NAME,$folder_name);      
                     //echo $result_data[$key]['img_url'];die();
                  }  

                //send data                
                $data['dataStatus'] = true;
                $data['status'] = REST_Controller::HTTP_OK;
                $data['records'] = $result_data;
                $this->response($data,REST_Controller::HTTP_OK);
        }   
        else
        {
                $data['dataStatus'] = false;
                $data['status'] = REST_Controller::HTTP_NOT_FOUND;
                $data['msg'] = 'No Records Found!';
                $this->response($data,REST_Controller::HTTP_OK);
        }
    }

    public function getIndividualSchoolReqData_get()
    {

        
        $schoold_id = $this->uri->segment(2);
        //echo is_numeric($schoold_id);die();
        
        if($schoold_id != '')
        {
            $result_data = $this->school_requirement_model->getIndividualSchoolReqData($schoold_id);
           // print_r($result_data);die();

            //fetch s3 schoo url

            foreach ($result_data as $key => $value) 
            {
                $result_data[$key]['images'] = array();
                if($value['photo1'] != "" || $value['photo1'] != null)
                {
                    $result_data[$key]['images'][] = $this->getSchoolImages($value['photo1']);
                }
                if($value['photo2'] != "" || $value['photo2'] != null)
                {
                    $result_data[$key]['images'][] = $this->getSchoolImages($value['photo2']);
                }
                if($value['photo3'] != "" || $value['photo3'] != null)
                {
                    $result_data[$key]['images'][] = $this->getSchoolImages($value['photo3']);
                }
                if($value['photo4'] != "" || $value['photo4'] != null)
                {
                    $result_data[$key]['images'][] = $this->getSchoolImages($value['photo4']);
                }
                if($value['photo5'] != "" || $value['photo5'] != null)
                {
                    $result_data[$key]['images'][] = $this->getSchoolImages($value['photo2']);
                }
            }
            if(count($result_data))
            {
                   // if(is_numeric($schoold_id)){ $result_data[0]['images'] = $img_url; }
                    $data['dataStatus'] = true;
                    $data['status'] = REST_Controller::HTTP_OK;
                    $data['records'] = $result_data;
                    $this->response($data,REST_Controller::HTTP_OK);
            }   
            else
            {
                    $data['dataStatus'] = false;
                    $data['status'] = REST_Controller::HTTP_NOT_FOUND;
                    $data['msg'] = 'No Records Found!';
                    $this->response($data,REST_Controller::HTTP_OK);
            }
        }
        else
        {
                    $data['dataStatus'] = false;
                    $data['status'] = REST_Controller::HTTP_NOT_FOUND;
                    $data['msg'] = 'In appropriate API Call...!';
                    $this->response($data,REST_Controller::HTTP_OK);
        }
    }



    function getSchoolImages($photo1)
    {
                    $arr = explode("/",$photo1);
                    $key = count($arr) > 1 ? 'School_Profile/'.$arr[1] : 'School_Profile/'.$arr[0];
                    return $this->aws_s3->get_s3_url(null,$key);
    }
        
     public function csrContribute_post()
        {
            $records = $this->post('records');

            $contributions = isset($records['contributions']) ? $records['contributions'] : array();
            unset($records['contributions']);
            $master_id = null;
            // print_r($records);
            // echo $records['user_id'];die();
            if($records['id'] == "")
            {
                //echo 'INS';
                $master_id = $this->school_requirement_model->saveRecords($records,CSR_CONTRIBUTIONS);

              //  print_r($this->db->last_query());
                //die();
                if($master_id)
                {    
                   
                    if(count($contributions))
                    {
                        foreach ($contributions as $contribution_key => $contribution_value) 
                        {
                            $contribution_value['cont_id'] = $master_id;
                            $child_id = $this->school_requirement_model->saveRecords($contribution_value,CSR_CONTRIBUTION_DETAILS);
                        }
                    }
                }
            }
            else
            {
               
                $master_id = $this->school_requirement_model->updateRecords($records,CSR_CONTRIBUTIONS,array('id' => $records['id']));
                if($master_id)
                {
                     if(count($contributions))
                    {
                        foreach ($contributions as $contribution_key => $contribution_value) 
                        {
                            if($contribution_value['id'] == "")
                            {
                                $contribution_value['cont_id'] = $records['id'];
                                $child_id = $this->school_requirement_model->saveRecords($contribution_value,CSR_CONTRIBUTION_DETAILS);
                            }
                            else
                            {
                                 $child_id = $this->school_requirement_model->updateRecords($contribution_value,CSR_CONTRIBUTION_DETAILS,array('id' => $contribution_value['id']));
                            }
                        }
                    }
                }

            }

            if($master_id)
            {

                    $data['dataStatus'] = true;
                    $data['status'] = REST_Controller::HTTP_OK;
                    $data['records'] = $master_id;
                    $this->response($data,REST_Controller::HTTP_OK);
            }
            else
            {
                    $data['dataStatus'] = false;
                    $data['status'] = REST_Controller::HTTP_NOT_FOUND;
                    $data['msg'] = 'Something went wrong! Try later';
                    $this->response($data,REST_Controller::HTTP_OK);
            }
        }


        public function csrDashboardContent_get()
        {
            $res_data = $this->school_requirement_model->csrDashboardContent();

                    $data['dataStatus'] = true;
                    $data['status'] = REST_Controller::HTTP_OK;
                    $data['records'] = $res_data;
                    $this->response($data,REST_Controller::HTTP_OK);
        }

        public function getStatusUpdates_get()
        {
                    $req_id = $this->uri->segment(2);

                    $res_data = $this->school_requirement_model->getStatusUpdates($req_id);
                    if(count($res_data))
                    {
                        foreach ($res_data as $key => $value) 
                        {
                          if($value['img_url_1'])
                          {
                                $bucket_name = CSR_BUCKET_NAME;
                                $folder = 'csr_photos/req_'.$value['fk_req_id'].'/update_'.$value['id'].'/'.$value['img_url_1'];
                                $res_data[$key]['img_url_1'] = $this->aws_s3->get_s3_url($bucket_name,$folder);  
                          }
                          if($value['img_url_2'])
                          {
                                $bucket_name = CSR_BUCKET_NAME;
                                $folder = 'csr_photos/req_'.$value['fk_req_id'].'/update_'.$value['id'].'/'.$value['img_url_2'];
                                $res_data[$key]['img_url_2'] = $this->aws_s3->get_s3_url($bucket_name,$folder);  
                          }
                          if($value['img_url_3'])
                          {
                                $bucket_name = CSR_BUCKET_NAME;
                                $folder = 'csr_photos/req_'.$value['fk_req_id'].'/update_'.$value['id'].'/'.$value['img_url_3'];
                                $res_data[$key]['img_url_3'] = $this->aws_s3->get_s3_url($bucket_name,$folder);  
                          }
                        }
                    }

                    $data['dataStatus'] = true;
                    $data['status'] = REST_Controller::HTTP_OK;
                    $data['records'] = $res_data;
                    $this->response($data,REST_Controller::HTTP_OK);
        }

        public function csrKTContribute_post()
        {
           // echo $this->getRandomPwd();die();
            $records = $this->post('records');
            // $D = json_encode($records['volunteer_info'][0]['subject']);
            // var_dump($D);
            // die();

            $volunteer_info = isset($records['volunteer_info']) ? $records['volunteer_info'] : null;
            $books_info = isset($records['books_info']) ? $records['books_info'] : null;
            $devices_info = isset($records['devices_info']) ? $records['devices_info'] : null;
            unset($records['volunteer_info']);
            unset($records['books_info']);
            unset($records['devices_info']);
            
            $kt_id = null;
            if(!$records['fk_user_id'])
            {   
                //create new user
                $pwd = $this->getRandomPwd();
                 $user_data = array('name' => $records['name'],'email' => $records['email'],'mobile' => $records['mobile'],'password' => md5($pwd));
                 $user_id = $this->school_requirement_model->saveRecords($user_data,CSR_USER);
                 if($user_id)
                 {
                    
                    $records['fk_user_id'] = $user_id;

                    //send mail
                    $mail_configs = $this->school_requirement_model->selectCustomRecords(array('*'),array('mail_code' => 'REG2'),CSR_MAIL_CONTENTS);
                    if(count($mail_configs))
                    {
                     $fromMail = $mail_configs[0]['from_mail'];
                     $display_name = $mail_configs[0]['display_name'];
                     $subject = $mail_configs[0]['subject'];
                     $tomail = $records['email'];
                     $content = $mail_configs[0]['content'];
                     $content = str_replace('{{user}}',$records['name'],$content);
                     $content = str_replace('{{pwd}}',$pwd,$content);
                     $this->load->helper('mymail');
                     MYMAIL::sendmyMail($fromMail,$display_name, $tomail,$subject,$content);
                    }
                    
                 }
                 else
                 {
                    $data['dataStatus'] = false;
                    $data['status'] = REST_Controller::HTTP_NOT_FOUND;
                    $data['msg'] = 'Something went wrong! Try later';
                    $this->response($data,REST_Controller::HTTP_OK);
                 }
            }
            //unset all params other than table fields
             unset($records['name']); unset($records['email']); unset($records['mobile']);

            //make KT contrubute
            if($records['kt_id'])
            {
                  $kt_id =  $this->school_requirement_model->updateRecords($records,CSR_KT_CONTRIBUTIONS,array('kt_id' => $records['kt_id']));
                   if($kt_id)
                   {
                        if($records['con_type'] == 3 && $volunteer_info && count($volunteer_info))
                        {
                            foreach ($volunteer_info as $key => $value) 
                            {
                               
                                if($value['volunteer_info_id'])
                                {
                                     if(isset($value['subject']) && count($value['subject']))
                                     {
                                        $value['subject'] = json_encode($value['subject']);  

                                     }
                                     $info_id = $this->school_requirement_model->updateRecords($value,CSR_VOLUNTEER_INFO,array('fk_kt_id' => $value['fk_kt_id']));
                                }
                                else
                                {
                                    $value['fk_kt_id'] = $kt_id;
                                     if(isset($value['subject']) && count($value['subject']))
                                     {
                                        $value['subject'] = json_encode($value['subject']);  
                                     }

                                     $info_id = $this->school_requirement_model->saveRecords($value,CSR_VOLUNTEER_INFO);
                                }
                            } 
                        }
                   }
            }
            else
            {
                   $kt_id =  $this->school_requirement_model->saveRecords($records,CSR_KT_CONTRIBUTIONS);
                   if($kt_id)
                   {
                        if($records['con_type'] == 3 && $volunteer_info && count($volunteer_info))
                        {
                               
                            foreach ($volunteer_info as $key => $value) 
                            {
                            
                            
                                if($value['volunteer_info_id'])
                                {
                                      if(isset($value['subject']) && count($value['subject']))
                                     {
                                        $value['subject'] = json_encode($value['subject']);  

                                     }
                                     $info_id = $this->school_requirement_model->updateRecords($value,CSR_VOLUNTEER_INFO,array('fk_kt_id' => $value['fk_kt_id']));
                                }
                                else
                                {
                                      if(isset($value['subject']) && count($value['subject']))
                                     {
                                        $value['subject'] = json_encode($value['subject']);  

                                     }
                                    $value['fk_kt_id'] = $kt_id;
                                     $info_id = $this->school_requirement_model->saveRecords($value,CSR_VOLUNTEER_INFO);
                                }
                            }
                        }
                        else if($records['con_type'] == 1 && $books_info && count($books_info))//books
                        {
                            foreach ($books_info as $books_info_key => $books_info_value) 
                            {
                               if($books_info_value['id'])
                               {
                                  //update  
                               }
                               else
                               {
                                    $books_info_value['kt_con_id'] = $kt_id;
                                    $this->school_requirement_model->saveRecords($books_info_value,CSR_KT_BOOKS);
                               }
                            }
                        }
                        else if($records['con_type'] == 2 && $devices_info && count($devices_info))
                        {
                            foreach ($devices_info as $devices_info_key => $devices_info_value) 
                            {
                               if($devices_info_value['id'])
                               {
                                  //update  
                               }
                               else
                               {
                                    $devices_info_value['kt_con_id'] = $kt_id;
                                    $this->school_requirement_model->saveRecords($devices_info_value,CSR_KT_DEVICES);
                               }
                            }
                        }
                   }
            }


            if($kt_id)
            {
                    $data['dataStatus'] = true;
                    $data['status'] = REST_Controller::HTTP_OK;
                    $data['records'] = $kt_id;
                    $this->response($data,REST_Controller::HTTP_OK);
            }
            else
            {
                    $data['dataStatus'] = false;
                    $data['status'] = REST_Controller::HTTP_NOT_FOUND;
                    $data['msg'] = 'Something went wrong! Try later';
                    $this->response($data,REST_Controller::HTTP_OK);
            }
        }

        public function getRandomPwd()
        {
                        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                        $charactersLength = strlen($characters);
                        $randomString = '';
                        for ($i = 0; $i < 8; $i++) {
                            $randomString .= $characters[rand(0, $charactersLength - 1)];
                        }
                       return $randomString;
        }

         public function getSchoolHMInfo_get()
        {
                $school_id = $this->uri->segment(2);        
                
                $hm_info = $this->school_requirement_model->getSchoolHMInfo($school_id);       
                if(count($hm_info))
                {
                    $data['dataStatus'] = true;
                    $data['status'] = REST_Controller::HTTP_OK;
                    $data['records'] = $hm_info;
                    $this->response($data,REST_Controller::HTTP_OK);
                }
                else
                {
                    $data['dataStatus'] = false;
                    $data['status'] = REST_Controller::HTTP_NOT_FOUND;
                    $data['msg'] = 'No Teachers data found for this school!';
                    $this->response($data,REST_Controller::HTTP_OK);
                }

        }

        public function getAllSchoolRequirementUpdates_get()
        {
            $school_id = $this->uri->segment(2); 
            $res_data = $this->school_requirement_model->getAllSchoolRequirementUpdates($school_id);
            
            
            if(count($res_data))
            {
                
                    foreach ($res_data as $key => $value) 
                        {
                          if($value['img_url_1'])
                          {
                                $bucket_name = CSR_BUCKET_NAME;
                                $folder = 'csr_photos/req_'.$value['fk_req_id'].'/update_'.$value['id'].'/'.$value['img_url_1'];
                                $res_data[$key]['img_url_1'] = $this->aws_s3->get_s3_url($bucket_name,$folder);  
                          }
                          if($value['img_url_2'])
                          {
                                $bucket_name = CSR_BUCKET_NAME;
                                $folder = 'csr_photos/req_'.$value['fk_req_id'].'/update_'.$value['id'].'/'.$value['img_url_2'];
                                $res_data[$key]['img_url_2'] = $this->aws_s3->get_s3_url($bucket_name,$folder);  
                          }
                          if($value['img_url_3'])
                          {
                                $bucket_name = CSR_BUCKET_NAME;
                                $folder = 'csr_photos/req_'.$value['fk_req_id'].'/update_'.$value['id'].'/'.$value['img_url_3'];
                                $res_data[$key]['img_url_3'] = $this->aws_s3->get_s3_url($bucket_name,$folder);  
                          }
                        }

                    $data['dataStatus'] = true;
                    $data['status'] = REST_Controller::HTTP_OK;
                    $data['records'] = $res_data;
                    $this->response($data,REST_Controller::HTTP_OK);        
                
            }
            else
            {
                    $data['dataStatus'] = false;
                    $data['status'] = REST_Controller::HTTP_NOT_FOUND;
                    $data['msg'] = 'No updates data found!';
                    $this->response($data,REST_Controller::HTTP_OK);
            }
        }


   
    

}