<?php

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

class Propertybase_model extends App_Model
{
    public function __construct()
    {
        parent::__construct();
    }

    public function create($data)
    {
        $data = hooks()->apply_filters('propertybase_before_property_added', $data);

        if (isset($data['custom_fields'])) {
            $custom_fields = $data['custom_fields'];
            unset($data['custom_fields']);
        }

        $amenities = [];
        if (isset($data['amenities'])) {
            $amenities = $data['amenities'];
            unset($data['amenities']);
        }

        $this->db->insert(db_prefix() . 'propertybase_properties', $data);
        $insert_id = $this->db->insert_id();

        if (isset($custom_fields)) {
            handle_custom_fields_post($insert_id, $custom_fields);
        }

        if ($insert_id && !empty($amenities)) {
            $this->add_amenities($insert_id, $amenities);
        }

        if ($insert_id) {
            hooks()->do_action('propertybase_after_property_added', $insert_id);

            return $insert_id;
        }

        return false;
    }

    public function get($id)
    {
        $this->db->where('id', $id);
        $property = $this->db->get(db_prefix() . 'propertybase_properties')->row();

        if ($property) {
            $property->amenities = $this->get_amenities($id);
            $property->amenities_with_types = $this->get_amenities_with_types($id);
        }

        return hooks()->apply_filters('propertybase_get_property', $property);
    }

    public function get_all($conditions = [])
    {
        if (!empty($conditions)) {
            $this->db->where($conditions);
        }
        $properties = $this->db->get(db_prefix() . 'propertybase_properties')->result_array();

        foreach ($properties as &$property) {
            $property['amenities'] = $this->get_amenities($property['id']);
            $property['amenities_with_types'] = $this->get_amenities_with_types($property['id']);
        }

        return hooks()->apply_filters('propertybase_get_properties', $properties);
    }

    public function update($id, $data)
    {
        $data = hooks()->apply_filters('propertybase_before_property_updated', $data, $id);

        if (isset($data['custom_fields'])) {
            $custom_fields = $data['custom_fields'];

            handle_custom_fields_post($id, $custom_fields);

            unset($data['custom_fields']);
        }

        $amenities = [];
        if (isset($data['amenities'])) {
            $amenities = $data['amenities'];
            unset($data['amenities']);
        }

        if (isset($data['total_views'])) {
            $this->db->set('total_views', 'total_views + 1', FALSE);
            unset($data['total_views']);
        }

        $this->db->where('id', $id);
        $this->db->update(db_prefix() . 'propertybase_properties', $data);

        if (!empty($amenities)) {
            $this->update_amenities($id, $amenities);
        }

        hooks()->do_action('propertybase_after_property_updated', $id);
        return true;
    }

    public function delete($id)
    {
        hooks()->do_action('propertybase_before_property_deleted', $id);

        $this->db->where('id', $id);
        $this->db->delete(db_prefix() . 'propertybase_properties');

        if ($this->db->affected_rows() > 0) {
            hooks()->do_action('propertybase_after_property_deleted', $id);

            $this->delete_property_main_image_attachment($id);
            $this->delete_property_attachments($id);
            $this->delete_property_notes($id);
            $this->delete_property_reminders($id);
            $this->delete_amenities($id);

            return true;
        }

        return false;
    }

    public function add_property_gallery_list_image($data)
    {
        $data = hooks()->apply_filters('propertybase_before_add_property_gallery_list_image', $data);

        $this->db->insert(db_prefix() . 'propertybase_property_images', $data);
        $insert_id = $this->db->insert_id();

        if ($insert_id) {
            hooks()->do_action('propertybase_after_add_property_gallery_list_image', $insert_id);
            return $insert_id;
        }

        return false;
    }

    public function get_property_gallery_list_images($property_id)
    {
        $this->db->where('property_id', $property_id);
        $this->db->order_by('image_order', 'asc');

        $imagesList = $this->db->get(db_prefix() . 'propertybase_property_images')->result_array();

        return hooks()->apply_filters('propertybase_get_property_gallery_list_images', $imagesList);
    }

    public function update_property_gallery_list_image($id, $data)
    {
        $this->db->where('id', $id);
        $this->db->update(db_prefix() . 'propertybase_property_images', $data);

        return $this->db->affected_rows() > 0;
    }

    public function delete_property_gallery_list_image($property_id, $image_id, $image_path)
    {
        $this->db->where('id', $image_id);
        $this->db->delete(db_prefix() . 'propertybase_property_images');

        $directory = FCPATH . 'modules/' . PROPERTYBASE_MODULE_NAME . '/uploads/property_images/attachments/' . $property_id . '/' . $image_path;

        if (is_file($directory)) {
            unlink($directory);
        }

        return $this->db->affected_rows() > 0;
    }

    public function transfer_property_agent($agent_id, $data = [])
    {
        $data = hooks()->apply_filters('propertybase_before_agent_transferred', $data, $agent_id);

        $this->db->where('selected_agent', $agent_id);
        $this->db->update(db_prefix() . 'propertybase_properties', $data);

        hooks()->do_action('propertybase_after_agent_transferred', $agent_id);
        return true;
    }

    public function add_amenities($property_id, $amenities)
    {
        foreach ($amenities as $amenity_id) {
            $this->db->insert(db_prefix() . 'propertybase_property_amenities', [
                'property_id' => $property_id,
                'amenity_id' => $amenity_id,
                'created_at' => date('Y-m-d H:i:s')
            ]);
        }
    }

    public function get_amenities($property_id)
    {
        $this->db->select('amenity_id');
        $this->db->where('property_id', $property_id);

        return array_column($this->db->get(db_prefix() . 'propertybase_property_amenities')->result_array(), 'amenity_id');
    }

    public function update_amenities($property_id, $amenities)
    {
        $this->delete_amenities($property_id);
        $this->add_amenities($property_id, $amenities);
    }

    private function delete_amenities($property_id)
    {
        $this->db->where('property_id', $property_id);
        $this->db->delete(db_prefix() . 'propertybase_property_amenities');
    }

    public function get_amenities_with_types($property_id)
    {
        $this->db->select('types.name, amenities.name as amenity_name');
        $this->db->from(db_prefix() . 'propertybase_property_amenities property_amenities');
        $this->db->join(db_prefix() . 'propertybase_amenities amenities', 'property_amenities.amenity_id = amenities.id', 'left');
        $this->db->join(db_prefix() . 'propertybase_amenities_types types', 'amenities.category = types.id', 'left');
        $this->db->where('property_amenities.property_id', $property_id);
        $this->db->order_by('types.name, amenities.name', 'ASC');
        $result = $this->db->get()->result_array();

        $grouped = [];
        foreach ($result as $row) {
            $grouped[$row['name']][] = $row['amenity_name'];
        }

        return $grouped;
    }

    public function _search_properties(array $data, $limit = 0)
    {
        $q = $data['q'];
        $customer_id = $data['customer_id'];

        $showOnlyAgentProperties = false;
        if (empty($customer_id)) {
            if (!is_admin() && !has_permission('propertybase', '', 'view')) {
                $showOnlyAgentProperties = true;
            }
        }

        $this->db->select();
        $this->db->from(db_prefix() . 'propertybase_properties');

        if ($showOnlyAgentProperties) {
            $this->db->where(db_prefix() . 'propertybase_properties.selected_agent', get_staff_user_id());
        }

        if (!empty($customer_id) && is_numeric($customer_id)) {
            $this->db->where(db_prefix() . 'propertybase_properties.rel_type', 'customer');
            $this->db->where(db_prefix() . 'propertybase_properties.rel_id', $customer_id);
        }

        $this->db->where('(name LIKE "%' . $this->db->escape_like_str($q) . '%" ESCAPE \'!\')');

        if ($limit != 0) {
            $this->db->limit($limit);
        }
        $this->db->order_by('name', 'ASC');

        return $this->db->get()->result_array();
    }

    public function get_property_main_image_attachment($property_id, $id = '')
    {
        if (is_numeric($id)) {
            $this->db->where('id', $id);
        } else {
            $this->db->where('rel_id', $property_id);
        }

        $this->db->where('rel_type', 'property_main_image');
        $result = $this->db->get(db_prefix() . 'files');

        if (is_numeric($id)) {
            return $result->row();
        }

        return $result->result_array();
    }

    public function get_property_floor_image_attachment($property_id, $id = '')
    {
        if (is_numeric($id)) {
            $this->db->where('id', $id);
        } else {
            $this->db->where('rel_id', $property_id);
        }

        $this->db->where('rel_type', 'property_floor_image');
        $result = $this->db->get(db_prefix() . 'files');

        if (is_numeric($id)) {
            return $result->row();
        }

        return $result->result_array();
    }

    public function delete_property_main_image_attachment($id)
    {
        $dir = PROPERTYBASE_PROPERTY_MAIN_IMAGE_PATH . $id . '/';

        if (is_dir($dir) && delete_dir($dir)) {

            $this->db->where('rel_id', $id);
            $this->db->where('rel_type', 'property_main_image');
            $this->db->delete(db_prefix() . 'files');

            return true;
        }

        return false;
    }

    public function delete_property_floor_image_attachment($id)
    {
        $dir = PROPERTYBASE_PROPERTY_FLOOR_IMAGE_PATH . $id . '/';

        if (is_dir($dir) && delete_dir($dir)) {

            $this->db->where('rel_id', $id);
            $this->db->where('rel_type', 'property_floor_image');
            $this->db->delete(db_prefix() . 'files');

            return true;
        }

        return false;
    }

    public function delete_property_attachments($id)
    {
        $dir = PROPERTYBASE_PROPERTY_ATTACHMENTS_PATH . $id . '/';

        if (is_dir($dir) && delete_dir($dir)) {

            $this->db->where('rel_id', $id);
            $this->db->where('rel_type', 'property_attachment');
            $this->db->delete(db_prefix() . 'files');

            return true;
        }

        return false;
    }

    public function delete_property_notes($id)
    {
        $this->db->where('rel_id', $id);
        $this->db->where('rel_type', 'property');
        $this->db->delete(db_prefix() . 'notes');

        return true;
    }

    public function delete_property_reminders($id)
    {
        $this->db->where('rel_id', $id);
        $this->db->where('rel_type', 'property');
        $this->db->delete(db_prefix() . 'reminders');

        return true;
    }

    public function get_billable_tasks($property_id = '')
    {
        $has_permission_view = has_permission('tasks', '', 'view');
        $noPermissionsQuery = get_tasks_where_string(false);

        $this->db->where('billable', 1);
        $this->db->where('billed', 0);

        if ($property_id == '') {
            $this->db->where('rel_type != "properties"');
        } else {
            $this->db->where('rel_type', 'properties');
            $this->db->where('rel_id', $property_id);
        }

        if (!$has_permission_view) {
            $this->db->where($noPermissionsQuery);
        }

        $tasks = $this->db->get(db_prefix() . 'tasks')->result_array();

        $i = 0;
        foreach ($tasks as $task) {
            $task_rel_data = get_relation_data($task['rel_type'], $task['rel_id']);
            $task_rel_value = get_relation_values($task_rel_data, $task['rel_type']);
            $tasks[$i]['rel_name'] = $task_rel_value['name'];
            if (total_rows(db_prefix() . 'taskstimers', [
                    'task_id' => $task['id'],
                    'end_time' => null,
                ]) > 0) {
                $tasks[$i]['started_timers'] = true;
            } else {
                $tasks[$i]['started_timers'] = false;
            }
            $i++;
        }

        return $tasks;
    }

    public function get_invoices_total($data)
    {
        $this->load->model('currencies_model');
        $this->load->model('invoices_model');

        if (isset($data['currency'])) {
            $currencyid = $data['currency'];
        } elseif (isset($data['customer_id']) && $data['customer_id'] != '') {
            $currencyid = $this->clients_model->get_customer_default_currency($data['customer_id']);
            if ($currencyid == 0) {
                $currencyid = $this->currencies_model->get_base_currency()->id;
            }
        } elseif (isset($data['property_id']) && $data['property_id'] != '') {
            $currencyid = $this->currencies_model->get_base_currency()->id;
        }

        $result = [];
        $result['due'] = [];
        $result['paid'] = [];
        $result['overdue'] = [];

        $has_permission_view = has_permission('invoices', '', 'view');
        $noPermissionsQuery = get_invoices_where_sql_for_staff(get_staff_user_id());

        for ($i = 1; $i <= 3; $i++) {
            $select = 'id,total';
            if ($i == 1) {
                $select .= ', (SELECT total - (SELECT COALESCE(SUM(amount),0) FROM ' . db_prefix() . 'invoicepaymentrecords WHERE invoiceid = ' . db_prefix() . 'invoices.id) - (SELECT COALESCE(SUM(amount),0) FROM ' . db_prefix() . 'credits WHERE ' . db_prefix() . 'credits.invoice_id=' . db_prefix() . 'invoices.id)) as outstanding';
            } elseif ($i == 2) {
                $select .= ',(SELECT SUM(amount) FROM ' . db_prefix() . 'invoicepaymentrecords WHERE invoiceid=' . db_prefix() . 'invoices.id) as total_paid';
            }
            $this->db->select($select);
            $this->db->from(db_prefix() . 'invoices');
            $this->db->where('currency', $currencyid);
            // Exclude cancelled invoices
            $this->db->where('status !=', Invoices_model::STATUS_CANCELLED);
            // Exclude draft
            $this->db->where('status !=', Invoices_model::STATUS_DRAFT);

            if (isset($data['property_id']) && $data['property_id'] != '') {
                $this->db->where('property_id', $data['property_id']);
            } elseif (isset($data['customer_id']) && $data['customer_id'] != '') {
                $this->db->where('clientid', $data['customer_id']);
            }

            if ($i == 3) {
                $this->db->where('status', Invoices_model::STATUS_OVERDUE);
            } elseif ($i == 1) {
                $this->db->where('status !=', Invoices_model::STATUS_PAID);
            }

            if (isset($data['years']) && count($data['years']) > 0) {
                $this->db->where_in('YEAR(date)', $data['years']);
            } else {
                $this->db->where('YEAR(date)', date('Y'));
            }

            if (!$has_permission_view) {
                $whereUser = $noPermissionsQuery;
                $this->db->where('(' . $whereUser . ')');
            }

            $invoices = $this->db->get()->result_array();

            foreach ($invoices as $invoice) {
                if ($i == 1) {
                    $result['due'][] = $invoice['outstanding'];
                } elseif ($i == 2) {
                    $result['paid'][] = $invoice['total_paid'];
                } elseif ($i == 3) {
                    $result['overdue'][] = $invoice['total'];
                }
            }
        }
        $currency = get_currency($currencyid);
        $result['due'] = array_sum($result['due']);
        $result['paid'] = array_sum($result['paid']);
        $result['overdue'] = array_sum($result['overdue']);
        $result['currency'] = $currency;
        $result['currencyid'] = $currencyid;

        return $result;
    }

    public function get_assigned_properties($assigned_type, $assigned_id)
    {
        $this->db->where('rel_type', $assigned_type)
            ->where('rel_id', $assigned_id);

        $assignedProperties = $this->db->get(db_prefix() . 'propertybase_properties')->result_array();

        return hooks()->apply_filters('propertybase_get_assigned_properties', $assignedProperties);
    }

    public function get_expenses_total($data)
    {
        $this->load->model('currencies_model');
        $base_currency = $this->currencies_model->get_base_currency()->id;
        $base = true;
        $currency_switcher = false;
        if (isset($data['currency'])) {
            $currencyid = $data['currency'];
            $currency_switcher = true;
        } elseif (isset($data['customer_id']) && $data['customer_id'] != '') {
            $currencyid = $this->clients_model->get_customer_default_currency($data['customer_id']);
            if ($currencyid == 0) {
                $currencyid = $base_currency;
            } else {
                if (total_rows(db_prefix() . 'expenses', [
                    'currency' => $base_currency,
                    'clientid' => $data['customer_id'],
                ])) {
                    $currency_switcher = true;
                }
            }
        } else {
            $currencyid = $base_currency;
            if (total_rows(db_prefix() . 'expenses', [
                'currency !=' => $base_currency,
            ])) {
                $currency_switcher = true;
            }
        }

        $currency = get_currency($currencyid);

        $has_permission_view = has_permission('expenses', '', 'view');
        $_result = [];

        for ($i = 1; $i <= 5; $i++) {
            $this->db->select('amount,tax,tax2,invoiceid');
            $this->db->where('currency', $currencyid);

            if (isset($data['years']) && count($data['years']) > 0) {
                $this->db->where('YEAR(date) IN (' . implode(', ', array_map(function ($year) {
                        return get_instance()->db->escape_str($year);
                    }, $data['years'])) . ')');
            } else {
                $this->db->where('YEAR(date) = ' . date('Y'));
            }
            if (isset($data['customer_id']) && $data['customer_id'] != '') {
                $this->db->where('clientid', $data['customer_id']);
            }
            if (isset($data['propertyid']) && $data['propertyid'] != '') {
                $this->db->where('property_id', $data['propertyid']);
            }

            if (!$has_permission_view) {
                $this->db->where('addedfrom', get_staff_user_id());
            }
            switch ($i) {
                case 1:
                    $key = 'all';

                    break;
                case 2:
                    $key = 'billable';
                    $this->db->where('billable', 1);

                    break;
                case 3:
                    $key = 'non_billable';
                    $this->db->where('billable', 0);

                    break;
                case 4:
                    $key = 'billed';
                    $this->db->where('billable', 1);
                    $this->db->where('invoiceid IS NOT NULL');
                    $this->db->where('invoiceid IN (SELECT invoiceid FROM ' . db_prefix() . 'invoices WHERE status=2 AND id=' . db_prefix() . 'expenses.invoiceid)');

                    break;
                case 5:
                    $key = 'unbilled';
                    $this->db->where('billable', 1);
                    $this->db->where('invoiceid IS NULL');

                    break;
            }
            $all_expenses = $this->db->get(db_prefix() . 'expenses')->result_array();
            $_total_all = [];
            $cached_taxes = [];
            foreach ($all_expenses as $expense) {
                $_total = $expense['amount'];
                if ($expense['tax'] != 0) {
                    if (!isset($cached_taxes[$expense['tax']])) {
                        $tax = get_tax_by_id($expense['tax']);
                        $cached_taxes[$expense['tax']] = $tax;
                    } else {
                        $tax = $cached_taxes[$expense['tax']];
                    }
                    $_total += ($_total / 100 * $tax->taxrate);
                }
                if ($expense['tax2'] != 0) {
                    if (!isset($cached_taxes[$expense['tax2']])) {
                        $tax = get_tax_by_id($expense['tax2']);
                        $cached_taxes[$expense['tax2']] = $tax;
                    } else {
                        $tax = $cached_taxes[$expense['tax2']];
                    }
                    $_total += ($expense['amount'] / 100 * $tax->taxrate);
                }
                array_push($_total_all, $_total);
            }
            $_result[$key]['total'] = app_format_money(array_sum($_total_all), $currency);
        }
        $_result['currency_switcher'] = $currency_switcher;
        $_result['currencyid'] = $currencyid;

        return $_result;
    }

//ASSET ASSIGN
    public function create_property_assign($data)
    {
        $data = hooks()->apply_filters('propertybase_before_property_assign_added', $data);

        if (is_reference_in_table('property_id', db_prefix() . 'propertybase_property_assigned', $data['property_id'])) {
            $this->delete_property_assign('', $data['property_id']);
        }

        $this->db->insert(db_prefix() . 'propertybase_property_assigned', $data);
        $insert_id = $this->db->insert_id();

        if ($insert_id) {
            hooks()->do_action('propertybase_after_property_assign_added', $insert_id);

            return $insert_id;
        }

        return false;
    }

    public function get_property_assign($id)
    {
        $this->db->where('property_id', $id);
        $property_assign = $this->db->get(db_prefix() . 'propertybase_property_assigned')->row();

        return hooks()->apply_filters('propertybase_get_property_assign', $property_assign);
    }

    public function get_related_properties_list($rel_id, $related_to)
    {
        $this->db->where('assigned_to', $related_to);
        $this->db->where('assigned_id', $rel_id);

        $related_properties = $this->db->get(db_prefix() . 'propertybase_property_assigned')->result_array();

        return hooks()->apply_filters('propertybase_get_related_properties_list', $related_properties);
    }

    public function get_all_property_assign()
    {
        $property_assignments = $this->db->get(db_prefix() . 'propertybase_property_assigned')->result_array();

        return hooks()->apply_filters('propertybase_get_all_property_assign', $property_assignments);
    }

    public function update_property_assign($id, $data)
    {
        $data = hooks()->apply_filters('propertybase_before_property_assign_updated', $data, $id);

        $this->db->where('id', $id);
        $this->db->update(db_prefix() . 'propertybase_property_assigned', $data);

        hooks()->do_action('propertybase_after_property_assign_updated', $id);

        return true;
    }

    public function delete_property_assign($id = '', $property_id = '')
    {
        hooks()->do_action('propertybase_before_property_assign_deleted', $id, $property_id);

        if (!empty($property_id)) {
            $this->db->where('property_id', $property_id);
        } else {
            $this->db->where('id', $id);
        }
        $this->db->delete(db_prefix() . 'propertybase_property_assigned');

        if ($this->db->affected_rows() > 0) {
            hooks()->do_action('propertybase_after_property_assign_deleted', $id, $property_id);

            return true;
        }

        return false;
    }

    public function create_property_history($data)
    {
        $data = hooks()->apply_filters('propertybase_before_property_history_added', $data);

        $this->db->insert(db_prefix() . 'propertybase_property_history', $data);
        $insert_id = $this->db->insert_id();

        if ($insert_id) {
            hooks()->do_action('propertybase_after_property_history_added', $insert_id);
            return $insert_id;
        }

        return false;
    }

    public function get_property_history($id)
    {
        $this->db->where('property_id', $id);
        $property_history = $this->db->get(db_prefix() . 'propertybase_property_history')->row();

        return hooks()->apply_filters('propertybase_get_property_history', $property_history);
    }

    public function get_all_property_history()
    {
        $property_histories = $this->db->get(db_prefix() . 'propertybase_property_history')->result_array();

        return hooks()->apply_filters('propertybase_get_all_property_histories', $property_histories);
    }

    public function update_property_history($id, $data)
    {
        $data = hooks()->apply_filters('propertybase_before_property_history_updated', $data, $id);

        $this->db->where('id', $id);
        $this->db->update(db_prefix() . 'propertybase_property_history', $data);

        hooks()->do_action('propertybase_after_property_history_updated', $id);

        return true;
    }

    public function delete_property_history($id = '', $property_id = '')
    {
        hooks()->do_action('propertybase_before_property_history_deleted', $id, $property_id);

        if (!empty($property_id)) {
            $this->db->where('property_id', $property_id);
        } else {
            $this->db->where('id', $id);
        }

        $this->db->delete(db_prefix() . 'propertybase_property_history');

        if ($this->db->affected_rows() > 0) {
            hooks()->do_action('propertybase_after_property_history_deleted', $id, $property_id);
            return true;
        }

        return false;
    }

    public function create_property_event($data)
    {
        $data += ['event_by' => get_staff_user_id()];
        $data = hooks()->apply_filters('propertybase_before_property_event_added', $data);

        $this->db->insert(db_prefix() . 'propertybase_property_events', $data);
        $insert_id = $this->db->insert_id();

        if ($insert_id) {
            hooks()->do_action('propertybase_after_property_event_added', $insert_id, $data);
            return $insert_id;
        }

        return false;
    }

    public function get_property_event($id)
    {
        $this->db->where('id', $id);
        $event = $this->db->get(db_prefix() . 'propertybase_property_events')->row();

        return hooks()->apply_filters('propertybase_get_property_event', $event, $id);
    }

    public function get_all_property_event($property_id)
    {
        $this->db->where('property_id', $property_id);
        $this->db->order_by('created_at', 'desc');

        $events = $this->db->get(db_prefix() . 'propertybase_property_events')->result_array();

        return hooks()->apply_filters('propertybase_get_all_property_events', $events, $property_id);
    }

    public function update_property_event($id, $data)
    {
        $data = hooks()->apply_filters('propertybase_before_property_event_updated', $data, $id);

        $this->db->where('id', $id);
        $this->db->update(db_prefix() . 'propertybase_property_events', $data);

        hooks()->do_action('propertybase_after_property_event_updated', $id, $data);

        return true;
    }

    public function delete_property_event($id = '', $property_id = '')
    {
        hooks()->do_action('propertybase_before_property_event_deleted', $id, $property_id);

        if (!empty($property_id)) {
            $this->db->where('property_id', $property_id);
        } else {
            $this->db->where('id', $id);
        }
        $this->db->delete(db_prefix() . 'propertybase_property_events');

        if ($this->db->affected_rows() > 0) {
            hooks()->do_action('propertybase_after_property_event_deleted', $id, $property_id);
            return true;
        }

        return false;
    }

    public function get_assigned_properties_for_client($customer_id)
    {
        $customer_id = hooks()->apply_filters('propertybase_before_get_assigned_properties_customer_id', $customer_id);

        $this->db->select('properties.*, assigned.property_id, assigned.assigned_to, assigned.assigned_id');
        $this->db->from(db_prefix() . 'propertybase_properties AS properties');
        $this->db->join(
            db_prefix() . 'propertybase_property_assigned AS assigned',
            'properties.id = assigned.property_id'
        );
        $this->db->where('assigned.assigned_to', 'customers');
        $this->db->where('assigned.assigned_id', $customer_id);

        hooks()->do_action('propertybase_before_get_assigned_properties_query', $this->db);
        $result = $this->db->get()->result_array();

        return hooks()->apply_filters('propertybase_get_assigned_properties_result', $result, $customer_id);
    }

    public function add_lead_to_property($data)
    {
        $data = hooks()->apply_filters('propertybase_before_add_lead_to_property', $data);

        $this->db->insert(db_prefix() . 'propertybase_properties_leads', $data);
        $insert_id = $this->db->insert_id();

        if ($insert_id) {
            hooks()->do_action('propertybase_after_add_lead_to_property', $insert_id);

            return $insert_id;
        }

        return false;
    }

}
