<?php

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

$custom_fields = get_table_custom_fields('propertybase_pr');

$aColumns = [
    db_prefix() . 'propertybase_properties.id as id',
    db_prefix() . 'propertybase_properties.name as name',
    'selected_agent',
    'property_status',
    'property_purpose',
    'ownership',
    db_prefix() . 'propertybase_properties.created_at as created_at'
];

$sIndexColumn = 'id';
$sTable = db_prefix() . 'propertybase_properties';
$join = [
    'LEFT JOIN ' . db_prefix() . 'propertybase_categories ON ' . db_prefix() . 'propertybase_categories.id = ' . db_prefix() . 'propertybase_properties.category',
];
$where = [];

if (!is_admin() && !has_permission('propertybase_properties', '', 'view')) {
    array_push($where, 'AND ' . db_prefix() . 'propertybase_properties.selected_agent=' . get_staff_user_id());
}

if (isset($postData['property_categories']) && $postData['property_categories']) {
    $propertyCategories = $postData['property_categories'];
    $propertyCategories = array_filter($propertyCategories);

    array_push($where, 'AND ' . db_prefix() . 'propertybase_properties.category IN (' . implode(',', $propertyCategories) . ')');
}

if (isset($postData['property_country']) && $postData['property_country']) {
    $propertyCountries = $postData['property_country'];
    $propertyCountries = array_filter($propertyCountries);

    array_push($where, 'AND ' . db_prefix() . 'propertybase_properties.country IN (' . implode(',', $propertyCountries) . ')');
}

if (isset($postData['property_agents']) && $postData['property_agents']) {
    $propertyAgents = $postData['property_agents'];
    $propertyAgents = array_filter($propertyAgents);

    array_push($where, 'AND ' . db_prefix() . 'propertybase_properties.selected_agent IN (' . implode(',', $propertyAgents) . ')');
}

if (isset($postData['ownership']) && $postData['ownership']) {
    $propertyOwnership = $postData['ownership'];
    $propertyOwnership = array_filter($propertyOwnership);

    array_push($where, 'AND ' . db_prefix() . 'propertybase_properties.ownership IN (' . implode(',', $propertyOwnership) . ')');
}

if (isset($postData['property_purpose']) && $postData['property_purpose']) {
    $propertyPurpose = $postData['property_purpose'];
    $propertyPurpose = array_filter($propertyPurpose);

    array_push($where, 'AND ' . db_prefix() . 'propertybase_properties.property_purpose IN (' . implode(',', $propertyPurpose) . ')');
}

if (isset($postData['energy_effiency']) && $postData['energy_effiency']) {
    $propertyEnergyEffiency = $postData['energy_effiency'];
    $propertyEnergyEffiency = array_filter($propertyEnergyEffiency);

    array_push($where, 'AND ' . db_prefix() . 'propertybase_properties.energy_effiency IN (' . implode(',', $propertyEnergyEffiency) . ')');
}

if (isset($postData['size']) && $postData['size']) {
    $propertySize = $postData['size'];
    array_push($where, 'AND ' . db_prefix() . 'propertybase_properties.size=' . $propertySize . '');
}

if (isset($postData['bathrooms']) && $postData['bathrooms']) {
    $propertyBathrooms = $postData['bathrooms'];
    array_push($where, 'AND ' . db_prefix() . 'propertybase_properties.bathrooms=' . $propertyBathrooms . '');
}

if (isset($postData['bedrooms']) && $postData['bedrooms']) {
    $propertyBedrooms = $postData['bedrooms'];
    array_push($where, 'AND ' . db_prefix() . 'propertybase_properties.bedrooms=' . $propertyBedrooms . '');
}

if (isset($postData['rooms']) && $postData['rooms']) {
    $propertyRooms = $postData['rooms'];
    array_push($where, 'AND ' . db_prefix() . 'propertybase_properties.rooms=' . $propertyRooms . '');
}

if (isset($postData['floor']) && $postData['floor']) {
    $propertyFloor = $postData['floor'];
    array_push($where, 'AND ' . db_prefix() . 'propertybase_properties.floor=' . $propertyFloor . '');
}

if (isset($postData['city']) && $postData['city']) {
    $propertyCity = $postData['city'];
    array_push($where, 'AND ' . db_prefix() . 'propertybase_properties.city LIKE "%' . $propertyCity . '%"');
}

if (isset($postData['price_from']) && $postData['price_from']) {
    $priceFrom = $postData['price_from'];
    array_push($where, 'AND (' . db_prefix() . 'propertybase_properties.sale_price >= ' . $priceFrom .
        ' OR ' . db_prefix() . 'propertybase_properties.rent_price_incl >= ' . $priceFrom .
        ' OR ' . db_prefix() . 'propertybase_properties.rent_price_excl >= ' . $priceFrom . ')');
}

if (isset($postData['price_to']) && $postData['price_to']) {
    $priceTo = $postData['price_to'];
    array_push($where, 'AND (' . db_prefix() . 'propertybase_properties.sale_price <= ' . $priceTo .
        ' OR ' . db_prefix() . 'propertybase_properties.rent_price_incl <= ' . $priceTo .
        ' OR ' . db_prefix() . 'propertybase_properties.rent_price_excl <= ' . $priceTo . ')');
}

if (isset($postData['property_status']) && $postData['property_status']) {
    $propertyStatus = $postData['property_status'];
    $propertyStatus = array_filter($propertyStatus);

    array_push($where, 'AND ' . db_prefix() . 'propertybase_properties.property_status IN (' . implode(',', $propertyStatus) . ')');
}

if (isset($postData['property_projects'])) {
    $propertyProjects = $postData['property_projects'];
    $propertyProjects = array_filter($propertyProjects);

    array_push($join, 'LEFT JOIN ' . db_prefix() . 'propertybase_property_assigned as filter_assigned_projects ON ' . db_prefix() . 'propertybase_properties.id = filter_assigned_projects.property_id');
    array_push($where, 'AND filter_assigned_projects.assigned_to = "project"');
    array_push($where, 'AND filter_assigned_projects.assigned_id IN (' . implode(',', $propertyProjects) . ')');
}

if (isset($postData['property_customers'])) {
    $propertyCustomers = $postData['property_customers'];
    $propertyCustomers = array_filter($propertyCustomers);

    array_push($join, 'LEFT JOIN ' . db_prefix() . 'propertybase_property_assigned ON ' . db_prefix() . 'propertybase_properties.id = ' . db_prefix() . 'propertybase_property_assigned.property_id');
    array_push($where, 'AND ' . db_prefix() . 'propertybase_property_assigned.assigned_to = "customers"');
    array_push($where, 'AND ' . db_prefix() . 'propertybase_property_assigned.assigned_id IN (' . implode(',', $propertyCustomers) . ')');
}

if (isset($postData['property_allocate_to'])) {
    $propertyAllocateTo = $postData['property_allocate_to'];
    $propertyAllocateTo = array_filter($propertyAllocateTo);
    $quotedAllocateTo = array_map(function ($item) {

        if ($item == 'customer') {
            $item = 'customers';
        }

        return "'" . $item . "'";
    }, $propertyAllocateTo);

    array_push($join, 'LEFT JOIN ' . db_prefix() . 'propertybase_property_assigned as assigned_to ON ' . db_prefix() . 'propertybase_properties.id = assigned_to.property_id');
    array_push($where, 'AND assigned_to.assigned_to IN (' . implode(',', $quotedAllocateTo) . ')');

}

foreach ($custom_fields as $key => $field) {
    $selectAs = (is_cf_date($field) ? 'date_picker_cvalue_' . $key : 'cvalue_' . $key);
    array_push($customFieldsColumns, $selectAs);
    array_push($aColumns, 'ctable_' . $key . '.value as ' . $selectAs);
    array_push($join, 'LEFT JOIN ' . db_prefix() . 'customfieldsvalues as ctable_' . $key . ' ON ' . db_prefix() . 'propertybase_properties.id = ctable_' . $key . '.relid AND ctable_' . $key . '.fieldto="' . $field['fieldto'] . '" AND ctable_' . $key . '.fieldid=' . $field['id']);
}

$result = data_tables_init($aColumns, $sIndexColumn, $sTable, $join, $where, [
    db_prefix() . 'propertybase_properties.id',
    db_prefix() . 'propertybase_categories.name as category_name',
]);

$output = $result['output'];
$rResult = $result['rResult'];


foreach ($rResult as $aRow) {
    $row = [];
    for ($i = 0; $i < count($aColumns); $i++) {

        $CI = &get_instance();
        $CI->load->model('propertybase_model');

        $assetMainImages = $CI->propertybase_model->get_property_main_image_attachment($aRow['id']);
        $propertyAssigned = $CI->propertybase_model->get_property_assign($aRow['id']);

        $row[] = $aRow['id'];

        $url = admin_url(PROPERTYBASE_MODULE_NAME . '/view/' . $aRow['id']);
        $assetImage = '<img class="mtop5 img img-responsive text-center propertybase-default-image-size" src="' . substr(module_dir_url(PROPERTYBASE_MODULE_NAME . '/uploads/default_image.jpg'), 0, -1) . '">';
        if (!empty($assetMainImages)) {
            $assetImageUrl = substr(module_dir_url(PROPERTYBASE_MODULE_NAME . '/uploads/property_images/main_image/' . $aRow['id'] . '/' . $assetMainImages[0]['file_name']), 0, -1);
            $assetImage = '<img class="mtop5 img img-responsive text-center propertybase-image-size-manage" src="' . $assetImageUrl . '">';
        }
        $row[] = $assetImage;

        $asset = '<a target="_blank" href="' . propertybase_get_property_single_page_url($aRow['id']) . '"><i class="fa fa-globe"></i></a>  <a href="' . $url . '">' . $aRow['name'] . '</a>';

        $asset .= '<div class="row-options">';
        $asset .= '<a href="' . admin_url(PROPERTYBASE_MODULE_NAME . '/view/' . $aRow['id']) . '">' . _l('view') . '</a>';
        $asset .= '<a href="' . admin_url(PROPERTYBASE_MODULE_NAME . '/create/' . $aRow['id']) . '"> | ' . _l('edit') . '</a>';

        if (has_permission('propertybase', '', 'delete')) {
            $asset .= ' | <a href="' . admin_url(PROPERTYBASE_MODULE_NAME . '/delete/' . $aRow['id']) . '" class="text-danger _delete">' . _l('delete') . '</a>';
        }

        $asset .= '</div>';

        $row[] = $asset;

        if (!empty($aRow['selected_agent'])) {
            $row[] = '<a href="' . admin_url('staff/profile/' . $aRow['selected_agent']) . '">' . staff_profile_image($aRow['selected_agent'], [
                    'staff-profile-image-small',
                ]) . '</a>';
        } else {
            $row[] = '';
        }

        $status = propertybase_get_status_data($aRow['property_status'])['badge'] ?? 'undefined';
        if ($aRow['property_status'] == 2 && !empty($propertyAssigned)) {
            $status .= propertybase_get_property_assigned_data($propertyAssigned);
        }

        $row[] = $status;

        $row[] = $aRow['category_name'];

        $row[] = _l(propertybase_property_purposes($aRow['property_purpose']));

        $row[] = propertybase_get_property_ownership_name($aRow['ownership']);

        $row[] = propertybase_formatted_property_location($aRow['id']);

        $row[] = '<span class="propertybase-manage-property-price">' . propertybase_get_property_price($aRow['id'], true, true) . '</span>';

        $row[] = _d($aRow['created_at']);

        foreach ($customFieldsColumns as $customFieldColumn) {
            $row[] = (strpos($customFieldColumn, 'date_picker_') !== false ? _d($aRow[$customFieldColumn]) : $aRow[$customFieldColumn]);
        }
    }

    $output['aaData'][] = $row;
}
