<?php

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

use chillerlan\QRCode\QRCode;

class Propertybase extends AdminController
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('propertybase_model');
        hooks()->do_action('propertybase_init');
    }

    public function index()
    {
        show_404();
    }

    public function manage()
    {
        if (!has_permission('propertybase', '', 'view')) {
            access_denied('propertybase');
        }

        if ($this->input->is_ajax_request()) {
            $this->app->get_table_data(module_views_path(PROPERTYBASE_MODULE_NAME, 'admin/properties/table'), ['postData' => $_POST]);
        }

        $data['title'] = _l('propertybase_manage_properties');

        $this->load->model('staff_model');
        $data['members'] = $this->staff_model->get('', ['is_not_staff' => 0, 'active' => 1]);

        $this->load->model('clients_model');
        $data['client_list'] = $this->clients_model->get('', [db_prefix() . 'clients.active' => 1]);

        $this->load->model('projects_model');
        $data['projects_list'] = $this->projects_model->get();

        $this->load->model('propertycategories_model');
        $data['property_categories'] = $this->propertycategories_model->get_all();

        $data['property_countries'] = get_all_countries();

        $this->load->model('PropertyOwnershipTypes_model');
        $data['property_ownership_types'] = $this->PropertyOwnershipTypes_model->get_all();

        $this->load->model('PropertyEnergyEfficiencyTypes_model');
        $data['property_energy_efficiency_types'] = $this->PropertyEnergyEfficiencyTypes_model->get_all();

        $this->load->view('admin/properties/manage', $data);
    }

    public function view($id)
    {
        if (!has_permission('propertybase', '', 'view')) {
            access_denied('propertybase');
        }

        if ($this->input->is_ajax_request()) {
            $this->app->get_table_data(module_views_path(PROPERTYBASE_MODULE_NAME, 'admin/properties/history_table'), ['property_id' => $id]);
        }

        $data['property'] = $this->propertybase_model->get($id);
        $data['title'] = propertybase_formatted_property_name($id);
        $data['property_main_image'] = $this->propertybase_model->get_property_main_image_attachment($id);
        $data['property_floor_image'] = $this->propertybase_model->get_property_floor_image_attachment($id);
        $data['property_assigned'] = $this->propertybase_model->get_property_assign($id);

        $this->load->model('staff_model');
        $data['members'] = $this->staff_model->get('', ['is_not_staff' => 0, 'active' => 1]);
        $data['attachments'] = get_all_property_attachments($data['property']->id);

        $this->load->model('invoices_model');

        $data['invoiceid'] = '';
        $data['status'] = '';
        $data['custom_view'] = '';

        $data['invoices_years'] = $this->invoices_model->get_invoices_years();
        $data['invoices_sale_agents'] = $this->invoices_model->get_sale_agents();
        $data['invoices_statuses'] = $this->invoices_model->get_statuses();
        $data['invoices_sale_agents'] = $this->invoices_model->get_sale_agents();

        $this->load->model('payment_modes_model');
        $data['payment_modes'] = $this->payment_modes_model->get('', [], true);

        $this->load->model('taxes_model');
        $this->load->model('expenses_model');
        $this->load->model('currencies_model');
        $data['taxes'] = $this->taxes_model->get();
        $data['expense_categories'] = $this->expenses_model->get_category();
        $data['currencies'] = $this->currencies_model->get();

        $data['generatedQr'] = (new QRCode)->render('
        Property ID: ' . $id . '
        Property Name: ' . propertybase_formatted_property_name($id) . '
        Property Purpose: ' . _l(propertybase_property_purposes($data['property']->property_purpose)) . '
        Property Price: ' . propertybase_get_property_price($id, true, true) . '
        Property Agent: ' . get_staff_full_name($data['property']->selected_agent) . '
        Full Property Details: ' . propertybase_get_property_single_page_url($id) . '
        ');

        $data['property_events'] = $this->propertybase_model->get_all_property_event($id);
        $data['propertyAssigned'] = $this->propertybase_model->get_property_assign($id);


        $this->load->view('admin/properties/view', $data);
    }

    public function create($id = '')
    {
        if (!has_permission('propertybase', '', 'create')) {
            access_denied('propertybase');
        }

        if ($this->input->post() && $id === '') {

            $response = $this->propertybase_model->create($this->input->post() + ['created_at' => date('Y-m-d H:i:s'), 'is_enabled' => 1]);

            if ($response == true) {

                propertybase_handle_property_main_image($response);
                propertybase_handle_property_floor_image($response);

                set_alert('success', _l('propertybase_created_successfully'));
            } else {
                set_alert('warning', _l('propertybase_not_created_successfully'));
            }

            redirect(admin_url('propertybase/manage'));

        } elseif ($this->input->post() && $id !== '') {

            $response = $this->propertybase_model->update($id, $this->input->post());

            if ($response == true) {

                if (isset($_FILES['file']) && $_FILES['file']['size'] != 0) {
                    $this->propertybase_model->delete_property_main_image_attachment($id);

                    propertybase_handle_property_main_image($id);
                }

                if (isset($_FILES['floor']) && $_FILES['floor']['size'] != 0) {
                    $this->propertybase_model->delete_property_floor_image_attachment($id);

                    propertybase_handle_property_floor_image($id);
                }

                set_alert('success', _l('propertybase_updated_successfully'));
            } else {
                set_alert('warning', _l('propertybase_not_updated_successfully'));
            }

            redirect(admin_url('propertybase/create/' . $id));
        }

        $data['title'] = _l('propertybase');
        if ($id) {
            $data['property_data'] = $this->propertybase_model->get($id);
            $data['property_list_images'] = $this->propertybase_model->get_property_gallery_list_images($id);
            $data['property_main_image'] = $this->propertybase_model->get_property_main_image_attachment($id);
            $data['property_floor_image'] = $this->propertybase_model->get_property_floor_image_attachment($id);

            $data['title'] = _l('propertybase_manage_property') . ' - ' . propertybase_formatted_property_name($data['property_data']->id);
        }

        $this->load->model('staff_model');
        $data['members'] = $this->staff_model->get('', ['is_not_staff' => 0, 'active' => 1]);

        $this->load->model('propertycategories_model');
        $data['property_categories'] = $this->propertycategories_model->get_all();

        $this->load->model('PropertyAreaTypes_model');
        $data['property_areas'] = $this->PropertyAreaTypes_model->get_all();

        $this->load->model('PropertyEnergyEfficiencyTypes_model');
        $data['property_energy_efficiency_types'] = $this->PropertyEnergyEfficiencyTypes_model->get_all();

        $this->load->model('PropertyOwnershipTypes_model');
        $data['property_ownership_types'] = $this->PropertyOwnershipTypes_model->get_all();

        $this->load->model('PropertyAmenitiesTypes_model');
        $data['property_amenities_types'] = $this->PropertyAmenitiesTypes_model->get_all();

        $this->load->model('propertyamenities_model');
        $data['property_amenities'] = $this->propertyamenities_model->get_all();

        $data['property_countries'] = get_all_countries();

        $data = hooks()->apply_filters('propertybase_create_edit_property_data_controller', $data, $id);

        $this->load->view('admin/properties/create', $data);
    }

    public function delete($id = '')
    {
        if (!has_permission('propertybase', '', 'delete')) {
            access_denied('propertybase');
        }

        if (!$id) {
            redirect(admin_url('propertybase/manage'));
        }

        $response = $this->propertybase_model->delete($id);

        if ($response == true) {
            set_alert('success', _l('deleted', _l('propertybase')));
        } else {
            set_alert('warning', _l('problem_deleting', _l('propertybase')));
        }

        redirect(admin_url('propertybase/manage'));
    }

    public function property_status()
    {
        $postData = $this->input->post();
        $edit_status = $postData['id'] ?? '';

        $modalFormInputs = '';

        if ($postData['status'] == 'allocate') {

            $this->load->model('clients_model');
            $this->load->model('projects_model');

            $clients = $this->clients_model->get('', [db_prefix() . 'clients.active' => 1]);
            $projects = $this->projects_model->get();

            $allocateToValue = '';
            $projectsValue = '';
            $customersValue = '';
            $allocationNoteValue = '';
            $hideCheckbox = '';
            $hideSignaturePad = '';
            $signatureValue = '';

            if ($edit_status) {
                $eventData = $this->propertybase_model->get_property_event($edit_status);
                $eventDataForm = json_decode($eventData->event_form);

                $allocateToValue = $eventDataForm->allocate_to;
                $projectsValue = $eventDataForm->projects;
                $customersValue = $eventDataForm->customers;
                $allocationNoteValue = $eventDataForm->allocation_note ?? '';
                $signatureValue = $eventDataForm->signature;

                $hideCheckbox = 'hide';
                $hideSignaturePad = 'hide';

            }

            $modalFormInputs .= '
                                      ' . render_select("allocate_to", propertybase_allocate_to_options(), ["value", "name"], "propertybase_allocate_to", $allocateToValue) . '
                                      ' . render_select("projects", $projects, ["id", "name"], "propertybase_allocate_to_project_label", $projectsValue) . '
                                      ' . render_select("customers", $clients, ["userid", "company"], "propertybase_allocate_to_customer_label", $customersValue) . '
                                        <div class="row">
                                            <div class="col-md-12">
                                                <p class="bold">' . _l("propertybase_allocate_to_note") . '</p>
                                                    ' . render_textarea("allocation_note", "", $allocationNoteValue) . '
                                            </div>
                                        </div>
                                        <div class="div ' . $hideSignaturePad . '">
                                            <p class="bold" id="signatureLabel">Signature</p>
                                                <div class="signature-pad--body propertybase-signature-pad-style">
                                                  <canvas id="signature" height="130" width="550"></canvas>
                                                </div>
                                            <input type="text" class="propertybase-signature-input" tabindex="-1" value="' . $signatureValue . '" name="signature" id="signatureInput">
                                            <div class="dispay-block">
                                              <button type="button" class="btn btn-default btn-xs clear" tabindex="-1" data-action="clear">Clear</button>
                                              <button type="button" class="btn btn-default btn-xs" tabindex="-1" data-action="undo">Undo</button>
                                            </div>
                                        </div>
                                        <div class="row ' . $hideCheckbox . '">
                                            <div class="col-md-12">
                                                <div class="checkbox checkbox-primary">
                                                    <input type="checkbox" name="notify" id="notify">
                                                    <label for="notify">
                                                        ' . _l("propertybase_notify_checkout") . '
                                                    </label>
                                                </div>
                                            </div>
                                        </div>
         
                <script>
                init_selectpicker();
                init_datepicker();
                
                $(`[app-field-wrapper="projects"]`).hide();
                $(`[app-field-wrapper="customers"]`).hide();

                $(document).ready(function () {
                    let initialValue = $(`select[name="allocate_to"]`).val();
                    showRelevantField(initialValue);
                    ' . propertybase_signature_pad_js() . '
                })

                $(`select[name="allocate_to"]`).on("change", function () {
                    let selectedValue = $(`select[name="allocate_to"]`).val();
                    showRelevantField(selectedValue);
                });

                function showRelevantField(value) {
                    if (value == "project") {
                        $(`[app-field-wrapper="projects"]`).show();
                        $(`[app-field-wrapper="customers"]`).hide();
                        $(`select[name="customers"]`).val("").change();
                    } else if (value == "customer") {
                        $(`[app-field-wrapper="customers"]`).show();
                        $(`[app-field-wrapper="projects"]`).hide();
                        $(`select[name="projects"]`).val("").change();
                    } else {
                        $(`[app-field-wrapper="projects"]`).hide();
                        $(`[app-field-wrapper="customers"]`).hide();
                    }
                }
            </script>
                ';

        }

        if ($postData['status'] == 'sell') {

            $dateValue = '';
            $soldToValue = '';
            $saleAmountValue = '';
            $noteValue = '';
            $signatureValue = '';
            $hideSignaturePad = '';

            if ($edit_status) {
                $eventData = $this->propertybase_model->get_property_event($edit_status);
                $eventDataForm = json_decode($eventData->event_form);

                $dateValue = $eventDataForm->date_sold;
                $soldToValue = $eventDataForm->sold_to;
                $saleAmountValue = $eventDataForm->sale_amount;
                $noteValue = $eventDataForm->note;
                $signatureValue = $eventDataForm->signature;
                $hideSignaturePad = 'hide';
            }

            $modalFormInputs .= '
                                      ' . render_date_input("date_sold", "propertybase_asset_date_sold_label", $dateValue) . '
                                      ' . render_input("sold_to", "propertybase_asset_date_sold_to_label", $soldToValue) . '
                                      <div class="row">
                                      <div class="col-md-12">
                                            <div class="form-group">
                                                <label for="donate_value">' . _l("propertybase_asset_date_sale_value_label") . '</label>
                                                <div class="input-group">
                                                    <input type="number" class="form-control" name="sale_amount"
                                                           value="' . $saleAmountValue . '">
                                                    <div class="input-group-addon">
                                                        ' . get_base_currency()->symbol . '
                                                    </div>
                                                </div>
                                            </div>
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-12">
                                                <p class="bold">' . _l("propertybase_allocate_to_note") . '</p>
                                                    ' . render_textarea("note", "", $noteValue) . '
                                            </div>
                                        </div>
                                        <div class="div ' . $hideSignaturePad . '">
                                            <p class="bold" id="signatureLabel">Signature</p>
                                                <div class="signature-pad--body propertybase-signature-pad-style">
                                                  <canvas id="signature" height="130" width="550"></canvas>
                                                </div>
                                            <input type="text" class="propertybase-signature-input" tabindex="-1" value="' . $signatureValue . '" name="signature" id="signatureInput">
                                            <div class="dispay-block">
                                              <button type="button" class="btn btn-default btn-xs clear" tabindex="-1" data-action="clear">Clear</button>
                                              <button type="button" class="btn btn-default btn-xs" tabindex="-1" data-action="undo">Undo</button>
                                            </div>
                                        </div>
                                        
                <script>
                init_selectpicker();
                init_datepicker();
                $(document).ready(function () {
                    ' . propertybase_signature_pad_js() . '
                })
                </script>
                ';
        }

        $modalFormInputs = hooks()->apply_filters('propertybase_property_status_form', $modalFormInputs, $postData);

        echo json_encode(['form' => $modalFormInputs]);
        die;
    }

    public function save_property_status()
    {
        $postData = $this->input->post();
        $postId = $postData['id'];

        if ($postData['status'] == 'allocate') {

            $sendEmail = false;
            if (isset($postData['notify'])) {
                $sendEmail = true;
            }

            $rel_id = 0;
            $related_to = '';
            $requiredInput = 'customers';
            $whoReceivesNotifications = [];
            $notificationUrl = '';
            $emailUrl = '';

            if ($postData['allocate_to'] == 'customer') {
                $rel_id = $postData['customers'];
                $related_to = 'customers';
                $requiredInput = 'customers';
                $emailUrl = admin_url('clients/client/' . $rel_id);
                $notificationUrl = 'clients/client/' . $rel_id;

                $this->load->model('clients_model');
                $customerContacts = $this->clients_model->get_contacts($rel_id);
                foreach ($customerContacts as $contact) {
                    $whoReceivesNotifications[] = ['id' => $contact['id'], 'email' => $contact['email']];
                }
            }

            if ($postData['allocate_to'] == 'project') {
                $rel_id = $postData['projects'];
                $related_to = 'project';
                $requiredInput = 'projects';
                $emailUrl = admin_url('projects/view/' . $rel_id);
                $notificationUrl = 'projects/view/' . $rel_id;

                $this->load->model('projects_model');
                $projectMembers = $this->projects_model->get_project_members($rel_id);
                foreach ($projectMembers as $staff) {
                    $whoReceivesNotifications[] = ['id' => $staff['staff_id'], $staff['email']];
                }
            }

            if (empty($postData['allocate_to'])) {
                echo json_encode(['status' => 0, 'message' => _l('propertybase_required_not_filled')]);
                die;
            }
            if (empty($postData[$requiredInput])) {
                echo json_encode(['status' => 0, 'message' => _l('propertybase_required_not_filled')]);
                die;
            }

            $propertyData = $this->propertybase_model->get($postData['property_id']);
            $currentAssetStatus = propertybase_get_status_data($propertyData->property_status);

            $this->propertybase_model->update($postData['property_id'], ['property_status' => propertybase_get_status_data($postData['status'])['id']]);
            $this->propertybase_model->create_property_assign([
                'property_id' => $postData['property_id'],
                'assigned_to' => $related_to,
                'assigned_id' => $rel_id,
                'assign_date' => date('Y-m-d H:i:s')
            ]);

            if (empty($postId)) {
                $eventId = $this->propertybase_model->create_property_event([
                    'event_form' => json_encode($postData),
                    'property_id' => $postData['property_id'],
                    'created_at' => date('Y-m-d H:i:s')
                ]);

                $uploadPath = FCPATH . 'modules/' . PROPERTYBASE_MODULE_NAME . '/uploads/property_images/signatures/' . $eventId . '/';

                process_digital_signature_image($this->input->post('signature', false), $uploadPath);

            } else {
                $this->propertybase_model->update_property_event($postId, [
                    'event_form' => json_encode($postData)
                ]);
            }

            if (empty($postId)) {
                $this->propertybase_model->create_property_history([
                    'property_id' => $postData['property_id'],
                    'event' => ucfirst(propertybase_get_status_data($postData['status'])['value']),
                    'field' => 'Status',
                    'changed_from' => ucfirst($currentAssetStatus['value']),
                    'changed_to' => ucfirst(propertybase_get_status_data($postData['status'])['value']),
                    'changed_by' => get_staff_user_id(),
                    'changed_at' => date('Y-m-d H:i:s')
                ]);
            }

            $propertyRelatedTo = $related_to;
            if ($related_to == 'customers') {
                $propertyRelatedTo = 'customer';
            }

            $this->propertybase_model->update($postData['property_id'], [
                'rel_type' => $propertyRelatedTo,
                'rel_id' => $rel_id
            ]);

            if ($sendEmail) {
                foreach ($whoReceivesNotifications as $receiver) {
                    $notified = add_notification([
                        'description' => 'propertybase_property_allocated_notification',
                        'touserid' => $receiver['id'],
                        'fromcompany' => 1,
                        'fromuserid' => 0,
                        'link' => $notificationUrl,
                        'additional_data' => serialize([
                            $propertyData->name,
                            get_staff_full_name(get_staff_user_id())
                        ]),
                    ]);

                    if ($notified) {
                        pusher_trigger_notification([$receiver['id']]);
                    }

                    $propertyName = $propertyData->name ?? "";

                    $this->load->model('emails_model');
                    $this->emails_model->send_simple_email(
                        $receiver['email'],
                        'New Property Allocated To You -' . get_option('companyname'),
                        '
            Hello,
<br>
Property with title <strong>' . $propertyName . '</strong> has been allocated to you by : <strong>' . get_staff_full_name(get_staff_user_id()) . '</strong>
<br>
<a href="' . $emailUrl . '">More Details</a>
<br>
Best regards,<br>
' . get_option('companyname') . '
            '
                    );

                }
            }

            if (empty($postId)) {
                echo json_encode(['success' => 'true', 'message' => _l('propertybase_allocate_successfully')]);
                die;
            }

            echo json_encode(['success' => 'true', 'message' => _l('propertybase_allocate_successfully_update')]);
            die;

        }

        if ($postData['status'] == 'sell') {

            if (empty($postData['date_sold'])) {
                echo json_encode(['status' => 0, 'message' => _l('propertybase_required_not_filled')]);
                die;
            }

            $propertyData = $this->propertybase_model->get($postData['property_id']);
            $currentAssetStatus = propertybase_get_status_data($propertyData->property_status);

            $this->propertybase_model->delete_property_assign($propertyData->id);

            $this->propertybase_model->update($postData['property_id'], ['property_status' => propertybase_get_status_data($postData['status'])['id']]);

            if (empty($postId)) {
                $eventId = $this->propertybase_model->create_property_event([
                    'event_form' => json_encode($postData),
                    'property_id' => $postData['property_id'],
                    'created_at' => date('Y-m-d H:i:s')
                ]);

                $uploadPath = FCPATH . 'modules/' . PROPERTYBASE_MODULE_NAME . '/uploads/property_images/signatures/' . $eventId . '/';
                process_digital_signature_image($this->input->post('signature', false), $uploadPath);
            } else {
                $this->propertybase_model->update_property_event($postId, [
                    'event_form' => json_encode($postData)
                ]);
            }

            if (empty($postId)) {
                $this->propertybase_model->create_property_history([
                    'property_id' => $postData['property_id'],
                    'event' => ucfirst(propertybase_get_status_data($postData['status'])['value']),
                    'field' => 'Status',
                    'changed_from' => ucfirst($currentAssetStatus['value']),
                    'changed_to' => ucfirst(propertybase_get_status_data($postData['status'])['value']),
                    'changed_by' => get_staff_user_id(),
                    'changed_at' => date('Y-m-d H:i:s')
                ]);
            }

            if (empty($postId)) {
                echo json_encode(['success' => 'true', 'message' => _l('propertybase_sold_successfully')]);
                die;
            }

            echo json_encode(['success' => 'true', 'message' => _l('propertybase_sold_successfully_update')]);
            die;
        }

    }

    public function delete_property_event($event_id)
    {
        $this->propertybase_model->delete_property_event($event_id);

        echo json_encode(['success' => 'true', 'message' => _l('propertybase_property_event_deleted')]);
        die;
    }

    public function revocate_property($property_id)
    {
        $propertyData = $this->propertybase_model->get($property_id);
        $currentAssetStatus = propertybase_get_status_data($propertyData->property_status);

        $this->propertybase_model->update($property_id, ['property_status' => 1]);
        $this->propertybase_model->delete_property_assign('', $property_id);

        $this->propertybase_model->create_property_event([
            'event_form' => '{"id":"","property_id":"' . $property_id . '","status":"revocate"}',
            'property_id' => $property_id,
            'created_at' => date('Y-m-d H:i:s')
        ]);

        $this->propertybase_model->create_property_history([
            'property_id' => $property_id,
            'event' => ucfirst(propertybase_get_status_data(1)['value']),
            'field' => 'Status',
            'changed_from' => ucfirst($currentAssetStatus['value']),
            'changed_to' => ucfirst(propertybase_get_status_data(1)['value']),
            'changed_by' => get_staff_user_id(),
            'changed_at' => date('Y-m-d H:i:s')
        ]);

        $this->propertybase_model->update($property_id, [
            'rel_type' => '',
            'rel_id' => ''
        ]);

        set_alert('success', _l('propertybase_property_revocate_success'));
        redirect(admin_url(PROPERTYBASE_MODULE_NAME . '/view/' . $property_id));
    }

    public function queue_uploaded_file($property_id)
    {
        if (isset($_FILES['file']) && _perfex_upload_error($_FILES['file']['error'])) {
            header('HTTP/1.0 400 Bad error');
            echo _perfex_upload_error($_FILES['file']['error']);
            die;
        }

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

        if (isset($_FILES['file']['name'])) {
            // Get the temp file path
            $tmpFilePath = $_FILES['file']['tmp_name'];
            // Make sure we have a filepath
            if (!empty($tmpFilePath) && $tmpFilePath != '') {
                _maybe_create_upload_path($path);
                $filename = $_FILES['file']['name'];
                $newFilePath = $path . $filename;

                // Upload the file into the temp dir
                if (move_uploaded_file($tmpFilePath, $newFilePath)) {
                    $attachment = [];
                    $attachment[] = [
                        'image_url' => $filename,
                        'property_id' => $property_id,
                        'created_at' => date('Y-m-d H:i:s')
                    ];

                    $this->propertybase_model->add_property_gallery_list_image($attachment[0]);
                }
            }
        }
    }

    public function delete_image()
    {
        if (!has_permission('propertybase', '', 'delete')) {
            access_denied('propertybase');
        }

        if ($this->input->post()) {

            $property_id = $this->input->post('property_id');
            $image_id = $this->input->post('image_id');
            $image_path = $this->input->post('image_path');

            $response = $this->propertybase_model->delete_property_gallery_list_image($property_id, $image_id, $image_path);

            if ($response == true) {
                set_alert('success', _l('deleted', _l('propertybase_property_images')));
            } else {
                set_alert('warning', _l('problem_deleting', _l('propertybase_property_images')));
            }

            redirect(admin_url(PROPERTYBASE_MODULE_NAME . '/create/' . $property_id));

        }
    }

    public function update_images_order()
    {
        if ($this->input->post()) {
            $imageids_arr = array();

            if ($this->input->post('imageids')) {
                $imageids_arr = $this->input->post('imageids');
            }

            if (count($imageids_arr) > 0) {
                $position = 1;
                foreach ($imageids_arr as $id) {
                    $this->propertybase_model->update_property_gallery_list_image($id, ['image_order' => $position]);
                    $position++;
                }
                echo json_encode([
                    'error' => '0',
                    'message' => _l('propertybase_images_order_updated'),
                ]);
                die;
            }

            echo json_encode([
                'error' => '0',
                'message' => _l('propertybase_images_order_updated_failed'),
            ]);
            die;
        }
    }

    public function bulk_property_agent_transfer()
    {
        if (!is_admin()) {
            access_denied('propertybase');
        }

        if ($this->input->post()) {

            $postData = $this->input->post();

            $sendEmail = false;
            if (isset($postData['notify'])) {
                $sendEmail = true;
            }

            $transferFrom = $postData['transfer_from'];
            $transferTo = $postData['transfer_to'];

            $this->propertybase_model->transfer_property_agent($transferFrom, ['selected_agent' => $transferTo]);

            if ($sendEmail) {
                $notified = add_notification([
                    'description' => 'propertybase_asset_transfered_notification',
                    'touserid' => $transferTo,
                    'fromcompany' => 1,
                    'fromuserid' => 0,
                    'link' => PROPERTYBASE_MODULE_NAME . "/manage",
                ]);

                if ($notified) {
                    pusher_trigger_notification([$transferTo]);
                }

                $emailUrl = admin_url(PROPERTYBASE_MODULE_NAME . '/manage');
                $this->load->model('emails_model');
                $this->emails_model->send_simple_email(
                    get_staff($transferTo)->email,
                    'New Properties Under Your Management -' . get_option('companyname'),
                    '
            Hello,
<br>
New properties have been added under your management by : <strong>' . get_staff_full_name(get_staff_user_id()) . '</strong>
<br>
<a href="' . $emailUrl . '">More Details</a>
<br>
Best regards,<br>
' . get_option('companyname') . '
            '
                );

            }

            set_alert('success', _l('propertybase_bulk_event_success'));
            redirect(admin_url(PROPERTYBASE_MODULE_NAME . '/manage'));

        }

        $data['title'] = _l('propertybase_bulk_property_agent_transfer');

        $this->load->model('staff_model');
        $data['staffMembers'] = $this->staff_model->get('', ['is_not_staff' => 0, 'active' => 1]);

        $this->load->view('admin/properties/bulk/transfer_property_agent', $data);
    }

    public function import_properties()
    {
        if (!is_admin()) {
            access_denied('propertybase');
        }

        $propertyImporter = new Import_properties();

        $propertyImporter->setDatabaseFields($this->db->list_fields(db_prefix() . 'propertybase_properties'))
            ->setCustomFields(get_custom_fields('propertybase_pr'));

        if ($this->input->post('download_sample') === 'true') {
            $propertyImporter->downloadSample();
        }

        if (
            $this->input->post()
            && isset($_FILES['file_csv']['name']) && $_FILES['file_csv']['name'] != ''
        ) {
            $propertyImporter->setSimulation($this->input->post('simulate'))
                ->setTemporaryFileLocation($_FILES['file_csv']['tmp_name'])
                ->setFilename($_FILES['file_csv']['name'])
                ->perform();

            $data['total_rows_post'] = $propertyImporter->totalRows();

            if (!$propertyImporter->isSimulation()) {
                set_alert('success', _l('import_total_imported', $propertyImporter->totalImported()));
            }
        }

        $data['title'] = _l('propertybase_import_properties_menu');
        $data['importInstance'] = $propertyImporter;
        $this->load->view('admin/properties/import/import_properties', $data);
    }

    public function add_note($rel_id)
    {
        $this->load->model('misc_model');
        $this->misc_model->add_note($this->input->post(), 'property', $rel_id);
        echo $rel_id;
    }

    public function upload_attachment($id)
    {
        handle_property_attachments_upload($id);
    }

    public function get_notes($id)
    {
        $this->load->model('misc_model');
        $data['notes'] = $this->misc_model->get_notes($id, 'property');
        $this->load->view('admin/includes/sales_notes_template', $data);
    }

    public function client_change_data($customer_id)
    {
        if ($this->input->is_ajax_request()) {
            $data = [];

            $data['customer_has_properties'] = propertybase_customer_has_properties($customer_id);

            echo json_encode($data);
        }
    }

    public function properties_change_data($property_id = '')
    {
        if ($this->input->is_ajax_request()) {
            $data = [];

            if ($property_id !== '') {
                $data['billable_tasks'] = $this->propertybase_model->get_billable_tasks($property_id);
            } else {
                $data['billable_tasks'] = [];
            }

            echo json_encode($data);
        }
    }

    public function get_property_invoices_total()
    {
        if ($this->input->post()) {
            propertybase_load_invoices_total_template();
        }
    }

    public function invoice_table($property_id = '')
    {
        if (!has_permission('invoices', '', 'view')
            && !has_permission('invoices', '', 'view_own')
            && get_option('allow_staff_view_invoices_assigned') == '0') {
            ajax_access_denied();
        }

        $this->load->model('payment_modes_model');
        $data['payment_modes'] = $this->payment_modes_model->get('', [], true);

        $this->app->get_table_data(module_views_path(PROPERTYBASE_MODULE_NAME, 'admin/properties/tabs/tables/invoices'), [
            'propertyid' => $property_id,
            'data' => $data,
        ]);
    }

    public function returnAssignedProperties($assigned_type = '', $assigned_id = '')
    {
        if ($this->input->is_ajax_request() && !empty($assigned_type) && !empty($assigned_id)) {
            echo json_encode($this->propertybase_model->get_assigned_properties($assigned_type, $assigned_id));
            exit;
        }

        echo json_encode([]);
        exit;
    }

    public function savePropertyInCore($where, $property_id)
    {
        if ($where == 'contracts') {
        }

        if ($where == 'expenses') {
        }
    }

    public function expenses($id)
    {
        $this->load->model('expenses_model');
        $this->load->model('payment_modes_model');
        $data['payment_modes'] = $this->payment_modes_model->get('', [], true);

        $this->app->get_table_data(module_views_path(PROPERTYBASE_MODULE_NAME, 'admin/properties/tabs/tables/expenses'), [
            'propertyid' => $id,
            'data' => $data,
        ]);
    }

    public function add_expense()
    {
        if ($this->input->post()) {
            $this->load->model('expenses_model');
            $id = $this->expenses_model->add($this->input->post());
            if ($id) {
                set_alert('success', _l('added_successfully', _l('expense')));
                echo json_encode([
                    'url' => admin_url('projects/view/' . $this->input->post('project_id') . '/?group=project_expenses'),
                    'expenseid' => $id,
                ]);
                die;
            }
            echo json_encode([
                'url' => admin_url('projects/view/' . $this->input->post('project_id') . '/?group=project_expenses'),
            ]);
            die;
        }
    }

    public function get_expenses_total()
    {
        if ($this->input->post()) {
            $data['totals'] = $this->propertybase_model->get_expenses_total($this->input->post());

            if ($data['totals']['currency_switcher'] == true) {
                $this->load->model('currencies_model');
                $data['currencies'] = $this->currencies_model->get();
            }

            $this->load->model('expenses_model');
            $data['expenses_years'] = $this->expenses_model->get_expenses_years();

            if (count($data['expenses_years']) >= 1 && $data['expenses_years'][0]['year'] != date('Y')) {
                array_unshift($data['expenses_years'], ['year' => date('Y')]);
            }

            $data['_currency'] = $data['totals']['currencyid'];
            $this->load->view('admin/expenses/expenses_total_template', $data);
        }
    }

    public function lead_properties($lead_id)
    {
        $this->app->get_table_data(module_views_path(PROPERTYBASE_MODULE_NAME, 'admin/properties/tabs/leads/lead_properties'), [
            'leadid' => $lead_id
        ]);
    }

    public function property_leads($property_id)
    {
        $this->app->get_table_data(module_views_path(PROPERTYBASE_MODULE_NAME, 'admin/properties/tabs/leads/property_leads'), [
            'property_id' => $property_id
        ]);
    }

    public function property_maintenance_requests($property_id = '')
    {
        $this->app->get_table_data(module_views_path(PROPERTYBASE_MODULE_NAME, 'admin/maintenance_requests/maintenance_requests_table'), [
            'property_id' => $property_id,
            'postData' => $_POST
        ]);
    }

    public function qr_scanner()
    {
        $data['title'] = _l('propertybase_properties') . ' - ' . _l('propertybase_qr_scanner');
        $this->load->view('admin/properties/qr_scanner/manage', $data);
    }
}
