<?php

namespace App\Controllers;
use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\API\ResponseTrait;

class Mylistings extends BaseController
{
    use ResponseTrait;

    public function mylistings($return_data = false)
    {
        $data = array();

        $listingModel = model('App\Models\ListingModel');
        $fieldModel = model('App\Models\FieldModel');
        $treeModel = model('App\Models\TreefieldModel');
        $userModel = model('App\Models\UserModel');
        $tokenModel = model('App\Models\TokenModel');
        $favoriteModel = model('App\Models\FavoriteModel');

        // [Check Token]
        
        $user_id = NULL;

        if(!empty($_GET['token']))
        {
            $token = $_GET['token'];

            $user_token = $tokenModel->where('token', $token)->findAll(1);

            if(count($user_token) > 0)
            {
                $user_id = $user_token[0]['user_id'];

                $data['token'] = array(
                    'token' => $user_token[0]['token'],
                    'user_id' =>  $user_id,
                    'expire_date' =>  date('Y-m-d H:i:s', strtotime($user_token[0]['date_last_access']." +2 months")),
                    'user_email' =>  $user_token[0]['username'],
                );
            }
        }

        // [/Check Token]

        $offset = 0;
        $where = array();
        $user_check = TRUE;
        $show_other_agents_litings = FALSE;
        $order_by = 'id DESC';

        $limit = 10;
        if(isset($_GET['per_page']))
            $limit = $_GET['per_page'];

        if(isset($_GET['paged']))
            $offset = $limit*$_GET['paged'];

        if(isset($_GET['search']))
            $_GET['field_search'] = $_GET['search'];

        if(isset($_GET['is_featured']))
            $order_by = 'is_featured DESC, counter_views DESC';

        if(isset($_GET['field_search']) && !empty($_GET['field_search']))
            $where['search_values LIKE \'%'.$_GET['field_search'].'%\''] = NULL;

        if(isset($_GET['search_location']))
            $_GET['location_id'] = $_GET['search_location'];

        if(isset($_GET['search_category']))
            $_GET['category_id'] = $_GET['search_category'];

        // Purpose
        if(isset($_GET['field_5']))
        {
            $where['field_4'] = $_GET['field_5'];
        }

        // By post id
        if(isset($_GET['field_post_id']))
        {
            $where['property.id'] = $_GET['field_post_id'];
        }

        if(isset($_GET['location_id']) && !empty($_GET['location_id']))
        {
            $search_location = '';

            // get name by id
            $tree_search = $treeModel->where('language_id', getenv('LANGUAGE_ID'))
                                       ->where('field_id', 64)
                                       ->where('treefield_id', $_GET['location_id'])                          
                                       ->findAll();

            if(count($tree_search) > 0)
            {
                $search_location = $tree_search[0]['value'];
            }
            else
            {
                $search_location = 'LOCATION_NOT_EXISTS';
            }

            if(!empty($search_location))
                $where['json_object LIKE \'%'.$search_location.' -%\''] = NULL;
        }

        if(isset($_GET['category_id']) && !empty($_GET['category_id']))
        {
            $search_category = '';

            // get name by id
            $tree_search = $treeModel->where('language_id', getenv('LANGUAGE_ID'))
                                       ->where('field_id', 79)
                                       ->where('treefield_id', $_GET['category_id'])                          
                                       ->findAll();

            if(count($tree_search) > 0)
            {
                $search_category = $tree_search[0]['value'];
            }
            else
            {
                $search_category = 'CATEGORY_NOT_EXISTS';
            }

            if(!empty($search_category))
                $where['json_object LIKE \'%'.$search_category.' -%\''] = NULL;
        } 

        // Sale price
        if(isset($_GET['field_6_min']))
        {
            $where['field_36_int > '.intval($_GET['field_6_min'])] = NULL;
        }

        if(isset($_GET['field_6_max']))
        {
            $where['field_36_int < '.intval($_GET['field_6_max'])] = NULL;
        }

        // Rent price
        if(isset($_GET['field_7_min']))
        {
            $where['field_37_int > '.intval($_GET['field_7_min'])] = NULL;
        }

        if(isset($_GET['field_7_min']))
        {
            $where['field_37_int < '.intval($_GET['field_7_max'])] = NULL;
        }

        // Washer
        if(isset($_GET['field_29']) && $_GET['field_29']=='1')
        {
            $where['json_object LIKE \'%field_25":"true%\''] = NULL;
        }

        // Fireplace
        if(isset($_GET['field_33']) && $_GET['field_33']=='1')
        {
            $where['json_object LIKE \'%field_27":"true%\''] = NULL;
        }

        // Refrigator
        if(isset($_GET['field_37']) && $_GET['field_37']=='1')
        {
            $where['json_object LIKE \'%field_22":"true%\''] = NULL;
        }

        // filter by agents
        if(isset($_GET['search_agents_ids']) && !empty($_GET['search_agents_ids']))
        {
            $where['user_id'] = $_GET['search_agents_ids'];
        }

        if(!empty($user_id) && isset($_GET['is_favorite']))
        {
            $where['favorites.id > 0'] = NULL;
        }

        $fields = $fieldModel->where('language_id', getenv('LANGUAGE_ID'))->findAll();

        $listings = $listingModel->where('language_id', getenv('LANGUAGE_ID'))->orderBy($order_by)->get_pagination($limit, $offset, $where, $user_check, $user_id, $show_other_agents_litings);

        if(getenv('CI_ENVIRONMENT') == 'development')
            $data['sql'] = (string) $listingModel->getLastQuery();

        $data['listings_count'] = ''.count($listings);

        $data['listings'] = array();

        // prepare/modify results
        foreach($listings as $listing)
        {
            $n_listing = array();
            $n_listing['post_id'] = $listing['property_id'];
            $n_listing['idlisting'] = $listing['property_id'];
            $n_listing['address'] = $listing['address'];
            $n_listing['lat'] = $listing['lat'];
            $n_listing['lng'] = $listing['lng'];
            $n_listing['is_activated'] = $listing['is_visible'];
            $n_listing['is_favorite'] = 'null';

            if($user_id !== NULL)
            {
                $favorites = $favoriteModel->where('property_id', $listing['id'])
                              ->where('user_id', $user_id)
                              ->where('lang_code', getenv('LANG_CODE'))->findAll(1);

                if(count($favorites) > 0)
                    $n_listing['is_favorite'] = '1';
            }

            $n_listing['guid'] = getenv('WEBSITE_URL').'index.php/'.getenv('LISTING_URI').'/'.$listing['id'];

            $n_listing['listing_images_path_medium'] = '';
            $n_listing['listing_images_path'] = '';
            if(isset($listing['image_repository']))
            {
                $images_paths = json_decode($listing['image_repository']);

                foreach($images_paths as $key=>$path)
                {
                    if(file_exists(getenv('FILES_DIRECTORY').'strict_cache/851x678'.$path))
                    {
                        $images_paths[$key] = 'strict_cache/851x678'.$path;
                    }
                }

                $n_listing['listing_images_path_medium'] = join(',', $images_paths);
                $n_listing['listing_images_path'] = join(',', $images_paths);
                
            }

            // Agent info

            $n_listing['agent_exists'] = '0';

            $users = $userModel->where('property_id', $listing['id'])->findAllListing(1);

            if(count($users) > 0)
            {
                $user = $users[0];

                $n_listing['avatar_url'] = '';

                $n_listing['agent_exists'] = '1';

                $n_listing['profile_display_name'] = $user['name_surname'];
                $n_listing['profile_email'] = $user['mail'];
                $n_listing['profile_url'] = getenv('WEBSITE_URL').'index.php/profile/'.$user['id'];

                if(!empty($user['image_user_filename']))
                    $n_listing['avatar_url'] = getenv('WEBSITE_URL').'files/'.$user['image_user_filename'];

                $n_listing['wdk_phone'] = $user['phone'];
                $n_listing['wdk_facebook'] = $user['facebook_link'];
                $n_listing['wdk_linkedin'] = $user['linkedin_link'];
                $n_listing['wdk_instagram'] = '';
                $n_listing['wdk_telegram'] = '';
                $n_listing['wdk_twitter'] = $user['twitter_link'];
            }

            $json_object = json_decode($listing['json_object']);

            $n_listing['post_title'] = '';
            if(isset($json_object->{"field_10"}))
                $n_listing['post_title'] = $json_object->{"field_10"};

            $n_listing['location_name'] = '';
            if(isset($json_object->{"field_7"}))
                $n_listing['location_name'] = $json_object->{"field_7"};

            foreach($fields as $field)
            {
                if($field['type'] == 'HTMLTABLE')continue;
                if($field['type'] == 'PEDIGREE')continue;
                if($field['type'] == 'UPLOAD')continue;

                $value = '';

                if(isset($json_object->{"field_".$field['id']}))
                {
                    $value = $json_object->{"field_".$field['id']};

                    if($field['type'] == 'TEXTAREA')
                    {
                        $value = strip_tags($value);
                        $value = str_replace('&amp;', '&', $value);
                    }

                    if($field['type'] == 'TREE' && strlen($value) > 2)
                    {
                        $value = substr($value,0, -2);

                        $tree_search = $treeModel->where('language_id', getenv('LANGUAGE_ID'))
                                                ->where('field_id', $field['id'])
                                                ->where('value', $value)                          
                                                ->findAll();

                        if(count($tree_search) > 0 && !empty($tree_search[0]['treefield_id']))
                        {
                            $trefield_id = $tree_search[0]['treefield_id'];

                            if($field['id'] == getenv('CATEGORY_FIELD_ID'))
                            {
                                $n_listing['category_id'] = $trefield_id; //79
                            }
                            elseif($field['id'] == getenv('LOCATION_FIELD_ID'))
                            {
                                $n_listing['location_id'] = $trefield_id;  //64
                            }
                        }
                    }

                    if($value == '-')
                        $value = '';
                }

                if($value === true || $value === 'true')
                    $value = '1';

                if($value === false || $value === 'false')
                    $value = '0';

                if(!empty($value))
                    $n_listing['field_'.$field['id'].'_'.$field['type']] = $value;

                if($field['type'] == 'INPUTBOX' && !empty($value))
                {
                    $n_listing['field_'.$field['id'].'_NUMBER'] = $value;
                }
                    
            }

            $n_listing['post_content_stripped'] = '';
            if(!empty($json_object->{"field_17"}))
                $n_listing['post_content_stripped'] = strip_tags($json_object->{"field_17"});

            $n_listing['post_content'] = '';
                if(!empty($json_object->{"field_17"}))
                    $n_listing['post_content'] = $json_object->{"field_17"};

            $data['listings'][] = $n_listing;
        }

        if($return_data)
            return $data;

        return $this->respond($data);
    }

    public function edit_listing()
    {
        $data = array(
            'code'	    => 'empty_code',
            'message'   => 'Empty Message'
        );

        $data_json = $this->request->getJSON();

        // Mapping fields
        if(isset($data_json->post_title))
            $data_json->{'field_'.getenv('TITLE_FIELD_ID')} = $data_json->post_title;
        if(isset($data_json->post_content))
            $data_json->{'field_'.getenv('CONTENT_FIELD_ID')} = $data_json->post_content;

        $db = \Config\Database::connect();
        $listingModel = model('App\Models\ListingModel');
        $userModel = model('App\Models\UserModel');
        $favoriteModel = model('App\Models\FavoriteModel');
        $tokenModel = model('App\Models\TokenModel');
        $treeModel = model('App\Models\TreefieldModel');
        $fieldModel = model('App\Models\FieldModel');

        // [Check Token]

        if(empty($_GET['token']))
        {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => 'Token missing'
            ));
        }

        $token = $_GET['token'];

        $user_token = $tokenModel->where('token', $token)->findAll(1);

        if(count($user_token) == 0)
        {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => 'Valid Token missing'
            ));
        }

        $user_id = $user_token[0]['user_id'];

        // [/Check Token]

        $fields = $fieldModel->where('language_id', getenv('LANGUAGE_ID'))
                             ->where('is_frontend', '1')->findAll();

        $rules = array(
            array(
                'field' => 'post_title',
                'label' => __('Title', 'wpdirectorykit'),
                'rules' => 'required'
            ),
            array(
                'field' => 'post_content',
                'label' => __('Content', 'wpdirectorykit'),
                'rules' => 'required'
            ),
            array(
                'field' => 'category_id',
                'label' => __('Category', 'wpdirectorykit'),
                'rules' => ''
            ),
            array(
                'field' => 'location_id',
                'label' => __('Location', 'wpdirectorykit'),
                'rules' => ''
            ),
            array(
                'field' => 'is_activated',
                'label' => __('Is Activated', 'wpdirectorykit'),
                'rules' => ''
            ),
            array(
                'field' => 'lat',
                'label' => __('lat', 'wpdirectorykit'),
                'rules' => ''
            ),
            array(
                'field' => 'address',
                'label' => __('Address', 'wpdirectorykit'),
                'rules' => ''
            ),
            array(
                'field' => 'lng',
                'label' => __('lng', 'wpdirectorykit'),
                'rules' => ''
            ),
            array(
                'field' => 'listing_images',
                'label' => __('Listing images', 'wpdirectorykit'),
                'rules' => ''
            ),
            array(
                'field' => 'listing_plans_documents',
                'label' => __('Listing plans and documents', 'wpdirectorykit'),
                'rules' => ''
            ),
        );

        $prepared_rules = array();
        foreach($rules as $key=>$rule)
        {
            if(!empty($rule['rules']))
            {
                $prepared_rules[$rule['field']] = $rule;
            }
            elseif(empty($data_json->{$rule['field']}))
            {
                $data_json->{$rule['field']} = '';
            }
        }

        foreach($fields as $item)
        {
            if($item['type'] == 'CATEGORY')
                $item['type'] = 'SECTION';

            if($item['type'] == 'SECTION')
                continue;

            $item['idfield'] = $item['id'];
            $item['field_type'] = $item['type'];
            $item['field_label'] = $item['option'];
            $item['values_list'] = $item['values'];

            if(empty($item['columns_number']))
                $item['columns_number'] = '12';

            $new_rules = array();

            if(!empty($item['is_required']))
                $new_rules[] = 'required';

            if($item['id'] == getenv('TITLE_FIELD_ID') ||
               $item['id'] == getenv('CONTENT_FIELD_ID'))
            {
                $new_rules = array();
            }

            if(!empty($item['max_length']))
                $new_rules[] = 'max_length['.$item['max_length'].']';

            $new_rule = join('|', $new_rules);

            if(!empty($new_rule))
            $prepared_rules['field_'.$item['idfield']] = 
                array(
                    'field' => 'field_'.$item['idfield'],
                    'label' => $item['field_label'],
                    'rules' => $new_rule
                );

            if(empty($new_rule))
            {
                if(empty($data_json->{'field_'.$item['idfield']}))
                {
                    $data_json->{'field_'.$item['idfield']} = '';
                }
            }
        }

        if(!empty($data_json->post_id))
        {
            $listing_post_id = intval($data_json->post_id);
    
            $listings = $listingModel->where('property.id', $listing_post_id)
                                     ->where('language_id', getenv('LANGUAGE_ID'))
                                     ->findAll(1);

            if(count($listings) == 0)
            {
                return $this->respond(array(
                    'code'	    => 'failed',
                    'message'   => 'Listing id not found'
                ));
            }

            $listing_db_data = $listings[0];

            $builder = $db->table('property_user');
            $builder->where('user_id', $user_id);
            $builder->where('property_id', $listing_post_id);
            $query = $builder->get(1);
            $user_detected = $query->getResultArray();

            if(count($user_detected) == 0)
            {
                return $this->respond(array(
                    'code'	    => 'failed',
                    'message'   => __('Token missing permissions', 'wpdirectorykit')
                ));
            }
        }

        $validation = \Config\Services::validation();

        $validation->setRules($prepared_rules);

        // request customize

        if ($validation->withRequest($this->request)->run()) {
            // validation successfuly

            // Saving proccess
            $data = [
                'gps' => '',
                'lat' => '',
                'lng' => '',
                'date' => date('Y-m-d H:i:s'),
                'date_modified' => date('Y-m-d H:i:s'),
                'address' => $data_json->address,
                'search_values' => join(',', (array) $data_json),
                'is_visible' => $data_json->is_activated,
                'is_activated' => '0',
            ];

            // try autopopulate ocoordinates
            $gps_array = get_gps($data_json->address);
            if($gps_array !== FALSE)
            {
                $data['gps'] = $gps_array['lat'].', '.$gps_array['lng'];
                $data['lat'] = $gps_array['lat'];
                $data['lng'] = $gps_array['lng'];
            }

            if(empty($listing_db_data))
            {
                $listing_id = $listingModel->insert($data);
            }
            else
            {
                $listing_updated = $listingModel->update($listing_db_data['id'], $data);

                $listing_id = $listing_post_id;
            }
            

            if(empty($listing_id))
            {
                return $this->respond(array(
                    'code'	    => 'failed',
                    'message'   => 'Insertion listing_id failed'
                ));
            }

            $data['post_id'] = $listing_id;

            // Mapping fields

            if(isset($data_json->category_id) && getenv('CATEGORY_FIELD_ID') > 0)
            {
                // get name by id
                $tree_search = $treeModel->where('language_id', getenv('LANGUAGE_ID'))
                            ->where('field_id', getenv('CATEGORY_FIELD_ID'))
                            ->where('treefield_id', $data_json->category_id)                          
                            ->findAll();


                if(count($tree_search) > 0)
                {
                    $detected_value = $tree_search[0]['value'];

                    $data_json->{"field_".getenv('CATEGORY_FIELD_ID')} = $detected_value.' -';
                }
            }

            if(isset($data_json->location_id) && getenv('LOCATION_FIELD_ID') > 0)
            {
                // get name by id
                $tree_search = $treeModel->where('language_id', getenv('LANGUAGE_ID'))
                            ->where('field_id', getenv('LOCATION_FIELD_ID'))
                            ->where('treefield_id', $data_json->location_id)                          
                            ->findAll();


                if(count($tree_search) > 0)
                {
                    $detected_value = $tree_search[0]['value'];

                    $data_json->{"field_".getenv('LOCATION_FIELD_ID')} = $detected_value.' -';
                }
            }

            //property_user

            $builder = $db->table('property_user');
            $builder->where('user_id', $user_id);
            $builder->where('property_id', $listing_id);
            $builder->delete();

            $builder = $db->table('property_user');
            $insert_id = $builder->insert(['user_id' => $user_id, 'property_id' => $listing_id]);

            if(empty($insert_id))
            {
                return $this->respond(array(
                    'code'	    => 'failed',
                    'message'   => 'Insertion property_user failed'
                ));
            }

            //property_value

            $builder = $db->table('property_value');
            $builder->where('property_id', $listing_id);
            $builder->where('language_id', getenv('LANGUAGE_ID'));
            $builder->delete();

            foreach((array) $data_json as $field_key => $value)
            {
                if(empty($value))continue;

                if(substr($field_key, 0, 6) == 'field_')
                {
                    $field_id = substr($field_key, 6);

                    if(empty($field_id))continue;

                    $builder = $db->table('property_value');
                    $builder->insert(
                        [
                            'language_id' => getenv('LANGUAGE_ID'), 
                            'property_id' => $listing_id,
                            'option_id' => $field_id,
                            'value' => $value,
                            'value_num' => is_numeric($value)?$value:'',
                        ]);
                }
            }

            //property_lang

            $builder = $db->table('property_lang');
            $builder->where('property_id', $listing_id);
            $builder->where('language_id', getenv('LANGUAGE_ID'));
            $builder->delete();

            $data_insert = [
                'language_id' => getenv('LANGUAGE_ID'), 
                'property_id' => $listing_id, 
                'json_object' => json_encode($data_json),
            ];

            $fields_property_lang = $db->getFieldNames('property_lang');

            foreach ($fields_property_lang as $column_name) {
                if(substr($column_name, 0, 6) == 'field_')
                if(strpos($column_name, '_int') === FALSE)
                {
                    if(isset($data_json->{$column_name}))
                    {
                        $data_insert[$column_name] = $data_json->{$column_name};
                    }
                }
                else
                {
                    $field_name = substr($column_name, 0, strlen($column_name)-4);

                    if(isset($data_json->{$column_name}) && is_numeric($data_json->{$column_name}))
                    {
                        $data_insert[$column_name] = $data_json->{$column_name};
                    }
                }
            }

            $builder = $db->table('property_lang');
            $insert_id = $builder->insert($data_insert);
            
            if(empty($insert_id))
            {
                return $this->respond(array(
                    'code'	    => 'failed',
                    'message'   => 'Insertion property_lang failed'
                ));
            }

            $data = array_merge($data, array(
                'code'	    => 'success',
                'message'   => __('Listing submitted successfuly', 'wpdirectorykit')
            ));

            return $this->respond($data);

        }
        else
        {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => join("\n", $validation->getErrors())
            ));
        }       


        return $this->respond($data);
    }

    public function delete()
    {
        $data = array(
            'code'	    => 'empty_code',
            'message'   => 'Empty Message'
        );

        $data_json = $this->request->getJSON();

        $db = \Config\Database::connect();
        $listingModel = model('App\Models\ListingModel');
        $userModel = model('App\Models\UserModel');
        $favoriteModel = model('App\Models\FavoriteModel');
        $tokenModel = model('App\Models\TokenModel');

        // [Check Token]

        if(empty($_GET['token']))
        {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => 'Token missing'
            ));
        }

        $token = $_GET['token'];

        $user_token = $tokenModel->where('token', $token)->findAll(1);

        if(count($user_token) == 0)
        {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => 'Valid Token missing'
            ));
        }

        $user_id = $user_token[0]['user_id'];

        if(empty($_GET['post_id']))
        {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => 'Listing ID missing'
            ));
        }

        $listing_id = $_GET['post_id'];

        // check if user have ownership on listing

        $builder = $db->table('property_user');
        $builder->where('user_id', $user_id);
        $builder->where('property_id', $listing_id);
        $query = $builder->get(1);
        $user_detected = $query->getResultArray();

        if(count($user_detected) == 0)
        {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => __('Token missing permissions', 'wpdirectorykit')
            ));
        }

        // [/Check Token]

        // Remove listing
        $ret = $listingModel->delete_item($listing_id);

        if($ret)
        {
            return $this->respond(array(
                'code'	    => 'success',
                'message'   => __('Deleted successfuly', 'wpdirectorykit')
            ));
        }

        return $this->respond(array(
            'code'	    => 'failed',
            'message'   => __('Deleting failed, please contact support team', 'wpdirectorykit')
        ));
    }

    public function images_upload()
    {
        $data = array(
            'code'	    => 'empty_code',
            'message'   => 'Empty Message'
        );

        $postBody = file_get_contents('php://input');
        $data_json = json_decode($postBody);

        $db = \Config\Database::connect();
        $listingModel = model('App\Models\ListingModel');
        $userModel = model('App\Models\UserModel');
        $favoriteModel = model('App\Models\FavoriteModel');
        $tokenModel = model('App\Models\TokenModel');
        $treeModel = model('App\Models\TreefieldModel');
        $fieldModel = model('App\Models\FieldModel');
        $repositoryModel = model('App\Models\RepositoryModel');
        $fileModel = model('App\Models\FileModel');

        $image_lib = \Config\Services::image();

        // [Check Token]

        if(empty($_GET['token']))
        {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => 'Token missing'
            ));
        }

        $token = $_GET['token'];

        $user_token = $tokenModel->where('token', $token)->findAll(1);

        if(count($user_token) == 0)
        {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => 'Valid Token missing'
            ));
        }

        $user_id = $user_token[0]['user_id'];

        // [/Check Token]


        // [Check Post Permissions]

        if(empty($_GET['post_id']))
        {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => __('Post ID missing', 'wpdirectorykit')
            ));
        }

        $listing_post_id = intval($_GET['post_id']);

        $listings = $listingModel->where('property.id', $listing_post_id)
                                 ->where('language_id', getenv('LANGUAGE_ID'))
                                 ->findAll(1);

        if(count($listings) == 0)
        {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => 'Listing id not found'
            ));
        }

        $listing_db_data = $listings[0];

        $builder = $db->table('property_user');
        $builder->where('user_id', $user_id);
        $builder->where('property_id', $listing_post_id);
        $query = $builder->get(1);
        $user_detected = $query->getResultArray();

        if(count($user_detected) == 0)
        {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => __('Token missing permissions', 'wpdirectorykit')
            ));
        }

        // [/Check Post Permissions]

        $img = ['jpg', 'jpeg', 'png', 'bmp'];
        $doc = [];//['zip', 'rar', 'pdf', 'doc', 'docx', 'xls','xlsx','ppt','pptx'];
        
        
        $whitelistExt = array_merge($img, $doc);

        $attachment_files = array();
        $upload_dir_path = getenv('FILES_DIRECTORY');

        $results_files = array();

        foreach ($data_json as $key => $value)
        {
            $file_name = $value->fileName;
            $ext = pathinfo($file_name, PATHINFO_EXTENSION);
            $f_decoded = base64_decode($value->encoded);   
    
            // Rename file baased on listing
            for($detect_file_number=1;$detect_file_number<9999;$detect_file_number++)
            {
                $file_name = 'listing-'.$listing_post_id.'-'.$detect_file_number .'.'.$ext;
                if(!file_exists($upload_dir_path . '/' . $file_name))
                    break;
            }
    
            // Upload file to wp
            
            $file_path = $upload_dir_path . '/' . $file_name;
            $file_url = getenv('WEBSITE_URL') . 'files/' . $file_name;
    
            $transfer = file_put_contents($file_path, $f_decoded);

            $file_path_thumb = $upload_dir_path . '/thumbnail/' . $file_name;

            $image_lib->withFile($file_path)
                        ->fit(300, 225, 'center')
                        ->save($file_path_thumb, 75);

            $image_lib->withFile($file_path)
                        ->resize(1980, 1080, true)
                        ->save($file_path, 85);

            // save file data in repository table

            if(empty($listing_db_data['repository_id'])) 
            {
                // create repository
                $insert_id = $repositoryModel->insert([
                    'is_activated' => '1',
                    'name' => 'estate_m'
                ]);

                if(empty($insert_id))
                {
                    return $this->respond(array(
                        'code'	    => 'failed',
                        'message'   => 'Creating repository failed'
                    ));
                }

                $listingModel->update($listing_post_id, ['repository_id' => $insert_id]);

                $listing_db_data['repository_id'] = $insert_id;
            }

            // Populate file data

            // $fileModel: order, filename, filetype, repository_id

            $file_last = $fileModel->orderBy('order DESC')->findAll(1);

            $max_order = 1;
            if(count($file_last) > 0)
            {
                $max_order = $file_last[0]['order'];
            }

            $insert_file_id = $fileModel->insert([
                'order' => $max_order+1,
                'filename' => $file_name,
                'filetype' => filetype($file_path),
                'repository_id' => $listing_db_data['repository_id']
            ]);


            // Populate property data
            // property: repository_id, image_filename, image_repository

            if(empty($listing_db_data['image_filename'])) 
            {
                $listing_db_data['image_filename'] = $file_name;
                $listing_db_data['image_repository'] = json_encode(array($listing_db_data['image_filename']));

                $listingModel->update($listing_post_id, ['image_filename' => $listing_db_data['image_filename'], 
                                                         'image_repository' => $listing_db_data['image_repository']]);
            
                
            }
            else
            {
                $image_rep = json_decode($listing_db_data['image_repository']);
                $image_rep[] = $file_name;
                $listing_db_data['image_repository'] = json_encode($image_rep);

                $listingModel->update($listing_post_id, ['image_repository' => json_encode($image_rep)]);
            }

            $results_files[] = array('file_url'=>$file_name, 
                                     'attach_id' =>$insert_file_id);

        }

        if(count($results_files) > 0)
        {
            return $this->respond(array(
                'files'     => $results_files,
                'code'	    => 'success',
                'message'   => __('Uploaded images: ', 'wpdirectorykit').count($results_files)
            ));
        }

        return $this->respond(array(
            'code'	    => 'failed',
            'message'   => __('Images not uploaded', 'wpdirectorykit')
        ));
    }

    public function delete_image()
    {
        $data = array(
            'code'	    => 'empty_code',
            'message'   => 'Empty Message'
        );

        $postBody = file_get_contents('php://input');
        $data_json = json_decode($postBody);

        $db = \Config\Database::connect();
        $listingModel = model('App\Models\ListingModel');
        $userModel = model('App\Models\UserModel');
        $favoriteModel = model('App\Models\FavoriteModel');
        $tokenModel = model('App\Models\TokenModel');
        $treeModel = model('App\Models\TreefieldModel');
        $fieldModel = model('App\Models\FieldModel');
        $repositoryModel = model('App\Models\RepositoryModel');
        $fileModel = model('App\Models\FileModel');

        $image_lib = \Config\Services::image();

        // [Check Token]

        if(empty($_GET['token']))
        {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => 'Token missing'
            ));
        }

        $token = $_GET['token'];

        $user_token = $tokenModel->where('token', $token)->findAll(1);

        if(count($user_token) == 0)
        {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => 'Valid Token missing'
            ));
        }

        $user_id = $user_token[0]['user_id'];

        // [/Check Token]


        // [Check Post Permissions]

        if(empty($_GET['post_id']))
        {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => __('Post ID missing', 'wpdirectorykit')
            ));
        }

        $listing_post_id = intval($_GET['post_id']);

        $listings = $listingModel->where('property.id', $listing_post_id)
                                 ->where('language_id', getenv('LANGUAGE_ID'))
                                 ->findAll(1);

        if(count($listings) == 0)
        {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => 'Listing id not found'
            ));
        }

        if(empty($_GET['image_path']))
        {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => __('Image path missing', 'wpdirectorykit')
            ));
        }

        $listing_db_data = $listings[0];

        $builder = $db->table('property_user');
        $builder->where('user_id', $user_id);
        $builder->where('property_id', $listing_post_id);
        $query = $builder->get(1);
        $user_detected = $query->getResultArray();

        if(count($user_detected) == 0)
        {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => __('Token missing permissions', 'wpdirectorykit')
            ));
        }

        // [/Check Post Permissions]

        $images_path_array = json_decode($listing_db_data['image_repository']);
        $index = array_search($_GET['image_path'], $images_path_array);

        $file_name = $_GET['image_path'];


        if($index === FALSE)
        {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => __('Image not found', 'wpdirectorykit')
            ));
        }

        // Remove images from listing

        unset($images_path_array[$index]);

        $listingModel->update($listing_post_id, ['image_repository' => json_encode(array_values($images_path_array))]);

        // if first image, then replace first image

        if($index == 0)
        {
            if(count($images_path_array) > 0)
            {
                $listingModel->update($listing_post_id, ['image_filename' => array_values($images_path_array)[0]]);
            }
            else
            {
                $listingModel->update($listing_post_id, ['image_filename' => '']);
            }
        }

        // Remove from repository

        $fileModel->where('repository_id', $listing_db_data['repository_id'])
                    ->where('filename', $_GET['image_path'])->delete();

        // Remove from filesystem, thumb and image

        @unlink(getenv('FILES_DIRECTORY').'' . $file_name);
        @unlink(getenv('FILES_DIRECTORY').'thumbnail/' . $file_name);

        return $this->respond(array(
            'code'	    => 'success',
            'message'   =>  __('Image removed #', 'wpdirectorykit').$_GET['image_path']
        ));
    }

    public function move_image_top()
    {
        $data = array(
            'code'	    => 'empty_code',
            'message'   => 'Empty Message'
        );

        $postBody = file_get_contents('php://input');
        $data_json = json_decode($postBody);

        $db = \Config\Database::connect();
        $listingModel = model('App\Models\ListingModel');
        $userModel = model('App\Models\UserModel');
        $favoriteModel = model('App\Models\FavoriteModel');
        $tokenModel = model('App\Models\TokenModel');
        $treeModel = model('App\Models\TreefieldModel');
        $fieldModel = model('App\Models\FieldModel');
        $repositoryModel = model('App\Models\RepositoryModel');
        $fileModel = model('App\Models\FileModel');

        $image_lib = \Config\Services::image();

        // [Check Token]

        if(empty($_GET['token']))
        {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => 'Token missing'
            ));
        }

        $token = $_GET['token'];

        $user_token = $tokenModel->where('token', $token)->findAll(1);

        if(count($user_token) == 0)
        {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => 'Valid Token missing'
            ));
        }

        $user_id = $user_token[0]['user_id'];

        // [/Check Token]


        // [Check Post Permissions]

        if(empty($_GET['post_id']))
        {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => __('Post ID missing', 'wpdirectorykit')
            ));
        }

        $listing_post_id = intval($_GET['post_id']);

        $listings = $listingModel->where('property.id', $listing_post_id)
                                 ->where('language_id', getenv('LANGUAGE_ID'))
                                 ->findAll(1);

        if(count($listings) == 0)
        {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => 'Listing id not found'
            ));
        }

        if(empty($_GET['image_path']))
        {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => __('Image path missing', 'wpdirectorykit')
            ));
        }

        $listing_db_data = $listings[0];

        $builder = $db->table('property_user');
        $builder->where('user_id', $user_id);
        $builder->where('property_id', $listing_post_id);
        $query = $builder->get(1);
        $user_detected = $query->getResultArray();

        if(count($user_detected) == 0)
        {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => __('Token missing permissions', 'wpdirectorykit')
            ));
        }

        // [/Check Post Permissions]

        $images_path_array = json_decode($listing_db_data['image_repository']);
        $index = array_search($_GET['image_path'], $images_path_array);

        $file_name = $_GET['image_path'];


        if($index === FALSE)
        {
            return $this->respond(array(
                'code'	    => 'failed',
                'message'   => __('Image not found', 'wpdirectorykit')
            ));
        }

        // move image to first position

        //appending $new in our array 
        array_unshift($images_path_array, $images_path_array[$index]);
        //now make it unique.
        $images_path_array = array_unique($images_path_array);

        $listingModel->update($listing_post_id, ['image_repository' => json_encode(array_values($images_path_array))]);

        // if first image, then replace first image

        $listingModel->update($listing_post_id, ['image_filename' => array_values($images_path_array)[0]]);

        // change order in file table

        $file_first = $fileModel->where('repository_id', $listing_db_data['repository_id'])
                                ->orderBy('order ASC')->findAll(1);

        $min_order = 0;
        if(count($file_first) > 0)
        {
            $min_order = $file_first[0]['order'];
        }

        $fileModel->set('order', $min_order-1, false)
                    ->where('filename', $_GET['image_path'])
                    ->where('repository_id', $listing_db_data['repository_id'])
                    ->update();

        return $this->respond(array(
            'code'	    => 'success',
            'message'   =>  __('Image moved to top #', 'wpdirectorykit').$_GET['image_path']
        ));
    }

}
