<?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 getFilterSchools_get()
    {
        $district_id = $this->uri->segment(2);//echo $district_id;
        $result_data = $this->school_requirement_model->getFilterSchools($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);
        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($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($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);

                    $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');
            //print_r($records);
            $volunteer_info = isset($records['volunteer_info']) ? $records['volunteer_info'] : null;
            unset($records['volunteer_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'])
                                {
                                     $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;
                                     $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'])
                                {
                                     $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;
                                     $info_id = $this->school_requirement_model->saveRecords($value,CSR_VOLUNTEER_INFO);
                                }
                            }
                        }
                   }
            }


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


   
    

}