<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Admin 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_tourist_attraction()
    {
       
        $check_name =   $this->db->get_where('tourist_attraction', array("title" => $_POST['title']))->row();

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

            $config['upload_path'] = './tourist_attractions/';  
            $config['allowed_types'] = 'gif|jpg|png|jpeg';  
            $new_name = time() . '-' . $_FILES["image"]['name']; 
            $config['file_name'] = $new_name; 

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

            if (!$this->upload->do_upload('image') && !empty($_FILES['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()."tourist_attractions/".$upload_data['file_name'];
           

            $data = array(
                "title" => $_POST['title'],
                "description" => $_POST['description'],
                'image' => $image_url,
                'date_created' => time()
            );
            if ($this->db->insert('tourist_attractions', $data)) {
                return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(200)
                    ->set_output(json_encode(array(
                        'success' => true,
                        'message' => 'tourist attraction added successfully'
                    )));
            } else {
                return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(200)
                    ->set_output(json_encode(array(
                        'success' => false,
                        'message' => 'tourist attraction not added successfully'
                    )));
            }
        }
    }

    public function get_tourist_attraction($id)
    {
        $this->db->select('id,title,description,image');
        $this->db->where('id', $id);
        $tourist_attraction = $this->db->get('tourist_attractions');

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

    public function get_tourist_attractions()
    {
        $this->db->select('*');
        $this->db->from('tourist_attractions');
        $query = $this->db->get();

        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(200)
            ->set_output(json_encode(array(
                'success' => true,
                'tourist_attractions' => $query->result_array()
            )));
    }
  
    public function edit_tourist_attraction($id)
    {

        $tourist_attraction = $this->db->get_where('tourist_attraction', array('id' => $id))->row();
        if($tourist_attraction == null){
            return $this->output
            ->set_content_type('application/json')
            ->set_status_header(200)
            ->set_output(json_encode(array(
                'success' => false,
                'message' => "tourist_attraction of id $id not found"
            )));
        }


            if (!empty($_FILES['image']['name'])) {
                $config['upload_path'] = './tourist_attractions/';

                $config['allowed_types'] = 'gif|jpg|png|jpeg';


                // $config['max_size'] = 0;    


                $new_name = time() . '-' . $_FILES["image"]['name'];

                //Added time function in image name for no duplicate image 

                $config['file_name'] = $new_name;

                //Stored the new name into $config['file_name']

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


                if (!$this->upload->do_upload('image') && !empty($_FILES['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
                        ));
                } else {

                    //got the tourist_attraction using its id
                    $tourist_attraction = $this->db->get_where('tourist_attractions', array('id' => $id))->row();
                    // exploded the url which is like "http://api-url/categories/image.jpg"
                    if ($tourist_attraction->image != null) {
                        $old_image_file_name = explode("tourist_attractions/", $tourist_attraction->image)[1];
                        $old_image_location = "tourist_attractions/" . $old_image_file_name;
                        // first check if the file 
                        if (file_exists($old_image_location)) {
                            // if it exists delete it
                            unlink($old_image_location);
                        } else {
                            return $this->output
                                ->set_content_type('application/json')
                                ->set_status_header(200)
                                ->set_output(json_encode(array(
                                    'success' => false,
                                    'message' => 'old image not found, failed to be deleted'
                                )));
                        }
                    }

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

                    $image_url =  base_url()."tourist_attractions/".$upload_data['file_name'];

                    $data = array(

                        'image' => $image_url,
                        'title' => $_POST['title'],
                        'description' => $_POST['description']
                    );
                }
            } else {
               
            // if no file was passed
            // on text info is passed to update



            $data = array(

                'title' => $_POST['title'],
                'description' => $_POST['description'],
                //could put here the last update time like 'last_update'=>time()

            );
        }

        // now update the data

        $this->db->set($data);
        $this->db->where('id', $id);
        if ($this->db->update('tourist_attractions', $data)) {

            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(array(
                    'success' => true,
                    'message' => 'tourist_attraction edited successfully'
                )));
        } else {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => 'something wrong happened'
                )));
        }
    }

    public function delete_tourist_attraction($id)
    {
        if ($this->input->method() != 'delete') {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => 'wrong request method used'
                )));
        }

        $tourist_attraction = $this->db->get_where('tourist_attractions', array('id' => $id))->row();
        if ($tourist_attraction == null) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => 'tourist_attraction not found'
                )));
        }
        // else delete
        $this->db->where('id', $id);
        if ($this->db->delete('tourist_attractions')) {
            
            // delete / unlink the old tourist_attraction
            $tourist_attraction_location = 'tourist_attractions/' . explode('tourist_attractions/', $tourist_attraction->image)[1];

            if (file_exists($tourist_attraction_location)) {
                // if it exists delete it
                unlink($tourist_attraction_location);
                return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(200)
                    ->set_output(json_encode(array(
                        'success' => true,
                        'message' => 'tourist_attraction deleted successfully'
                    )));
            } else {
                return $this->output
                    ->set_content_type('application/json')
                    ->set_status_header(200)
                    ->set_output(json_encode(array(
                        'success' => true,
                        'message' => 'tourist_attraction not found, failed to be delete tourist_attraction file, but deleted tourist_attraction information'
                    )));
            }
        } else {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(array(
                    'success' => true,
                    'message' => 'tourist_attraction not deleted'
                )));
        }
    }



// gallarey trip

public function add_gallery_trip()
{
   
    $check_name =   $this->db->get_where('gallery_trips', array("caption" => $_POST['caption']))->row();

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

        $config['upload_path'] = './gallery_trips/';  
        $config['allowed_types'] = 'gif|jpg|png|jpeg';  
        $new_name = time() . '-' . $_FILES["image"]['name']; 
        $config['file_name'] = $new_name; 

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

        if (!$this->upload->do_upload('image') && !empty($_FILES['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()."gallery_trips/".$upload_data['file_name'];
       

        $data = array(
            "caption" => $_POST['caption'],
            'image' => $image_url,
            'date_created' => time()
        );
        if ($this->db->insert('gallery_trips', $data)) {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(array(
                    'success' => true,
                    'message' => 'gallery_trip added successfully'
                )));
        } else {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(array(
                    'success' => false,
                    'message' => 'gallery_trip not added successfully'
                )));
        }
    }
}

public function get_gallery_trip($id)
{
    $this->db->select('id,caption,image');
    $this->db->where('id', $id);
    $gallery_trip = $this->db->get('gallery_trips');

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

public function get_gallery_trips()
{
    $this->db->select('*');
    $this->db->from('gallery_trips');
    $query = $this->db->get();

    return $this->output
        ->set_content_type('application/json')
        ->set_status_header(200)
        ->set_output(json_encode(array(
            'success' => true,
            'gallery_trips' => $query->result_array()
        )));
}

public function edit_gallery_trip($id)
{

    $gallery_trip = $this->db->get_where('gallery_trips', array('id' => $id))->row();
    if($gallery_trip == null){
        return $this->output
        ->set_content_type('application/json')
        ->set_status_header(200)
        ->set_output(json_encode(array(
            'success' => false,
            'message' => "gallery_trip of id $id not found"
        )));
    }


        if (!empty($_FILES['image']['name'])) {
            $config['upload_path'] = './gallery_trips/';

            $config['allowed_types'] = 'gif|jpg|png|jpeg';


            // $config['max_size'] = 0;    


            $new_name = time() . '-' . $_FILES["image"]['name'];

            //Added time function in image name for no duplicate image 

            $config['file_name'] = $new_name;

            //Stored the new name into $config['file_name']

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


            if (!$this->upload->do_upload('image') && !empty($_FILES['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
                    ));
            } else {

                //got the gallery_trip using its id
                $gallery_trip = $this->db->get_where('gallery_trips', array('id' => $id))->row();
                // exploded the url which is like "http://api-url/categories/image.jpg"
                if ($gallery_trip->image != null) {
                    $old_image_file_name = explode("gallery_trips/", $gallery_trip->image)[1];
                    $old_image_location = "gallery_trips/" . $old_image_file_name;
                    // first check if the file 
                    if (file_exists($old_image_location)) {
                        // if it exists delete it
                        unlink($old_image_location);
                    } else {
                        return $this->output
                            ->set_content_type('application/json')
                            ->set_status_header(200)
                            ->set_output(json_encode(array(
                                'success' => false,
                                'message' => 'old image not found, failed to be deleted'
                            )));
                    }
                }

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

                $image_url =  base_url()."gallery_trips/".$upload_data['file_name'];

                $data = array(

                     "caption" => $_POST['caption'],
                    'image' => $image_url,
                    'date_created' => time()
                );
            }
        } else {
           
       


        $data = array(

            "caption" => $_POST['caption'],
           

        );
    }

    // now update the data

    $this->db->set($data);
    $this->db->where('id', $id);
    if ($this->db->update('gallery_trips', $data)) {

        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(200)
            ->set_output(json_encode(array(
                'success' => true,
                'message' => 'gallery_trip edited successfully'
            )));
    } else {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(200)
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'something wrong happened'
            )));
    }
}

public function delete_gallery_trip($id)
{
    if ($this->input->method() != 'delete') {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(200)
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'wrong request method used'
            )));
    }

    $gallery_trip = $this->db->get_where('gallery_trips', array('id' => $id))->row();
    if ($gallery_trip == null) {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(200)
            ->set_output(json_encode(array(
                'success' => false,
                'message' => 'gallery_trip not found'
            )));
    }
    // else delete
    $this->db->where('id', $id);
    if ($this->db->delete('gallery_trips')) {
        
        // delete / unlink the old gallery_trip
        $gallery_trip_location = 'gallery_trips/' . explode('gallery_trips/', $gallery_trip->image)[1];

        if (file_exists($gallery_trip_location)) {
            // if it exists delete it
            unlink($gallery_trip_location);
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(array(
                    'success' => true,
                    'message' => 'gallery_trip deleted successfully'
                )));
        } else {
            return $this->output
                ->set_content_type('application/json')
                ->set_status_header(200)
                ->set_output(json_encode(array(
                    'success' => true,
                    'message' => 'gallery_trip not found, failed to be delete gallery_trip file, but deleted gallery_trip information'
                )));
        }
    } else {
        return $this->output
            ->set_content_type('application/json')
            ->set_status_header(200)
            ->set_output(json_encode(array(
                'success' => true,
                'message' => 'gallery_trip not deleted'
            )));
    }
}



}
