2026-05-22 20:21:54 +02:00
< ? php
include $_SERVER [ 'DOCUMENT_ROOT' ] . '/import/obj/ImportRecord.php' ;
include $_SERVER [ 'DOCUMENT_ROOT' ] . '/import/obj/Building.php' ;
include $_SERVER [ 'DOCUMENT_ROOT' ] . '/import/helper/Date.php' ;
include $_SERVER [ 'DOCUMENT_ROOT' ] . '/import/Clock/Clock.php' ;
include $_SERVER [ 'DOCUMENT_ROOT' ] . '/import/Clock/RealtimeClock.php' ;
require_once ( $_SERVER [ 'DOCUMENT_ROOT' ] . '/engine/classes/phpexcel/Classes/PHPExcel.php' );
require_once ( $_SERVER [ 'DOCUMENT_ROOT' ] . '/engine/classes/phpexcel/Classes/PHPExcel/IOFactory.php' );
require_once ( $_SERVER [ 'DOCUMENT_ROOT' ] . '/engine/classes/phpexcel/Classes/PHPExcel/Writer/Excel2007.php' );
//ini_set('display_errors', '1');
//ini_set('display_startup_errors', '1');
//error_reporting(E_ALL);
class Complex
{
private $user = null ;
private $types_comples = array ();
private $db = null ;
private $sphinx = null ;
private $sphinx2 = null ;
private $table = 'complex_list' ;
private $paymentTypes = array ();
private $housingClass = array ();
private $complex ;
private $objRequisitionsArray = false ;
private $objPricesArray = false ;
private $userIds = array ();
private $filter = array ();
private $page_obj = 1 ;
private $page = 1 ;
private $limit = 10 ;
private $listDecorations = array ();
private $user_id = 0 ;
public function __construct ( $db = null )
{
if ( $db ) {
$this -> db = $db ;
} else {
$pdo = new MysqlPdo ( hst , ndb , user , pass );
$sql = " SET NAMES 'utf8mb4' " ;
$pdo -> query ( $sql );
$this -> db = $pdo ;
}
$this -> set_types_complex ();
}
public function createImport ( $document ) {
$this -> set_user ();
$result = $this -> uploadFile ( $document , 'ImportDocuments' );
if ( $result ) {
$file_content = file_get_contents ( $result );
if ( $this -> endsWith ( $result , 'csv' )) {
$data = $this -> parseCsv ( mb_convert_encoding ( $file_content , 'utf-8' ));
} else if ( $this -> endsWith ( $result , 'xlsx' )) {
$temp_name = tempnam ( sys_get_temp_dir (), 'tmp-xlsx' );
file_put_contents ( $temp_name , $file_content );
$type = PHPExcel_IOFactory :: identify ( $temp_name );
$objReader = PHPExcel_IOFactory :: createReader ( $type );
$objPHPExcel = $objReader -> load ( $temp_name );
$data = [];
foreach ( $objPHPExcel -> getWorksheetIterator () as $worksheet ) {
// $worksheets[$worksheet->getTitle()] = $worksheet->toArray();
$data = $worksheet -> toArray ( '' );
break ;
}
} else {
return [ 'status' => false , 'message' => " Format not supported " ];
}
$columns = [];
$rows_count = 10 ;
foreach ( $data as $rowIndex => $row ) {
foreach ( $row as $key => $value ) {
if ( $rowIndex < $rows_count ) {
$value = is_string ( $value ) ? str_replace ( '"' , " ` " , $value ) : $value ;
$value = is_string ( $value ) ? preg_replace ( '/\s/' , " " , $value ) : $value ;
if ( isset ( $columns [ $key ])) {
$columns [ $key ][] = $value ;
} else {
$columns [ $key ] = [ $value ];
}
}
}
}
$response = [ 'head' => isset ( $data [ 0 ]) ? $data [ 0 ] : [] , 'body' => $columns ];
$insertSql = " INSERT INTO complex_house_import SET user_id = { $this -> user_id } , document = ' { $result } ', step = 2, document_preview = ' " . json_encode ( $response , JSON_UNESCAPED_UNICODE ) . " ' " ;
$status = $this -> db -> query ( $insertSql );
if ( $status ) {
$response [ 'id' ] = ( int ) $this -> db -> insert_id ();
$response [ 'step' ] = 2 ;
return $response ;
}
}
return $result ;
}
public function getImportHouse ( $import_id ) {
$this -> set_user ();
$sql = $this -> db -> query ( " SELECT * FROM complex_house_import WHERE id = $import_id AND user_id = { $this -> user_id } " );
$import = $this -> db -> fetch_assoc ( $sql );
$import [ 'document_preview' ] = json_decode ( str_replace ( ' ' , " " , $import [ 'document_preview' ]), true );
$import [ 'house_name_to_id' ] = json_decode ( $import [ 'house_name_to_id' ], true );
$import [ 'dynamic_fields' ] = json_decode ( $import [ 'dynamic_fields' ], true );
$import [ 'mapping_fields' ] = json_decode ( $import [ 'mapping_fields' ], true );
return $import ;
}
public function getImportHouseStatus ( $import_id ) {
$this -> set_user ();
$sql = $this -> db -> query ( " SELECT status, step FROM complex_house_import WHERE id = $import_id AND user_id = { $this -> user_id } " );
$import = $this -> db -> fetch_assoc ( $sql );
return $import ;
}
public function getHomeById ( $house_id ){
$sql = $this -> db -> query ( "
SELECT
house . name ,
ent . position AS entrance ,
floor . position AS floor ,
crn . note ,
room .* ,
cs . name AS status ,
house . name AS house_name
FROM complex_rooms room
JOIN complex_floors floor ON room . floor_id = floor . id
JOIN complex_entrances ent ON floor . complex_entrance_id = ent . id
JOIN complex_houses house ON ent . complex_house_id = house . id
LEFT JOIN complex_status cs ON cs . id = room . complex_status_id
LEFT JOIN complex_room_notes crn ON room . id = crn . room_id
WHERE house . id = $house_id
" );
while ( $import = $this -> db -> fetch_assoc ( $sql )){
$import [ 'attibutes' ] = $this -> getAttrById ( $import [ 'id' ]);
$house [] = $import ;
}
return $house ;
}
public function getAttrById ( $room_id ){
$attr = [];
$sql = $this -> db -> query ( "
SELECT * FROM complex_rooms_attribute WHERE complex_room_id = $room_id
" );
while ( $import = $this -> db -> fetch_assoc ( $sql )){
$attr [] = $import ;
}
return $attr ;
}
public function downloadHouse ( $house_id , $complex_name )
{
// НИЧЕГО не выводим!
while ( ob_get_level () > 0 ) { ob_end_clean (); }
// Н а всякий случай — не печатать ошибки в поток ответа
ini_set ( 'display_errors' , '0' );
ini_set ( 'display_startup_errors' , '0' );
error_reporting ( E_ALL );
// set_user может кидать Notice — обернём
if ( method_exists ( $this , 'set_user' )) {
try { $this -> set_user (); } catch ( \Throwable $e ) { /* молча */ }
}
// --- Утилита числовой очистки
$toInt = function ( $value ) {
if ( is_numeric ( $value )) return ( float ) $value ;
if ( is_string ( $value )) {
$clean = preg_replace ( '/[^\d\-\.\,]/u' , '' , $value );
$clean = str_replace ( ',' , '.' , $clean );
if ( $clean !== '' && is_numeric ( $clean )) return ( float ) $clean ;
}
return $value ;
};
// --- Получаем данные
$house = $this -> getHomeById ( $house_id );
if ( ! is_array ( $house )) $house = [];
// --- Справочники
$typeMapping = [
'apartment' => 'Квартира' ,
'apartments' => 'Апартаменты' ,
'parking_space' => 'Машиноместо' ,
'office' => 'Офис' ,
'storage_room' => 'Кладовка' ,
'warehouse' => 'Склад' ,
'retail_space' => 'Торговое Помещение' ,
'commercial_space' => 'Помещение свободного назначения' ,
'townhouse' => 'Таунхаус' ,
'villa' => 'Вилла' ,
'penthouse' => 'Пентхаус' ,
'duplex' => 'Дуплекс' ,
'cottage' => 'Коттедж' ,
];
$planningMapping = [
'none_of_the_above' => '' ,
'studio' => 'Студия' ,
'european_layout' => 'Европланировка' ,
'available' => 'Свободная планировка' ,
];
$window_placement_id = $this -> get_windows_placements () ? : [];
$decoration_types = $this -> get_decoration_types () ? : [];
// var_dump($window_placement_id);die;
// --- Сборка строк данных
$excelData = [];
foreach ( $house as $room ) {
$roomsAreas = [];
$balconiesAreas = [];
$loggiasAreas = [];
$bathroomsAreas = [];
// var_dump($room['decoration_id']);
// ВНИМАНИЕ: у тебя было 'attibutes'. Если в БД ключ 'attributes', то поправь:
$attrs = [];
if ( ! empty ( $room [ 'attributes' ]) && is_array ( $room [ 'attributes' ])) {
$attrs = $room [ 'attributes' ];
} elseif ( ! empty ( $room [ 'attibutes' ]) && is_array ( $room [ 'attibutes' ])) {
$attrs = $room [ 'attibutes' ];
}
foreach ( $attrs as $attr ) {
if ( empty ( $attr [ 'attribute_type' ]) || ! isset ( $attr [ 'area' ])) continue ;
switch ( $attr [ 'attribute_type' ]) {
case 'room' : $roomsAreas [] = $attr [ 'area' ]; break ;
case 'balcony' : $balconiesAreas [] = $attr [ 'area' ]; break ;
case 'loggia' : $loggiasAreas [] = $attr [ 'area' ]; break ;
case 'bathroom' : $bathroomsAreas [] = $attr [ 'area' ]; break ;
}
}
$roomAreaStr = implode ( ';' , $roomsAreas );
$bathroomAreaStr = implode ( ';' , $bathroomsAreas );
$balconyLoggiaStr = '' ;
if ( ! empty ( $loggiasAreas )) {
foreach ( $loggiasAreas as $a ) {
$a = trim ( preg_replace ( '/\s+/' , '' , ( string ) $a ));
$balconyLoggiaStr .= 'Лоджия:' . $a . ';' ;
}
}
if ( ! empty ( $balconiesAreas )) {
foreach ( $balconiesAreas as $a ) {
$a = trim ( preg_replace ( '/\s+/' , '' , ( string ) $a ));
$balconyLoggiaStr .= 'Балкон:' . $a . ';' ;
}
}
// var_dump($room);die;
$balconyLoggiaStr = rtrim ( $balconyLoggiaStr , ';' );
$balconyLoggiaStr = preg_replace ( '/\s*;\s*/' , ';' , $balconyLoggiaStr );
// Собираем строку данных. КЛЮЧИ ДОЛЖНЫ СОВПАДАТЬ С ЗАГОЛОВКАМИ В ШАБЛОНЕ!
$row = [
'Номер квартиры*' => isset ( $room [ 'number' ]) ? $room [ 'number' ] : '' ,
'Полная стоимость, р у б *' => isset ( $room [ 'total_amount' ]) ? $toInt ( $room [ 'total_amount' ]) : '' ,
'Название ЖК*' => $complex_name ? : '' ,
'Дом*' => isset ( $room [ 'house_name' ]) ? $room [ 'house_name' ] : '' ,
'Подъезд*' => isset ( $room [ 'entrance' ]) ? $room [ 'entrance' ] : '' ,
'Этаж*' => isset ( $room [ 'floor' ]) ? $room [ 'floor' ] : '' ,
'Статус помещения*' => isset ( $room [ 'status' ]) ? $room [ 'status' ] : '' ,
'Цена в рассрочку, р у б ' => ( isset ( $room [ 'installment_price' ]) && ( ! empty ( $room [ 'payment_types' ]) && strpos ( $room [ 'payment_types' ], 'INSTALLMENT' ) !== false )) ? $toInt ( $room [ 'installment_price' ]) : '' ,
'Ипотека' => ( ! empty ( $room [ 'payment_types' ]) && strpos ( $room [ 'payment_types' ], 'MORTGAGE' ) !== false ) ? 'Да' : '' ,
'Номер на площадке' => isset ( $room [ 'on_site_number' ]) ? $room [ 'on_site_number' ] : '' ,
'Код планировки' => isset ( $room [ 'layout_code' ]) ? $room [ 'layout_code' ] : '' ,
'Тип помещения*' => isset ( $typeMapping [ $room [ 'type' ]]) ? $typeMapping [ $room [ 'type' ]] : 'Квартира' ,
'Особенности планировки' => isset ( $planningMapping [ $room [ 'layout_feature' ]]) ? $planningMapping [ $room [ 'layout_feature' ]] : '' ,
'Кол-во комнат*' => isset ( $room [ 'rooms_count' ]) ? $room [ 'rooms_count' ] : '' ,
'Общая площадь, м2*' => isset ( $room [ 'area' ]) ? $toInt ( $room [ 'area' ]) : '' ,
'Жилая площадь, м2' => isset ( $room [ 'living_area' ]) ? $toInt ( $room [ 'living_area' ]) : '' ,
'Площадь кухни, м2' => isset ( $room [ 'kitchen_area' ]) ? $toInt ( $room [ 'kitchen_area' ]) : '' ,
'Расчетная площадь, м2' => isset ( $room [ 'estimated_area' ]) ? $toInt ( $room [ 'estimated_area' ]) : '' ,
'Описание' => isset ( $room [ 'description' ]) ? $room [ 'description' ] : '' ,
'Куда выходят окна' => ( ! empty ( $room [ 'windows_placement_id' ]) && ! empty ( $window_placement_id [ $room [ 'windows_placement_id' ] - 1 ][ 'name' ]))
? $window_placement_id [ $room [ 'windows_placement_id' ] - 1 ][ 'name' ] : '' ,
'Высота потолков' => isset ( $room [ 'ceiling_height' ]) ? $toInt ( $room [ 'ceiling_height' ]) : '' ,
'Кол-во лоджий' => isset ( $room [ 'loggias_count' ]) ? ( int ) $room [ 'loggias_count' ] : '' ,
'Кол-во балконов' => isset ( $room [ 'balconies_count' ]) ? ( int ) $room [ 'balconies_count' ] : '' ,
'Кол-во совмещенных санузлов' => isset ( $room [ 'combined_bathrooms_count' ]) ? ( int ) $room [ 'combined_bathrooms_count' ] : '' ,
'Кол-во раздельных санузлов' => isset ( $room [ 'seperated_bathrooms_count' ]) ? ( int ) $room [ 'seperated_bathrooms_count' ] : '' ,
'Отделка' => ( ! empty ( $room [ 'decoration_id' ]) && ! empty ( $decoration_types [ $room [ 'decoration_id' ] - 1 ][ 'name' ]))
? $decoration_types [ $room [ 'decoration_id' ] - 1 ][ 'name' ] : '' ,
'Номер помещения для БТИ' => isset ( $room [ 'bti_room_number' ]) ? $room [ 'bti_room_number' ] : '' ,
'Общая площадь по БТИ' => isset ( $room [ 'bti_total_area' ]) ? $toInt ( $room [ 'bti_total_area' ]) : '' ,
'Площадь без балкона' => isset ( $room [ 'area_without_balcony' ]) ? $toInt ( $room [ 'area_without_balcony' ]) : '' ,
'Площадь прихожей, м2' => isset ( $room [ 'hallway_area' ]) ? $toInt ( $room [ 'hallway_area' ]) : '' ,
'Общая площадь без жилой, м2' => isset ( $room [ 'total_area_excl_living' ]) ? $toInt ( $room [ 'total_area_excl_living' ]) : '' ,
'Общая площадь санузлов, м2' => isset ( $room [ 'total_bathroom_area' ]) ? $toInt ( $room [ 'total_bathroom_area' ]) : '' ,
'Общая площадь лоджий/балконов, м2' => isset ( $room [ 'total_balcony_loggia_area' ]) ? $toInt ( $room [ 'total_balcony_loggia_area' ]) : '' ,
// Если в шаблоне есть следующие столбцы — раскомментируй и УБЕДИСЬ, что названия совпадают
'Площадь комнаты, м2' => $roomAreaStr ,
'Площадь санузла, м2' => $bathroomAreaStr ,
'Площадь лоджии/балкона, м2' => $balconyLoggiaStr ,
'Примечание' => isset ( $room [ 'note' ]) ? $room [ 'note' ] : '' ,
];
// Нормализуем пробелы
$cleanRow = [];
foreach ( $row as $k => $v ) {
$cleanK = trim ( preg_replace ( '/[\s\x{00A0}]+/u' , ' ' , ( string ) $k ));
$cleanV = is_string ( $v ) ? trim ( preg_replace ( '/[\s\x{00A0}]+/u' , ' ' , $v )) : $v ;
$cleanRow [ $cleanK ] = $cleanV ;
}
$excelData [] = $cleanRow ;
}
// --- Загружаем шаблон
$inputFile = $_SERVER [ 'DOCUMENT_ROOT' ] . '/complexes/files/Пр име р _с тр а ницы_для_за г р у зки_О б ъе кто в_в_До м.xlsx' ;
if ( ! file_exists ( $inputFile )) {
// Нельзя писать в поток — отдадим пустой 400 JSON, чтоб фронт увидел ошибку
http_response_code ( 400 );
header ( 'Content-Type: application/json; charset=utf-8' );
echo json_encode ([ 'error' => 'Шаблон не найден: ' . $inputFile ], JSON_UNESCAPED_UNICODE );
exit ;
}
// Подключи PHPExcel до этого файла: require_once '.../Classes/PHPExcel.php';
$objPHPExcel = PHPExcel_IOFactory :: load ( $inputFile );
$sheet = $objPHPExcel -> getActiveSheet ();
// --- Читаем заголовки из первой строки шаблона
$headers = [];
$highestColumn = $sheet -> getHighestColumn ();
$highestColumnIndex = PHPExcel_Cell :: columnIndexFromString ( $highestColumn );
for ( $col = 0 ; $col < $highestColumnIndex ; $col ++ ) {
$cellValue = $sheet -> getCellByColumnAndRow ( $col , 1 ) -> getValue ();
if ( $cellValue instanceof PHPExcel_RichText ) {
$cellValue = $cellValue -> getPlainText ();
}
$headers [] = trim ( preg_replace ( '/[\s\x{00A0}]+/u' , ' ' , ( string ) $cellValue ));
}
// --- Перезаписываем заголовки (на случай «мусора»)
foreach ( $headers as $i => $hdr ) {
$sheet -> setCellValueByColumnAndRow ( $i , 1 , $hdr );
}
// --- Заполняем строки
$templateRow = 2 ;
// Получим диапазон последнего столбца
$highestColumn = $sheet -> getHighestColumn ();
// Функция копирования стилей и валидации
$copyRowFormat = function ( $srcRow , $dstRow ) use ( $sheet , $highestColumn ) {
// Преобразуем последнюю колонку в индекс (например, 'AF' -> 31)
$highestIndex = PHPExcel_Cell :: columnIndexFromString ( $highestColumn );
for ( $i = 0 ; $i < $highestIndex ; $i ++ ) {
$colLetter = PHPExcel_Cell :: stringFromColumnIndex ( $i );
$srcCell = $colLetter . $srcRow ;
$dstCell = $colLetter . $dstRow ;
// Копируем data validation (выпадающие списки, правила)
$dv = $sheet -> getDataValidation ( $srcCell );
if ( $dv ) {
$sheet -> setDataValidation ( $dstCell , clone $dv );
}
// Копируем формулу (если есть)
$formula = $sheet -> getCell ( $srcCell ) -> getValue ();
if ( is_string ( $formula ) && strpos ( $formula , '=' ) === 0 ) {
$sheet -> setCellValue ( $dstCell , $formula );
}
}
};
$rowNum = 2 ; // Если строка 2 — инструкции
foreach ( $excelData as $dataRow ) {
$copyRowFormat ( 2 , $rowNum );
$col = 0 ;
foreach ( $headers as $header ) {
$value = array_key_exists ( $header , $dataRow ) ? $dataRow [ $header ] : '' ;
$sheet -> setCellValueExplicitByColumnAndRow (
$col ,
$rowNum ,
$value
);
$col ++ ;
}
$rowNum ++ ;
}
// --- Отправляем во фронт как attachment (blob)
$filename = 'По ме ще ния_До ма _' . ( preg_replace ( '/\D+/' , '' , ( string ) $house_id ) ? : 'export' ) . '.xlsx' ;
header ( 'Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' );
header ( 'Content-Disposition: attachment; filename="' . $filename . '"' );
header ( 'Cache-Control: max-age=0' );
header ( 'Pragma: public' );
// Некоторые прокси любят знать длину — можно не ставить, чтобы не буферизовать целиком.
$objWriter = PHPExcel_IOFactory :: createWriter ( $objPHPExcel , 'Excel2007' );
$objWriter -> save ( 'php://output' );
exit ;
}
public function updateImportHouse ( $data , $import_id ) {
$this -> set_user ();
// complex_house_import
if ( $data && $import_id ) {
$sql = [];
foreach ( $data as $key => $value ) {
if ( is_string ( $value )) {
$sql [] = " $key =' $value ' " ;
} else if ( $key == 'step' && ( $value == 3 || $value == 4 ) ) {
continue ;
} else {
$sql [] = " $key = $value " ;
}
}
$sql = implode ( ' ,' , $sql );
$sql = " UPDATE complex_house_import SET $sql WHERE id= { $import_id } AND user_id = { $this -> user_id } " ;
$query = $this -> db -> query ( $sql );
if ( $query ) {
$import = $this -> db -> fetch_assoc ( $this -> db -> query ( " SELECT * FROM complex_house_import WHERE id = $import_id " ));
if ( isset ( $data [ 'step' ])) {
$mapping_fields = json_decode ( $import [ 'mapping_fields' ], true );
if ( $data [ 'step' ] == 3 ) {
if ( isset ( $mapping_fields [ 'house_name' ])) {
$scriptPath = $_SERVER [ 'DOCUMENT_ROOT' ] . '/cron/complexHouseImportGetHouses.php' ;
$logFile = $_SERVER [ 'DOCUMENT_ROOT' ] . '/cron/logs/complexHouseImportGetHouses.log' ;
// Параметры для передачи
$param1 = $import [ 'id' ];
$result = null ;
$retval = null ;
exec ( " php $scriptPath $param1 >> $logFile 2>/dev/null & " , $result , $retval );
$sql = " UPDATE complex_house_import SET status='get-houses:in_progress' WHERE id= { $import_id } AND user_id = { $this -> user_id } " ;
$query = $this -> db -> query ( $sql );
} else {
$sql = " UPDATE complex_house_import SET step = 3 WHERE id= { $import_id } AND user_id = { $this -> user_id } " ;
$query = $this -> db -> query ( $sql );
$import [ 'step' ] = 3 ;
// sleep(1);
return [ 'status' => true , 'data' => $import ];
}
} else if ( $data [ 'step' ] == 4 ) {
// return $mapping_fields;
if ( ! isset ( $mapping_fields [ 'complex_status_id' ]) && ! isset ( $mapping_fields [ 'type' ])) {
$sql = " UPDATE complex_house_import SET step = 5, status='in_progress' WHERE id= { $import_id } AND user_id = { $this -> user_id } " ;
$query = $this -> db -> query ( $sql );
if ( $query ) {
$this -> startImportHouse ( $import_id );
$import [ 'step' ] = 5 ;
return [ 'status' => true , 'data' => $import , 'message' => 'Starting import' ,];
}
} else {
$import [ 'step' ] = 4 ;
$sql = " UPDATE complex_house_import SET status='get-statuses-types:in_progress', step=4 WHERE id= { $import_id } AND user_id = { $this -> user_id } " ;
$query = $this -> db -> query ( $sql );
$scriptPath = $_SERVER [ 'DOCUMENT_ROOT' ] . '/cron/complexHouseImportGetStatusesAndTypes.php' ;
$logFile = $_SERVER [ 'DOCUMENT_ROOT' ] . '/cron/logs/complexHouseImportGetStatusesAndTypes.log' ;
// Параметры для передачи
$param1 = $import [ 'id' ];
$result = null ;
$retval = null ;
exec ( " php $scriptPath $param1 >> $logFile 2>/dev/null & " , $result , $retval );
// sleep(1);
return [ 'status' => true , 'data' => $import ];
}
} else if ( $data [ 'step' ] == 5 ) {
$this -> startImportHouse ( $import_id );
return [ 'status' => true , 'data' => $import , 'message' => 'Starting import' ,];
}
}
return [ 'status' => true , 'data' => $import , 'message' => 'Finding houses started' ,];
}
}
return [ 'status' => false , 'message' => 'empty id to update' ];
}
public function startImportHouse ( $import_id ) {
$this -> set_user ();
if ( $import_id ) {
$query = $this -> db -> query ( " SELECT id FROM complex_house_import
WHERE id = $import_id
AND step > 3
AND user_id = { $this -> user_id }
AND house_name_to_id IS NOT NULL
AND document IS NOT NULL " );
// TODO step
if ( $row = $this -> db -> fetch_assoc ( $query )) {
$scriptPath = $_SERVER [ 'DOCUMENT_ROOT' ] . '/cron/complexHouseImport.php' ;
$logFile = $_SERVER [ 'DOCUMENT_ROOT' ] . '/cron/logs/complexHouseImport.log' ;
// Параметры для передачи
$param1 = $row [ 'id' ];
$result = null ;
$retval = null ;
exec ( " php $scriptPath $param1 >> $logFile 2>/dev/null & " , $result , $retval );
return [
'status' => true ,
'message' => 'Import Started' ,
];
}
}
return [ 'status' => false , 'message' => " Invalid parameter id: $import_id " ];
}
public function uploadFile ( $file , $folder ) {
$Selectel = SelectelApi :: getTokenAndUrl ();
$token = $Selectel [ 0 ];
$storageUrl = $Selectel [ 1 ];
$uploaddir = $_SERVER [ 'DOCUMENT_ROOT' ] . " /files/ $folder / " ;
$newPhotos = [];
$originalName = str_replace ( " 0:/ " , " " , $file [ 'name' ]);
$strArray = explode ( " . " , $originalName );
$ext = end ( $strArray );
if ( ! in_array ( $ext , [ 'xlsx' , 'xls' , 'csv' ])) {
return [ 'status' => false , 'message' => 'Формат не подерживается' ];
};
$ext = mb_strtolower ( $ext );
$name = md5 ( time () . $originalName ) . " . " . $ext ;
$one = mb_substr ( $name , 0 , 1 );
$two = mb_substr ( $name , 1 , 1 );
$three = mb_substr ( $name , 3 , 1 );
$new_path = " $one / $two / $three / $name " ;
$fp = $uploaddir . $new_path ;
if ( ! is_dir ( $_SERVER [ 'DOCUMENT_ROOT' ] . " /files/ " )) {
mkdir ( $_SERVER [ 'DOCUMENT_ROOT' ] . " /files/ " );
}
if ( ! is_dir ( $_SERVER [ 'DOCUMENT_ROOT' ] . " /files/ " . " $folder " )) {
mkdir ( $_SERVER [ 'DOCUMENT_ROOT' ] . " /files/ $folder " );
}
if ( ! is_dir ( $_SERVER [ 'DOCUMENT_ROOT' ] . " /files/ $folder / $one " )) {
mkdir ( $_SERVER [ 'DOCUMENT_ROOT' ] . " /files/ $folder / $one " );
}
$two = mb_substr ( $name , 1 , 1 );
if ( ! is_dir ( $_SERVER [ 'DOCUMENT_ROOT' ] . " /files/ $folder / $one / $two " )) {
mkdir ( $_SERVER [ 'DOCUMENT_ROOT' ] . " /files/ $folder / $one / $two " );
}
$three = mb_substr ( $name , 3 , 1 );
if ( ! is_dir ( $_SERVER [ 'DOCUMENT_ROOT' ] . " /files/ $folder / $one / $two / $three " )) {
mkdir ( $_SERVER [ 'DOCUMENT_ROOT' ] . " /files/ $folder / $one / $two / $three " );
}
if ( is_uploaded_file ( $file [ 'tmp_name' ])) {
move_uploaded_file ( $file [ 'tmp_name' ], $fp );
} else {
rename ( $file [ 'tmp_name' ], $fp );
}
$SelectelApi = new SelectelApi ();
$contentType = $ext == 'csv'
? " text/ $ext "
: $ext == 'xls'
? " application/vnd.ms-excel "
: " application/vnd.openxmlformats-officedocument.spreadsheetml.sheet " ;
$r = $SelectelApi -> uploadFile ( $storageUrl , $token , $fp , " / $folder / " . $new_path , $contentType );
//если выложили в Selectel
if ( $r ) {
$new_path = " https://data.joywork.ru/ $folder / " . $new_path ;
unlink ( $fp );
return $new_path ;
} else {
// Local fallback: keep local path
return $fp ;
}
return null ;
}
public function get_complex_entrances ( $complex_id , $includes , $partner_id = 0 )
{
$this -> set_user ();
$result = array ();
$sql = " SELECT complex_entrances.*, ch.name as house_name, ch.parking as house_parking, ch.security as house_security, ch.fenced_area as house_fenced_area, ch.sports_ground as house_sports_ground, ch.play_ground as house_play_ground, ch.school as house_school, ch.kinder_garten as house_kinder_garten, ch.id as house_id, cl.name as complex_name FROM complex_entrances
JOIN complex_houses ch ON ch . id = complex_entrances . complex_house_id AND ( ch . deleted_at IS NULL OR ch . deleted_at = '0000-00-00 00:00:00' )
JOIN complex_list cl ON cl . id = ch . complex_id
WHERE ch . complex_id = { $complex_id } " ;
// echo($sql);die;
// echo($sql);
// die;
$q = $this -> db -> query ( $sql );
while ( $entrance = $this -> db -> fetch_assoc ( $q )) {
$floors = $this -> get_entrance_floors ( $entrance , $includes , $partner_id );
$entrance [ 'floors' ] = $floors ;
$result [] = $entrance ;
}
return $result ;
}
public function get_house_entrances ( $house_id , $includes , $partner_id = 0 , $has_token = false )
{
$this -> set_user ();
$result = array ();
$sql = " SELECT complex_entrances.*, ch.name as house_name, ch.parking as house_parking, ch.security as house_security, ch.fenced_area as house_fenced_area, ch.sports_ground as house_sports_ground, ch.play_ground as house_play_ground, ch.school as house_school, ch.kinder_garten as house_kinder_garten, ch.id as house_id, cl.name as complex_name FROM complex_entrances
JOIN complex_houses ch ON ch . id = complex_entrances . complex_house_id
JOIN complex_list cl ON cl . id = ch . complex_id
WHERE complex_entrances . complex_house_id = { $house_id } " ;
$q = $this -> db -> query ( $sql );
while ( $entrance = $this -> db -> fetch_assoc ( $q )) {
$floors = $this -> get_entrance_floors ( $entrance , $includes , $partner_id , $has_token );
$entrance [ 'floors' ] = $floors ;
$result [] = $entrance ;
}
return $result ;
}
public function updatePlanPhotoPosition ( $image_id , $position )
{
$sql = " UPDATE complex_house_plans_images SET `position` = $position WHERE id = { $image_id } " ;
$r = $this -> db -> query ( $sql );
return array ();
}
public function updateHousePlans ( $plan_ids , $fields )
{
$this -> set_user ();
$strArray = [];
$ids = implode ( ', ' , $plan_ids );
foreach ( $fields as $key => $value ) {
if ( $key == 'id' || ( empty ( $value ) && $value !== 0 && $value !== false )) {
continue ;
}
if ( is_string ( $value )) {
$strArray [] = " $key =' $value ' " ;
} else if ( is_bool ( $value )) {
$value = ( int ) $value ;
$strArray [] = " $key = $value " ;
} else {
$strArray [] = " $key = $value " ;
}
}
$str = implode ( ', ' , $strArray );
$sql = " UPDATE complex_house_plans SET $str WHERE id in ( { $ids } ) " ;
$this -> db -> query ( $sql );
return $fields ;
}
public function updateHouseFloorPlans ( $plan_ids , $floor_ids , $fields , $is_bulk = false )
{
$this -> set_user ();
$strArray = [];
$ids = implode ( ', ' , $plan_ids );
if ( ! $is_bulk ) {
$sql = " DELETE FROM complex_floors_plans WHERE `floor_plan_id` in ( { $ids } ) " ;
$q = $this -> db -> query ( $sql );
if ( ! empty ( $floor_ids )) {
foreach ( $floor_ids as $floor_id ) {
foreach ( $plan_ids as $plan_id ) {
$sql = " INSERT INTO complex_floors_plans SET `floor_id` = { $floor_id } , `floor_plan_id` = { $plan_id } " ;
$q = $this -> db -> query ( $sql );
}
}
}
}
foreach ( $fields as $key => $value ) {
if ( $key == 'id' || ( empty ( $value ) && $value !== 0 && $value !== false && ! is_array ( $value ))) {
continue ;
}
if ( in_array ( $key , [ 'entrances' , 'floor_positions' ])) {
$value = json_encode ( $value );
}
if ( is_string ( $value )) {
$strArray [] = " $key =' $value ' " ;
} else if ( is_bool ( $value )) {
$value = ( int ) $value ;
$strArray [] = " $key = $value " ;
} else {
$strArray [] = " $key = $value " ;
}
}
$str = implode ( ', ' , $strArray );
$sql = " UPDATE complex_house_floor_plans SET $str WHERE id in ( { $ids } ) " ;
$this -> db -> query ( $sql );
$result = array ();
foreach ( $plan_ids as $id ) {
$result [] = $this -> get_floor_plan ( $id );
}
return $result ;
}
public function isUsedRoomNumber ( $room_number , $floor_id ) {
$house_id = $this -> getFloorHouseId ( $floor_id );
if ( $house_id ) {
$find = $this -> db -> query ( " SELECT complex_rooms.number FROM complex_rooms
JOIN complex_floors ON complex_floors . id = complex_rooms . floor_id
JOIN complex_entrances ON complex_floors . complex_entrance_id = complex_entrances . id
JOIN complex_houses ON complex_entrances . complex_house_id = complex_houses . id
WHERE complex_houses . id = $house_id
AND complex_rooms . number = '{$room_number}'
" );
$row = $this -> db -> fetch_assoc ( $find );
return ( bool ) $row ;
}
}
public function generateRoomNumber ( $floor_id ) {
$house_id = $this -> getFloorHouseId ( $floor_id );
if ( $house_id ) {
$find = $this -> db -> query ( " SELECT MAX(CAST(complex_rooms.number AS UNSIGNED)) AS max_value FROM complex_rooms
JOIN complex_floors ON complex_floors . id = complex_rooms . floor_id
JOIN complex_entrances ON complex_floors . complex_entrance_id = complex_entrances . id
JOIN complex_houses ON complex_entrances . complex_house_id = complex_houses . id
WHERE complex_houses . id = $house_id
" );
$row = $this -> db -> fetch_assoc ( $find );
return $row ? $row [ 'max_value' ] + 1 : 1 ;
}
}
public function getFloorHouseId ( $floor_id ) {
$select = $this -> db -> query ( " SELECT complex_houses.id FROM complex_houses
JOIN complex_entrances ON complex_entrances . complex_house_id = complex_houses . id
JOIN complex_floors ON complex_floors . complex_entrance_id = complex_entrances . id
WHERE complex_floors . id = $floor_id
" );
$row = $this -> db -> fetch_assoc ( $select );
return $row ? $row [ 'id' ] : $row ;
}
public function getRoomsCountByStatusId ( $status_id )
{
if ( ! $status_id ) return false ;
$q = $this -> db -> query ( " SELECT COUNT(id) as count FROM complex_rooms WHERE `complex_status_id` = { $status_id } " );
return $this -> db -> fetch_assoc ( $q );
}
public function get_payment_types_list ()
{
$sql = " SELECT `code`, `label` FROM `apartment_payment_types` WHERE `is_active` = 1 ORDER BY `label` " ;
$rez = $this -> db -> query ( $sql );
$paymentTypes = array ();
if ( $this -> db -> num_rows ( $rez ) > 0 ) {
while ( $dbObject = $this -> db -> fetch_assoc ( $rez )) {
$paymentTypes [] = array (
'code' => $dbObject [ 'code' ],
'name' => $dbObject [ 'label' ]
);
}
}
return $paymentTypes ;
}
public function sendMessageToTelegram ( $chat_id , $text , $format = 'html' )
{
$token = '793676666:AAGFo66CjsmO2KxZVRwQbH8pLTvenpsHiHI' ;
require_once $_SERVER [ 'DOCUMENT_ROOT' ] . " /telegramm/vendor/autoload.php " ;
header ( 'Content-Type: application/json' );
try {
$bot = new \TelegramBot\Api\Client ( $token );
$bot -> sendMessage ( $chat_id , $text , $format );
}
catch ( Exception $e ) {
( new Logger ()) -> error ( $e -> getMessage ());
}
}
public function sendMessageToMax ( $max_user_id , $text )
{
$max = new MaxClass ();
$max -> send_messages_to_user ( $max_user_id , $text );
}
public function updateRequisitionWithClientsFunnelStep ( $room_id , $requisition_id )
{
$sqlSelectClientsFunnelStep = $this -> db -> query ( " SELECT cfs.*, fs.name, fs.stage, fs.funnel_id FROM `clients_funnel_step` as `cfs` LEFT JOIN `funnel_steps` as `fs` on cfs.step_id = fs.id WHERE cfs.req_id = { $requisition_id } " );
$steps = $this -> db -> fetch_assoc ( $sqlSelectClientsFunnelStep );
$sqlSelectRequisitionWhoWork = $this -> db -> query (
" SELECT
requisitions . `client_id` ,
users .*
FROM `requisitions`
LEFT JOIN `users` ON users . `id` = requisitions . `who_work`
WHERE requisitions . `id` = $requisition_id
" );
$requisition = $this -> db -> fetch_assoc ( $sqlSelectRequisitionWhoWork );
$history_requisition = json_decode ( $steps [ 'history_requisition' ], true );
$clients_funnel_step_id = $steps [ 'id' ];
$complex_room_id = NULL ;
$complex_status_id = NULL ;
$prev_id = 0 ;
$prev_next_id = 0 ;
$clientsFunnelStep = null ;
$newHistoryRequisition = [];
if ( $clients_funnel_step_id )
{
$sqlSelectClientsFunnelStep = $this -> db -> query ( " SELECT `step_id` FROM `clients_funnel_step` WHERE `id` = $clients_funnel_step_id " );
$clientsFunnelStep = $this -> db -> fetch_assoc ( $sqlSelectClientsFunnelStep );
}
foreach ( $history_requisition as $history )
{
if ( $history [ 'complex_room_id' ] != $room_id )
{
$complex_room_id = $history [ 'complex_room_id' ];
$complex_status_id = $history [ 'complex_status_id' ];
$valarr = json_decode ( str_replace ([ " \n " , " \t " , " \r " ], " " , $steps [ 'values' ]), true );
$arr = deClearInputElements ( $valarr );
$stepArr = json_decode ( $arr [ $history [ 'step_id' ]], true );
$prev_id = $stepArr [ 'prev_id' ] ? : 0 ;
$prev_next_id = $stepArr [ 'prev_next_id' ] ? : 0 ;
}
if ( $clientsFunnelStep && $clientsFunnelStep [ 'step_id' ]
&& $history [ 'step_id' ] != $clientsFunnelStep [ 'step_id' ]
){
$newHistoryRequisition [] = $history ;
}
}
if (( bool ) count ( $history_requisition ))
{
$newHistoryRequisition = json_encode ( $newHistoryRequisition ? : [], JSON_UNESCAPED_UNICODE );
$sqlUpdateClientsFunnelStep = " UPDATE `clients_funnel_step` SET `step_id` = $prev_id , `next_id` = $prev_next_id , `history_requisition` = ' { $newHistoryRequisition } ' WHERE `id` = $clients_funnel_step_id " ;
$this -> db -> query ( $sqlUpdateClientsFunnelStep );
$sqlUpdateRequisitions = " UPDATE
`requisitions`
SET
`complex_room_id` = '{$complex_room_id}' ,
`complex_status_id` = '{$complex_status_id}'
WHERE id = $requisition_id " ;
$this -> db -> query ( $sqlUpdateRequisitions );
}
else
{
$sqlUpdateRequisition = " UPDATE `requisitions` SET `complex_room_id` = NULL, `complex_status_id` = 0 WHERE id = $requisition_id " ;
$this -> db -> query ( $sqlUpdateRequisition );
}
if ( $requisition )
{
$text = " Заявка была исключена из очереди на бронирование. " ;
$client_id = $requisition [ 'client_id' ];
$now = new DateTime ( " now " );
$create_date = $now -> format ( 'Y-m-d H:i:s' );
$this -> db -> query ( " INSERT INTO `user_client_events` (
`user_id` ,
`req_id` ,
`client_id` ,
`type` ,
`comment` ,
`create_date`
)
VALUES (
$this -> user_id ,
$requisition_id ,
$client_id ,
'comment' ,
'{$text}' ,
'{$create_date}'
)
" );
if ( $requisition [ 'telegramm_notice' ]
&& $requisition [ 'telegramm_notice' ] == 1
&& $requisition [ 'telegramm_chat_id' ]
&& $requisition [ 'telegramm_chat_id' ] > 0
){
$text = " Заявка ID $requisition_id была исключена из очереди на бронирование. " ;
$this -> sendMessageToTelegram ( $requisition [ 'telegramm_chat_id' ], $text );;
}
}
$requisitions = $this -> get_room_requisitions ( $room_id );
$this -> generate_room_reservations_positions ( $room_id );
$reservations = $this -> get_room_reservations ( $room_id );
$can_change_queue = $reservations [ 'can_change_queue' ];
unset ( $reservations [ 'can_change_queue' ]);
$room = $this -> db -> fetch_assoc (
$this -> db -> query (
" SELECT
complex_rooms . `id` ,
cs . `name` as status_name ,
cs . `status` as status_type ,
cs . `color` as status_color
FROM `complex_rooms`
LEFT JOIN `complex_status` AS cs ON cs . `id` = complex_rooms . `complex_status_id`
WHERE complex_rooms . `id` = $room_id "
)
);
$complex_status_info = [
'status_name' => $room [ 'status_name' ],
'status_type' => $room [ 'status_type' ],
'status_color' => $room [ 'status_color' ]
];
if ( $room [ 'status_type' ] != 'reservation' && is_array ( $reservations ) && count ( $reservations ))
{
$complex_status_info = [
'status_name' => $reservations [ 0 ][ 'status_name' ],
'status_type' => $reservations [ 0 ][ 'status_type' ],
'status_color' => $reservations [ 0 ][ 'status_color' ],
];
}
return [
'requisitions' => $requisitions ,
'reservations' => $reservations ,
'can_change_queue' => $can_change_queue ,
'complex_status_info' => $complex_status_info
];
}
public function save_attributes ( $attributes , $room_id )
{
$existing = [];
$new_ids = [];
$q = $this -> db -> query ( " SELECT id FROM complex_rooms_attribute WHERE complex_room_id = " . intval ( $room_id ));
while ( $row = $this -> db -> fetch_assoc ( $q )) {
$existing [] = $row [ 'id' ];
}
foreach ( $attributes as $attr ) {
$attr_type = isset ( $attr -> attribute_type ) ? $attr -> attribute_type : null ;
$area = isset ( $attr -> area ) ? floatval ( $attr -> area ) : null ;
if ( isset ( $attr -> id ) && in_array ( $attr -> id , $existing )) {
$id = $attr -> id ;
$new_ids [] = $id ;
if ( ! $attr_type || $area === null ) {
$this -> db -> query ( " DELETE FROM complex_rooms_attribute WHERE id = $id " );
continue ;
}
$new_ids [] = $id ;
$this -> db -> query ( "
UPDATE complex_rooms_attribute
SET attribute_type = '{$attr_type}' , area = { $area }
WHERE id = { $id }
" );
} else {
if ( ! $attr_type || $area === null ) {
continue ;
}
$this -> db -> query ( "
INSERT INTO complex_rooms_attribute ( complex_room_id , attribute_type , area )
VALUES ( '{$room_id}' , '{$attr_type}' , { $area })
" );
}
}
if ( ! empty ( $existing )) {
$to_delete = array_diff ( $existing , $new_ids );
if ( ! empty ( $to_delete )) {
$ids = implode ( ',' , array_map ( 'intval' , $to_delete ));
$this -> db -> query ( " DELETE FROM complex_rooms_attribute WHERE id IN ( $ids ) " );
}
}
}
public function update_room ( $room )
{
$attributes = $room -> attributes ;
unset ( $room -> attributes );
$room_id = $room -> id ;
$this -> save_attributes ( $attributes , $room_id );
if ( $room -> note ) {
$note = ( string ) $room -> note ;
$note = str_replace ( " ' " , " '' " , $note );
$sql = " SELECT COUNT(*) as count FROM complex_room_notes WHERE room_id = { $room -> id } " ;
$result = $this -> db -> query ( $sql );
$count = $this -> db -> fetch_assoc ( $result );
if ( $count [ 'count' ] > 0 ) {
// Если запись существует, делаем UPDATE
$update_sql = " UPDATE complex_room_notes SET note = ' { $note } ' WHERE room_id = { $room -> id } " ;
$this -> db -> query ( $update_sql );
} else {
// Если записи нет, делаем INSERT
$insert_sql = " INSERT INTO complex_room_notes (`room_id`, `note`) VALUES ( { $room -> id } , ' { $note } ') " ;
$this -> db -> query ( $insert_sql );
}
}
if ( $room -> requisition_id )
{
return $this -> updateRequisitionWithClientsFunnelStep ( $room -> id , $room -> requisition_id );
}
if ( $room -> update_positions )
{
$sql = " UPDATE `requisitions` SET `position` = CASE `id` " ;
foreach ( $room -> update_positions as $key => $update )
{
$sql .= " WHEN { $update -> id } THEN { $update -> position } " ;
}
$sql .= " ELSE `position` END WHERE `id` IN ( " ;
$sql .= implode ( ', ' , array_map ( function ( $item ) { return $item -> id ; }, $room -> update_positions ));
$sql .= " ) " ;
// Execute the query using your database connection
$this -> db -> query ( $sql );
return true ;
}
$required_fields = [ 'number' , 'area' , 'complex_status_id' ];
if ( $room -> type === 'apartment' || $room -> type === 'apartments' ||
$room -> type === 'townhouse' || $room -> type === 'villa' ||
$room -> type === 'penthouse' || $room -> type === 'duplex' || $room -> type === 'cottage' ) {
$required_fields [] = 'rooms_count' ;
}
$errors = [];
$strArray = [];
$q = $this -> db -> query ( " SELECT id, number, complex_status_id FROM complex_rooms WHERE id = { $room -> id } " );
$old_room = $this -> db -> fetch_assoc ( $q );
foreach ( $room as $key => $value ) {
if ( in_array ( $key , $required_fields ) && empty ( $value )) {
$errors [ $key ] = 'required' ;
continue ;
}
if ( $key == 'id' ) {
continue ;
}
if ( $key == 'inPdf' ) {
continue ;
}
if ( $key == 'decoration_id' ) {
if ( is_string ( $value )) {
$sql = " INSERT INTO decoration_types SET `name` = ' { $value } ' " ;
$q = $this -> db -> query ( $sql );
$id = $this -> db -> insert_id ();
$value = $id ;
}
}
if ( $key == 'number' && $old_room [ 'number' ] != $value ) {
if ( $this -> isUsedRoomNumber ( $value , $room -> floor_id )) {
$errors [ $key ] = 'должен быть уникальным.' ;
continue ;
}
}
if ( $key === 'note' ) {
continue ;
}
if ( empty ( $value )) {
if ( $key === 'total_amount' ) {
$strArray [] = " $key =0 " ;
}
else {
$strArray [] = " $key =NULL " ;
}
} else {
if ( is_string ( $value )) {
$strArray [] = " $key =' $value ' " ;
} else {
$strArray [] = " $key = $value " ;
}
}
if ( $key == 'complex_status_id' && $old_room [ 'complex_status_id' ] != $value )
{
$complex_status = new ComplexStatus ( $value );
if ( $complex_status -> status !== 'reservation' )
{
$old_complex_status_id = $old_room [ 'complex_status_id' ];
$sql = " SELECT
requisitions . `id` AS req_id ,
requisitions . `client_id` ,
users .*
FROM `requisitions`
LEFT JOIN `users` ON users . `id` = requisitions . `who_work`
LEFT JOIN `complex_status` AS cs ON cs . `id` = $old_complex_status_id
WHERE `complex_room_id` = { $room -> id }
AND requisitions . `deleted` = 0
AND cs . `status` = 'reservation'
" ;
$requisitions = $complex_status :: $db -> query ( $sql ) -> fetchAll ();
foreach ( $requisitions as $req )
{
$text = " Заявка была исключена из очереди на бронирование. " ;
$req_id = $req [ 'req_id' ];
$client_id = $req [ 'client_id' ];
$user_id = $_SESSION [ 'id' ];
$now = new DateTime ( " now " );
$create_date = $now -> format ( 'Y-m-d H:i:s' );
if ( $req_id && $client_id && $user_id && $create_date )
{
$complex_status :: $db -> query ( " INSERT INTO `user_client_events` (
`user_id` ,
`req_id` ,
`client_id` ,
`type` ,
`comment` ,
`create_date`
)
VALUES (
$user_id ,
$req_id ,
$client_id ,
'comment' ,
'{$text}' ,
'{$create_date}'
)
" );
if ( $req [ 'telegramm_notice' ]
&& $req [ 'telegramm_notice' ] == 1
&& $req [ 'telegramm_chat_id' ]
&& $req [ 'telegramm_chat_id' ] > 0
){
$text = " Заявка ID $req_id была исключена из очереди на бронирование. " ;
$complex = new Complex ();
$complex -> sendMessageToTelegram ( $req [ 'telegramm_chat_id' ], $text );;
}
}
mysql_query ( " UPDATE `requisitions` SET `complex_status_id` = 0, `complex_room_id` = NULL WHERE id = { $req_id } " );
}
}
}
}
if ( count ( $errors )) {
return [ 'status' => false , 'errors' => $errors ];
}
// $str = preg_replace('/note\s*=\s*[^,]+,?/', '', $str);
// var_dump($strArray);die;
$str = implode ( ', ' , $strArray );
$sql = " UPDATE complex_rooms SET $str WHERE id= { $room -> id } " ;
$q = $this -> db -> query ( $sql );
$q = $this -> db -> query ( " SELECT complex_rooms.*,
cs . id as status_id ,
cs . name as status_name ,
cs . status as status_type ,
cs . color as status_color
FROM complex_rooms LEFT JOIN complex_status cs ON complex_rooms . complex_status_id = cs . id and cs . is_archive = 0 WHERE complex_rooms . id = { $room -> id } " );
$room = $this -> db -> fetch_assoc ( $q );
$room [ 'reservations' ] = $this -> get_room_reservations ( $room [ 'id' ]);
$room [ 'note' ] = $this -> get_room_note ( $room [ 'id' ]);
$room [ 'can_change_queue' ] = $room [ 'reservations' ][ 'can_change_queue' ];
unset ( $room [ 'reservations' ][ 'can_change_queue' ]);
$room [ 'complex_status_info' ] = [
'status_id' => $room [ 'status_id' ],
'status_name' => $room [ 'status_name' ],
'status_type' => $room [ 'status_type' ],
'status_color' => $room [ 'status_color' ]
];
if ( $room [ 'status_type' ] != 'reservation' && is_array ( $room [ 'reservations' ]) && count ( $room [ 'reservations' ]))
{
$room [ 'complex_status_info' ] = [
'status_id' => $room [ 'reservations' ][ 0 ][ 'status_id' ],
'status_name' => $room [ 'reservations' ][ 0 ][ 'status_name' ],
'status_type' => $room [ 'reservations' ][ 0 ][ 'status_type' ],
'status_color' => $room [ 'reservations' ][ 0 ][ 'status_color' ],
];
}
$room [ 'installment_plans' ] = [];
// Если тип оплаты содержит INSTALLMENT — подгрузим доступные рассрочки по дому
if ( ! empty ( $room [ 'payment_types' ])) {
$paymentTypes = is_array ( $room [ 'payment_types' ])
? $room [ 'payment_types' ]
: json_decode ( $room [ 'payment_types' ], true );
if ( in_array ( 'INSTALLMENT' , $paymentTypes )) {
// Получим house_id через этаж
$house_q = $this -> db -> query ( " SELECT e.complex_house_id AS house_id
FROM complex_entrances e
INNER JOIN complex_floors f ON f . complex_entrance_id = e . id
WHERE f . id = { $room [ 'floor_id' ]}
LIMIT 1 " );
$house = $this -> db -> fetch_assoc ( $house_q );
if ( $house && isset ( $house [ 'house_id' ])) {
$house_id = ( int ) $house [ 'house_id' ];
$installment_sql = " SELECT i.*, chi.end_date as house_installment_end_date
FROM installments i
INNER JOIN complex_house_installments chi ON chi . installment_id = i . id
WHERE chi . house_id = { $house_id }
AND i . is_archive = 0
AND ( chi . end_date IS NULL OR chi . end_date >= CURDATE ()) " ;
$installment_q = $this -> db -> query ( $installment_sql );
$installments = [];
while ( $plan = $this -> db -> fetch_assoc ( $installment_q )) {
$installments [] = [
'id' => $plan [ 'id' ],
'name' => $plan [ 'name' ],
'description' => $plan [ 'description' ],
'type' => $plan [ 'type' ],
'initial_payment' => $plan [ 'initial_payment' ],
'payment_period' => json_decode ( $plan [ 'payment_period' ], true ),
'allow_change_on_close' => $plan [ 'allow_change_on_close' ],
'interest_rate' => $plan [ 'interest_rate' ],
'comment' => $plan [ 'comment' ],
'house_installment_end_date' => $plan [ 'house_installment_end_date' ]
];
}
$room [ 'installment_plans' ] = $installments ;
}
}
}
return $room ;
}
public function save_room ( $room )
{
$attributes = $room -> attributes ;
unset ( $room -> attributes );
$required_fields = [ 'number' , 'area' , 'complex_status_id' , 'total_amount' ];
if ( $room -> type === 'apartment' || $room -> type === 'apartments' ||
$room -> type === 'townhouse' || $room -> type === 'villa' ||
$room -> type === 'penthouse' || $room -> type === 'duplex' || $room -> type === 'cottage' ) {
$required_fields [] = 'rooms_count' ;
}
$this -> set_user ();
$strArray = [];
$errors = [];
$note = null ;
// if (!isset($room->position)) {
// $floor_id = (int)$room->floor_id;
// $q = $this->db->query("SELECT MAX(position) as max_position FROM complex_rooms WHERE floor_id = $floor_id");
// $res = $this->db->fetch_assoc($q);
// $room->position = (int)$res['max_position'] + 1;
// }
foreach ( $room as $key => $value ) {
if ( in_array ( $key , $required_fields ) && empty ( $value )) {
$errors [ $key ] = 'required' ;
continue ;
}
if ( $key == 'id' || empty ( $value )) {
continue ;
}
if ( $key == 'decoration_id' ) {
if ( is_string ( $value )) {
$sql = " INSERT INTO decoration_types SET `name` = ' { $value } ' " ;
$q = $this -> db -> query ( $sql );
$id = $this -> db -> insert_id ();
$value = $id ;
}
}
if ( $key == 'note' ) {
$note = str_replace ( " ' " , " '' " , $value );
continue ;
}
if ( $key == 'number' ) {
if ( $this -> isUsedRoomNumber ( $value , $room -> floor_id )) {
$errors [ $key ] = 'должен быть уникальным.' ;
continue ;
}
}
if ( is_string ( $value )) {
$strArray [] = " $key =' $value ' " ;
} else {
$strArray [] = " $key = $value " ;
}
}
if ( count ( $errors )) {
return [ 'status' => false , 'errors' => $errors ];
}
$str = implode ( ', ' , $strArray );
$sql = " INSERT INTO complex_rooms SET { $str } " ;
$q = $this -> db -> query ( $sql );
$id = $this -> db -> insert_id ();
if ( $note != null ) {
// делаем INSERT
$insert_sql = " INSERT INTO complex_room_notes (`room_id`, `note`) VALUES ( { $id } , ' { $note } ') " ;
$this -> db -> query ( $insert_sql );
}
$q = $this -> db -> query ( " SELECT complex_rooms.*,
cs . name as status_name ,
cs . status as status_type ,
cs . color as status_color ,
crn . note
FROM complex_rooms
LEFT JOIN complex_status cs ON complex_rooms . complex_status_id = cs . id
LEFT JOIN complex_room_notes crn ON crn . room_id = complex_rooms . id
AND cs . is_archive = 0 WHERE complex_rooms . id = $id
" );
$room = $this -> db -> fetch_assoc ( $q );
$room [ 'complex_status_info' ] = [
'status_id' => $room [ 'status_id' ],
'status_name' => $room [ 'status_name' ],
'status_type' => $room [ 'status_type' ],
'status_color' => $room [ 'status_color' ]
];
$this -> save_attributes ( $attributes , $id );
return $room ;
}
public function get_room_entrance ( $id )
{
// $rooms_sql = "SELECT
// complex_rooms.*,
// MAX(c_house_p_i.url) as plan_url,
// c_floor.position as floor,
// c_entrance.id as entrance_id,
// c_house.name as house_name,
// c_house.id as house_id,
// c_complex.name as complex_name
// FROM complex_rooms
// LEFT JOIN complex_rooms_plans c_room_p ON c_room_p.room_id = complex_rooms.id
// LEFT JOIN complex_floors c_floor ON c_floor.id = complex_rooms.floor_id
// LEFT JOIN complex_entrances c_entrance ON c_entrance.id = c_floor.complex_entrance_id
// LEFT JOIN complex_houses c_house ON c_house.id = c_entrance.complex_house_id
// LEFT JOIN complex_list c_complex ON c_complex.id = c_house.complex_id
// LEFT JOIN complex_house_plans_images c_house_p_i ON c_room_p.plan_id = c_house_p_i.plan_id AND c_house_p_i.position = 1
// WHERE complex_rooms.id = {$id}
// GROUP BY complex_rooms.id
// ORDER BY complex_rooms.position;
// ";
// $rooms_q = $this->db->query($rooms_sql);
// $room = $this->db->fetch_assoc($rooms_q);
$entrance_sql = $this -> db -> query ( " SELECT complex_entrances.id as id FROM complex_entrances
LEFT JOIN complex_floors c_floor ON c_floor . complex_entrance_id = complex_entrances . id
LEFT JOIN complex_rooms c_room ON c_room . floor_id = c_floor . id
WHERE c_room . id = { $id }
" );
$entranceRow = $this -> db -> fetch_assoc ( $entrance_sql );
$sql = " SELECT complex_entrances.*, ch.name as house_name, ch.parking as house_parking, ch.security as house_security, ch.fenced_area as house_fenced_area, ch.sports_ground as house_sports_ground, ch.play_ground as house_play_ground, ch.school as house_school, ch.kinder_garten as house_kinder_garten, ch.id as house_id, cl.name as complex_name, cl.id as complex_id FROM complex_entrances
JOIN complex_houses ch ON ch . id = complex_entrances . complex_house_id
JOIN complex_list cl ON cl . id = ch . complex_id
WHERE complex_entrances . id = { $entranceRow [ 'id' ]} " ;
$q = $this -> db -> query ( $sql );
$entrance = $this -> db -> fetch_assoc ( $q );
$floors = $this -> get_entrance_floors ( $entrance , [ 'rooms' ]);
$entrance [ 'floors' ] = $floors ;
return $entrance ;
}
public function get_room_requisitions ( $room_id )
{
if ( ! $room_id ) return null ;
$requisition_sql = $this -> db -> query (
" SELECT
requisitions . `id` ,
requisitions . `name` ,
requisitions . `description` ,
CASE
WHEN requisitions . `funnel_id` != 0 THEN req_funnel . `name`
ELSE req_funnel_default . `name`
END as funnel_name ,
clients . `fio` as client_fio ,
clients . `phone` as client_phone ,
users . `last_name` as responsible_last_name ,
users . `first_name` as responsible_first_name ,
users . `middle_name` as responsible_middle_name
FROM requisitions
LEFT JOIN funnel req_funnel ON requisitions . `funnel_id` = req_funnel . `id` AND req_funnel . `deleted` != 1
LEFT JOIN funnel_default req_funnel_default ON req_funnel_default . `agency_id` = requisitions . `who_work`
LEFT JOIN clients on clients . `id` = requisitions . `client_id`
LEFT JOIN users on users . `id` = requisitions . `who_work`
WHERE requisitions . `complex_room_id` = { $room_id }
AND requisitions . `deleted` = 0
ORDER BY requisitions . created_at DESC "
);
return $this -> db -> result_pdo ( $requisition_sql ) ? : [];
}
public function get_room_note ( $room_id ) {
$sql = " SELECT note FROM complex_room_notes WHERE room_id = { $room_id } " ;
$q = $this -> db -> query ( $sql );
$note = $this -> db -> fetch_assoc ( $q );
return $note ? $note [ 'note' ] : '' ;
}
public function get_room_reservations ( $room_id , $generate_positions = false )
{
if ( ! $room_id ) return null ;
if ( $generate_positions )
{
$this -> generate_room_reservations_positions ( $room_id );
}
$requisition_sql = $this -> db -> query (
" SELECT
requisitions . `id` ,
requisitions . `name` ,
requisitions . `description` ,
requisitions . `position` ,
requisitions . `reservation_updated_at` ,
requisitions . `who_work` ,
requisitions . `doers_confirm` ,
requisitions . `doers` ,
CASE
WHEN requisitions . `funnel_id` != 0 THEN req_funnel . `name`
ELSE req_funnel_default . `name`
END AS funnel_name ,
users . `last_name` AS responsible_last_name ,
users . `first_name` AS responsible_first_name ,
users . `middle_name` AS responsible_middle_name ,
users . `email` AS responsible_email ,
users . `phone` AS responsible_phone ,
cs . `id` as status_id ,
cs . `name` as status_name ,
cs . `status` as status_type ,
cs . `color` as status_color ,
csr . `can_change_booking_queue` ,
csr . `booking_day` ,
csr . `booking_hour`
FROM requisitions
LEFT JOIN funnel req_funnel ON requisitions . `funnel_id` = req_funnel . `id` AND req_funnel . `deleted` != 1
LEFT JOIN funnel_default req_funnel_default ON req_funnel_default . `agency_id` = requisitions . `who_work`
LEFT JOIN users ON users . `id` = requisitions . `who_work`
LEFT JOIN complex_status AS cs ON cs . `id` = requisitions . `complex_status_id`
LEFT JOIN complex_status_reservation AS csr ON csr . `complex_status_id` = cs . `id`
WHERE requisitions . `complex_room_id` = $room_id
AND requisitions . `deleted` = 0
AND cs . `status` = 'reservation'
ORDER BY requisitions . `position` ASC "
);
$result = $this -> db -> result_pdo ( $requisition_sql );
$newDataReservations = [];
$can_change_booking_queue = [];
if ( $result )
{
foreach ( $result as $item )
{
$item_ccbq = json_decode ( $item [ 'can_change_booking_queue' ]);
$can_change_booking_queue = ! empty ( $item_ccbq ) && is_array ( $item_ccbq ) ? array_merge ( $item_ccbq , $can_change_booking_queue ) : $can_change_booking_queue ;
$booking_date = new DateTime ( $item [ 'reservation_updated_at' ]);
if ( ! empty ( $item [ 'booking_day' ]))
{
$booking_date = $booking_date -> modify ( '+' . $item [ 'booking_day' ] . ' day' );
}
if ( ! empty ( $item [ 'booking_hour' ]))
{
$booking_date = $booking_date -> modify ( '+' . $item [ 'booking_hour' ] . ' hour' );
}
$userId = $this -> user_id ;
if ( isset ( $_SESSION [ 'id' ])) {
$userId = $_SESSION [ 'id' ];
}
if ( ! empty ( $item [ 'booking_day' ]) || ! empty ( $item [ 'booking_hour' ])) {
$item [ 'completion_time' ] = $booking_date -> format ( 'd.m.Y H:i:s' );
} else {
$item [ 'completion_time' ] = null ;
}
$user = new User ;
$user -> get ( $userId );
$requisition = new Requisitions ();
$userIdsWork = $requisition -> getIdsUsers ( $userId );
$item [ 'can_read_details' ] = false ;
if ( $item [ 'who_work' ] == $user -> id )
{
$item [ 'can_read_details' ] = true ;
}
else if ( $user -> agency > 0 || $_SESSION [ 'users_admin' ] > 0 )
{
$item [ 'can_read_details' ] = true ;
}
else if ( $user -> manager > 0 )
{
if ( ! empty ( $userIdsWork ))
{
if ( in_array ( $item [ 'who_work' ], $userIdsWork ))
{
$item [ 'can_read_details' ] = true ;
}
}
}
else if ( ! empty ( $item [ 'doers' ]))
{
$doers1 = json_decode ( html_entity_decode ( $item [ 'doers' ]), true );
$item [ 'doers1' ] = $doers1 ;
if ( isset ( $doers1 [ $userId ]) && $doers1 [ $userId ] == 1 )
{
$item [ 'can_read_details' ] = true ;
}
}
$newDataReservations [] = $item ;
}
}
$newDataReservations [ 'can_change_queue' ] = in_array ( $user -> id , $can_change_booking_queue );
return $newDataReservations ;
}
public function generate_room_reservations_positions ( $room_id )
{
$requisition_sql = $this -> db -> query (
" SELECT
requisitions . `id`
FROM requisitions
JOIN complex_status ON complex_status . `id` = requisitions . `complex_status_id`
LEFT JOIN complex_status_reservation AS csr ON csr . `complex_status_id` = complex_status . `id`
WHERE requisitions . `complex_room_id` = $room_id
AND requisitions . `deleted` = 0
AND complex_status . `status` = 'reservation'
ORDER BY requisitions . `position` ASC "
);
$result = $this -> db -> result_pdo ( $requisition_sql );
$ids = array_column ( $result , 'id' );
$position = 1 ;
if ( $ids )
{
foreach ( $ids as $id )
{
$sql = " UPDATE `requisitions` SET `position` = $position WHERE`id` = $id " ;
$this -> db -> query ( $sql );
$position ++ ;
}
}
}
public function get_room_requisition ( $room_id )
{
$requisition_sql = $this -> db -> query (
" SELECT
requisitions . id ,
requisitions . name ,
requisitions . description ,
CASE
WHEN requisitions . funnel_id != 0 THEN req_funnel . name
ELSE req_funnel_default . name
END as funnel_name ,
clients . fio as client_fio ,
clients . phone as client_phone ,
users . last_name as responsible_last_name ,
users . first_name as responsible_first_name ,
users . middle_name as responsible_middle_name
FROM requisitions
LEFT JOIN funnel req_funnel ON requisitions . funnel_id = req_funnel . id AND req_funnel . deleted != 1
LEFT JOIN funnel_default req_funnel_default ON req_funnel_default . agency_id = requisitions . who_work
LEFT JOIN clients on clients . id = requisitions . client_id
LEFT JOIN users on users . id = requisitions . who_work
WHERE requisitions . complex_room_id = { $room_id }
ORDER BY requisitions . created_at DESC "
);
$requisition = $this -> db -> fetch_assoc ( $requisition_sql );
$requisition = $requisition ? : [];
return $requisition ;
}
public function copy_room ( $room_id , $floor_id , $position = 0 )
{
$this -> set_user ();
$sql = " SELECT * FROM complex_rooms WHERE id = { $room_id } " ;
$q = $this -> db -> query ( $sql );
$room = $this -> db -> fetch_assoc ( $q );
$strArray = [];
foreach ( $room as $key => $value ) {
if (
$key == 'id' ||
$key == 'position' ||
$key == 'floor_id' ||
$key == 'created_at' ||
$key == 'updated_at' ||
empty ( $value )
) {
continue ;
}
if ( $key == 'number' ) {
$value = $this -> generateRoomNumber ( $floor_id );
}
if ( is_string ( $value )) {
$strArray [] = " $key =' $value ' " ;
} else {
$strArray [] = " $key = $value " ;
}
}
$strArray [] = " floor_id= $floor_id " ;
if ( ! $position ) {
$rooms_count_sql = " SELECT COUNT(*) AS record_count FROM complex_rooms WHERE floor_id = { $floor_id } " ;
$result_count = $this -> db -> query ( $rooms_count_sql );
$row = $this -> db -> fetch_assoc ( $result_count );
$position = $row [ 'record_count' ] + 1 ;
}
$strArray [] = " position= $position " ;
$str = implode ( ', ' , $strArray );
$sql = " INSERT INTO complex_rooms SET { $str } " ;
$q = $this -> db -> query ( $sql );
$id = $this -> db -> insert_id ();
$attr_sql = " SELECT attribute_type, area FROM complex_rooms_attribute WHERE complex_room_id = { $room_id } " ;
$attr_q = $this -> db -> query ( $attr_sql );
while ( $attr = $this -> db -> fetch_assoc ( $attr_q )) {
$type = $attr [ 'attribute_type' ];
$area = $attr [ 'area' ];
$this -> db -> query ( "
INSERT INTO complex_rooms_attribute ( complex_room_id , attribute_type , area )
VALUES ( $id , '$type' , $area )
" );
}
$q = $this -> db -> query ( " SELECT complex_rooms.*,
cs . name as status_name ,
cs . status as status_type ,
cs . color as status_color
FROM complex_rooms
LEFT JOIN complex_status cs ON complex_rooms . complex_status_id = cs . id WHERE complex_rooms . id = $id
" );
$room = $this -> db -> fetch_assoc ( $q );
$reservations = $this -> get_room_reservations ( $room [ 'id' ]);
unset ( $reservations [ 'can_change_queue' ]);
$complex_status_info = [
'status_name' => $room [ 'status_name' ],
'status_type' => $room [ 'status_type' ],
'status_color' => $room [ 'status_color' ]
];
unset ( $room [ 'status_name' ]);
unset ( $room [ 'status_type' ]);
unset ( $room [ 'status_color' ]);
if ( $room [ 'status_type' ] != 'reservation' && is_array ( $reservations ) && count ( $reservations ))
{
$complex_status_info = [
'status_name' => $reservations [ 0 ][ 'status_name' ],
'status_type' => $reservations [ 0 ][ 'status_type' ],
'status_color' => $reservations [ 0 ][ 'status_color' ],
];
}
$room [ 'complex_status_info' ] = $complex_status_info ;
return $room ;
}
public function get_decoration_types ()
{
$this -> set_user ();
$result = array ();
$sql = " SELECT * FROM decoration_types where id <= 10 " ;
$q = $this -> db -> query ( $sql );
while ( $decoration = $this -> db -> fetch_assoc ( $q )) {
$result [] = $decoration ;
}
return $result ;
}
public function add_house_entrance ( $house_id , $data )
{
$this -> set_user ();
$strArray = [];
foreach ( $data as $key => $value ) {
if ( is_string ( $value )) {
$strArray [] = " $key =' $value ' " ;
} else {
$strArray [] = " $key = $value " ;
}
}
$str = implode ( ', ' , $strArray );
$sql = " INSERT INTO complex_entrances SET { $str } , complex_house_id= { $house_id } " ;
$q = $this -> db -> query ( $sql );
$id = $this -> db -> insert_id ();
$q = $this -> db -> query ( " SELECT * FROM complex_entrances WHERE id = $id " );
$entrance = $this -> db -> fetch_assoc ( $q );
// $entrance['floors'] = $this->get_entrance_floors($entrance);
$entrance [ 'floors' ] = [];
return $entrance ;
}
public function add_floor_plan_figure ( $floor_plan_id , $data )
{
$this -> set_user ();
$strArray = [];
foreach ( $data as $key => $value ) {
if ( in_array ( $key , [ 'points' ])) {
$value = json_encode ( $value );
}
if ( is_string ( $value )) {
$strArray [] = " $key =' $value ' " ;
} else {
$strArray [] = " $key = $value " ;
}
}
$str = implode ( ', ' , $strArray );
$sql = " INSERT INTO complex_floor_plan_figures SET { $str } , floor_plan_id= { $floor_plan_id } " ;
$q = $this -> db -> query ( $sql );
$id = $this -> db -> insert_id ();
$q = $this -> db -> query ( " SELECT * FROM complex_floor_plan_figures WHERE id = $id " );
$figure = $this -> db -> fetch_assoc ( $q );
$figure [ 'points' ] = json_decode ( $figure [ 'points' ]);
return $figure ;
}
public function update_house_entrance ( $entrance_id , $data )
{
$this -> set_user ();
$str = '' ;
foreach ( $data as $key => $value ) {
if ( is_string ( $value )) {
$str .= " $key =' $value ' " ;
} else {
$str .= " $key = $value " ;
}
}
$sql = " UPDATE complex_entrances SET $str WHERE id= { $entrance_id } " ;
$q = $this -> db -> query ( $sql );
return [ 'status' => $q ];
}
public function update_floor_plan_figure ( $figure_id , $data )
{
$this -> set_user ();
$strArray = [];
foreach ( $data as $key => $value ) {
// if ($key == 'room_plan_id') {
// $sql = "SELECT COUNT(room_plan_id) as count FROM complex_floor_plan_figures WHERE room_plan_id = {$value}";
// $res = $this->db->query($sql);
// $row = $this->db->fetch_assoc($res);
// if ($row['count']) {
// echo json_encode(['status' => false, 'count' => $row['count']], JSON_UNESCAPED_UNICODE);
// exit;
// }
// }
if ( is_string ( $value )) {
$strArray [] = " $key =' $value ' " ;
} else if ( is_null ( $value )) {
$strArray [] = " $key =NULL " ;
} else {
$strArray [] = " $key = $value " ;
}
}
$str = implode ( ', ' , $strArray );
$sql = " UPDATE complex_floor_plan_figures SET $str WHERE id= { $figure_id } " ;
$q = $this -> db -> query ( $sql );
return $data ;
}
public function create_floor ( $entrance_id , $data )
{
$this -> set_user ();
$strArray = [];
foreach ( $data as $key => $value ) {
if ( is_string ( $value )) {
$strArray [] = " $key =' $value ' " ;
} else {
$strArray [] = " $key = $value " ;
}
}
$str = implode ( ', ' , $strArray );
$q = $this -> db -> query ( " SELECT * FROM complex_floors WHERE { $str } and complex_entrance_id= { $entrance_id } " );
if ( $this -> db -> num_rows ( $q ) > 0 ) {
$floor = $this -> db -> fetch_assoc ( $q );
$floor [ 'rooms' ] = [];
return $floor ;
} else {
$sql = " INSERT INTO complex_floors SET { $str } , complex_entrance_id= { $entrance_id } " ;
$q = $this -> db -> query ( $sql );
$id = $this -> db -> insert_id ();
// var_dump($id);
$q = $this -> db -> query ( " SELECT * FROM complex_floors WHERE id = $id " );
$floor = $this -> db -> fetch_assoc ( $q );
$floor [ 'rooms' ] = [];
return $floor ;
}
}
public function copy_floor ( $floor_id , $position )
{
$this -> set_user ();
$sql = " SELECT * FROM complex_floors WHERE id = { $floor_id } " ;
$q = $this -> db -> query ( $sql );
$floor = $this -> db -> fetch_assoc ( $q );
$strArray = [];
foreach ( $floor as $key => $value ) {
if (
$key == 'id' ||
$key == 'position' ||
$key == 'created_at' ||
$key == 'updated_at' ||
empty ( $value )
) {
continue ;
}
if ( is_string ( $value )) {
$strArray [] = " $key =' $value ' " ;
} else {
$strArray [] = " $key = $value " ;
}
}
$strArray [] = " position= $position " ;
$str = implode ( ', ' , $strArray );
$sql = " INSERT INTO complex_floors SET { $str } " ;
$this -> db -> query ( $sql );
$id = $this -> db -> insert_id ();
$q = $this -> db -> query ( " SELECT * FROM complex_floors WHERE id = $id " );
$floor = $this -> db -> fetch_assoc ( $q );
$rooms_sql = " SELECT * FROM complex_rooms WHERE floor_id = { $floor_id } " ;
$rooms_q = $this -> db -> query ( $rooms_sql );
// $room = $this->db->fetch_assoc($q);
$floor [ 'rooms' ] = [];
// $rooms_count_sql = "SELECT COUNT(*) AS record_count FROM complex_rooms WHERE floor_id = {$floor_id}";
// $result_count = $this->db->query($rooms_count_sql);
// $row = $this->db->fetch_assoc($result_count);
// $rooms_count = $row['record_count'];
$copied_room_position = 1 ;
while ( $room = $this -> db -> fetch_assoc ( $rooms_q )) {
$copiedRoom = $this -> copy_room ( $room [ 'id' ], $floor [ 'id' ], $copied_room_position );
$copied_room_position = $copied_room_position + 1 ;
// $room['floor'] = $floor['position'];
// $room['entrance_name'] = $entrance['name'];
// $room['entrance_id'] = $entrance['id'];
// $room['house_name'] = $entrance['house_name'];
// $room['complex_name'] = $entrance['complex_name'];
$floor [ 'rooms' ][] = $copiedRoom ;
}
return $floor ;
}
public function copy_house ( $house_id , $complex_id )
{
$this -> set_user ();
$housesArr = $this -> get_houses ( $complex_id );
$targetHouse = null ;
foreach ( $housesArr as $house ) {
if ( $house [ 'id' ] == $house_id ) {
$targetHouse = $house ;
break ;
}
}
$house = $targetHouse ;
$user_id = $this -> user_id ;
// 1. Копируем дом
if ( ! $house ) {
return [ 'error' => 'Original house not found' ];
}
$house [ 'name' ] .= ' (копия)' ;
$house_id = $house [ 'id' ];
unset ( $house [ 'id' ]); // не копируем id
$images = $house [ 'images' ];
unset ( $house [ 'images' ]); // не копируем id
$floors = $house [ 'floors' ];
unset ( $house [ 'floors' ]); // не копируем id
$rooms = $house [ 'rooms' ];
unset ( $house [ 'rooms' ]); // не копируем id
$house [ 'created_at' ] = date ( 'Y-m-d H:i:s' );
$house [ 'update_at' ] = date ( 'Y-m-d H:i:s' );
unset ( $house [ 'total_rooms' ]);
unset ( $house [ 'name_complex' ]);
unset ( $house [ 'min_total_amount' ]);
$house [ 'parking' ] = $this -> db -> query ( " SELECT parking FROM complex_houses WHERE complex_id = { $house_id } " );
$columns_sql = implode ( ', ' , array_keys ( $house ));
$escaped_values = [];
foreach ( $house as $value ) {
if ( is_null ( $value ) || $value === '' ) {
$escaped_values [] = 'NULL' ;
} elseif ( is_numeric ( $value )) {
$escaped_values [] = $value ;
} else {
$escaped_values [] = " ' " . addslashes ( $value ) . " ' " ;
}
}
$values_sql = implode ( ', ' , $escaped_values );
$sql = "
INSERT INTO complex_houses ({ $columns_sql })
VALUES ({ $values_sql })
" ;
$this -> db -> query ( $sql );
$new_house_id = $this -> db -> insert_id ();
// 2. Копируем изображения
foreach ( $images as $image ) {
unset ( $image [ 'id' ]); // не копируем id
$image_url = $image [ 'url' ];
$name = $image [ 'name' ];
$this -> db -> query ( "
INSERT INTO complex_house_images ( house_id , url , name )
VALUES ({ $new_house_id }, '{$image_url}' , '{$name}' )
" );
}
// 3. Копируем подъезды
$entrances = $this -> db -> query ( " SELECT * FROM complex_entrances WHERE complex_house_id = { $house_id } " );
$entrance_name = 0 ;
$room_id_map = [];
while ( $entrance = $this -> db -> fetch_assoc ( $entrances )) {
$entrance_name = $entrance [ 'name' ];
$positionFloor = $entrance [ 'position' ];
$this -> db -> query ( "
INSERT INTO complex_entrances ( complex_house_id , name , position )
VALUES ({ $new_house_id }, '{$entrance_name}' , { $positionFloor })
" );
$old_entrance_id = $entrance [ 'id' ];
$new_entrance_id = $this -> db -> insert_id ();
// 3. Копируем этажи
foreach ( $floors as $floor ){
if ( $floor [ 'complex_entrance_id' ] !== $old_entrance_id ) {
continue ;
}
$position = $floor [ 'position' ]; // скопируем позицию
$old_floor_id = $floor [ 'id' ];
unset ( $floor [ 'id' ]);
$alignment = $floor [ 'alignment' ]; // скопируем позицию
$this -> db -> query ( "
INSERT INTO complex_floors ( complex_entrance_id , position , alignment )
VALUES ({ $new_entrance_id }, { $position }, '{$alignment}' )
" );
$new_floor_id = $this -> db -> insert_id ();
// 4. Копируем комнаты
foreach ( $rooms as $room ) {
if ( $room [ 'floor_id' ] !== $old_floor_id ) {
continue ;
}
$old_id = $room [ 'id' ];
unset ( $room [ 'id' ]);
unset ( $room [ 'min_total_amount' ]);
unset ( $room [ 'status' ]);
$room [ 'floor_id' ] = $new_floor_id ;
$room_column_sql = implode ( ', ' , array_keys ( $room ));
$room_values = [];
foreach ( $room as $value ) {
if ( is_null ( $value )) {
$room_values [] = 'NULL' ;
} elseif ( is_numeric ( $value )) {
$room_values [] = $value ;
} else {
$room_values [] = " ' " . addslashes ( $value ) . " ' " ;
}
}
$rooms__sql = implode ( ', ' , $room_values );
$sql = " INSERT INTO complex_rooms ( { $room_column_sql } )
VALUES ({ $rooms__sql }) " ;
$this -> db -> query ( $sql );
$new_id = $this -> db -> insert_id ();
// Сохраняем связь старый ID => новый ID
$room_id_map [ $old_id ] = $new_id ;
}
}
}
// 5. Копируем планировку
$houses_plans = $this -> db -> query ( " SELECT * FROM complex_house_plans WHERE house_id = { $house_id } " );
foreach ( $houses_plans as $plans ) {
$plans_id = $plans [ 'id' ];
unset ( $plans [ 'id' ]);
$columns_sql = implode ( ', ' , array_keys ( $plans ));
$plans [ 'house_id' ] = $new_house_id ;
$plans_values = [];
foreach ( $plans as $value ) {
if ( is_null ( $value )) {
$plans_values [] = 'NULL' ;
} elseif ( is_numeric ( $value )) {
$plans_values [] = $value ;
} else {
$plans_values [] = " ' " . addslashes ( $value ) . " ' " ;
}
}
$plans__sql = implode ( ', ' , $plans_values );
$sql = " INSERT INTO complex_house_plans ( { $columns_sql } )
VALUES ({ $plans__sql }) " ;
$this -> db -> query ( $sql );
$new_plan_id = $this -> db -> insert_id ();
// 6. Копируем изображения планировки
$houses_plans_images = $this -> db -> query ( " SELECT * FROM complex_house_plans_images WHERE plan_id = { $plans_id } " );
$houses_plans_image = $this -> db -> fetch_assoc ( $houses_plans_images );
if ( $houses_plans_image ) {
unset ( $houses_plans_image [ 'id' ]);
$houses_plans_image [ 'plan_id' ] = $new_plan_id ;
// var_dump($houses_plans_image);
$columns_sql = implode ( ', ' , array_keys ( $houses_plans_image ));
$plans_image_values = [];
foreach ( $houses_plans_image as $value ) {
if ( is_null ( $value )) {
$plans_image_values [] = 'NULL' ;
} elseif ( is_numeric ( $value )) {
$plans_image_values [] = $value ;
} else {
$plans_image_values [] = " ' " . addslashes ( $value ) . " ' " ;
}
}
$plans_image_sql = implode ( ', ' , $plans_image_values );
$sql = " INSERT INTO complex_house_plans_images ( { $columns_sql } )
VALUES ({ $plans_image_sql }) " ;
$this -> db -> query ( $sql );
}
// 7. Копируем планировку для каждого дома
$rooms_plans = $this -> db -> query ( " SELECT * FROM complex_rooms_plans WHERE plan_id = { $plans_id } " );
while ( $room_plan = $this -> db -> fetch_assoc ( $rooms_plans )) {
unset ( $room_plan [ 'id' ]);
$room_plan_id = $room_id_map [ $room_plan [ 'room_id' ]];
$plan_id_for_room = $new_plan_id ;
$sql = " INSERT INTO complex_rooms_plans (room_id, plan_id)
VALUES ({ $room_plan_id },{ $plan_id_for_room }) " ;
$this -> db -> query ( $sql );
}
}
return $housesArr ;
}
public function update_floor ( $floor_id , $data )
{
$this -> set_user ();
$result = array ();
$strArray = [];
foreach ( $data as $key => $value ) {
if ( is_string ( $value )) {
$strArray [] = " $key =' $value ' " ;
} else {
$strArray [] = " $key = $value " ;
}
}
$str = implode ( ', ' , $strArray );
$sql = " UPDATE complex_floors SET $str WHERE id= { $floor_id } " ;
$q = $this -> db -> query ( $sql );
return [ 'status' => $q ];
}
public function get_entrance_floors ( $entrance , $includes , $partner_id = 0 , $has_token = false )
{
$complex_status = new ComplexStatus ( null , true );
$this -> set_user ();
$result = array ();
$entrance_id = $entrance [ 'id' ];
$sql = " SELECT DISTINCT complex_floors.*, floor_plans.has_light_angle as has_light_angle, floor_plans.light_angle as light_angle FROM complex_floors
LEFT JOIN complex_floors_plans floor_plan_link ON floor_plan_link . floor_id = complex_floors . id
LEFT JOIN complex_house_floor_plans floor_plans ON floor_plans . id = floor_plan_link . floor_plan_id
WHERE complex_entrance_id = { $entrance_id } " ;
//echo $sql;
$q = $this -> db -> query ( $sql );
$roomIds = [];
$attributes = [];
while ( $floor = $this -> db -> fetch_assoc ( $q )) {
$floor [ 'rooms' ] = [];
if ( $includes && in_array ( 'rooms' , $includes )) {
// SELECT complex_rooms.*, c_house_p_i.url as plan_url FROM complex_rooms
// LEFT JOIN complex_rooms_plans c_room_p ON c_room_p.room_id = complex_rooms.id
// LEFT JOIN complex_house_plans_images c_house_p_i ON c_room_p.plan_id = c_house_p_i.plan_id AND c_house_p_i.position = 1
// WHERE complex_rooms.floor_id={$floor['id']}
// ORDER BY complex_rooms.position
// $rooms_sql = "SELECT complex_rooms.*, MAX(c_house_p_i.url) as plan_url FROM complex_rooms
// LEFT JOIN complex_rooms_plans c_room_p ON c_room_p.room_id = complex_rooms.id
// LEFT JOIN complex_house_plans_images c_house_p_i ON c_room_p.plan_id = c_house_p_i.plan_id AND c_house_p_i.position = 1
// WHERE complex_rooms.floor_id = {$floor['id']}
// GROUP BY complex_rooms.id
// ORDER BY complex_rooms.position;
// ";
if ( $has_token ) {
if ( $this -> user -> agencyId == 20382 ) {
$filter_by_status = " " ;
} else {
$filter_by_status = " AND cs.status IN ('available', 'reservation') " ;
}
} else {
$filter_by_status = " " ;
}
$rooms_sql = " SELECT complex_rooms.*,
MAX ( c_house_p_i . url ) as plan_url ,
MAX ( c_house_p . has_light_angle ) as has_light_angle ,
MAX ( c_house_p . light_angle ) as light_angle ,
MAX ( cs . name ) as status_name ,
MAX ( cs . status ) as status_type ,
MAX ( cs . color ) as status_color ,
MAX ( cra . add_to_domclick_feed ) as add_to_domclick_feed ,
MAX ( cra . add_to_avito_feed ) as add_to_avito_feed ,
MAX ( cra . add_to_cian_feed ) as add_to_cian_feed ,
MAX ( cra . add_to_yandex_feed ) as add_to_yandex_feed ,
MAX ( cra . add_to_domrf_feed ) as add_to_domrf_feed ,
MAX ( cra . add_to_site_feed ) as add_to_site_feed ,
MAX ( crn . note ) as note ,
CASE
WHEN MAX ( cs . status ) = 'reservation' THEN (
SELECT r . id
FROM requisitions r
WHERE r . complex_room_id = complex_rooms . id
ORDER BY r . created_at DESC
LIMIT 1
)
ELSE NULL
END AS requisition_id
FROM complex_rooms
LEFT JOIN complex_rooms_plans c_room_p ON c_room_p . room_id = complex_rooms . id
LEFT JOIN complex_room_advert cra ON cra . complex_room_id = complex_rooms . id
2026-07-15 09:58:57 +02:00
LEFT JOIN complex_house_plans_images c_house_p_i ON c_room_p . plan_id = c_house_p_i . plan_id
2026-05-22 20:21:54 +02:00
LEFT JOIN complex_house_plans c_house_p ON c_room_p . plan_id = c_house_p . id
LEFT JOIN complex_status cs ON complex_rooms . complex_status_id = cs . id AND cs . is_archive = 0
LEFT JOIN complex_room_notes crn ON crn . room_id = complex_rooms . id
WHERE complex_rooms . floor_id = { $floor [ 'id' ]}
{ $filter_by_status }
GROUP BY complex_rooms . id
ORDER BY complex_rooms . position ; " ;
$rooms_q = $this -> db -> query ( $rooms_sql );
// Modified installment plans query using only complex_house_installments
$house_id = $entrance [ 'house_id' ];
$installment_sql = " SELECT i.*,
chi . end_date as house_installment_end_date
FROM installments i
INNER JOIN complex_house_installments chi ON chi . installment_id = i . id
WHERE chi . house_id = { $house_id }
AND i . is_archive = 0
AND ( chi . end_date IS NULL OR chi . end_date >= CURDATE ()) " ;
$installment_q = $this -> db -> query ( $installment_sql );
$installment_plans = [];
while ( $plan = $this -> db -> fetch_assoc ( $installment_q )) {
$installment_plans [] = [
'id' => $plan [ 'id' ],
'name' => $plan [ 'name' ],
'description' => $plan [ 'description' ],
'type' => $plan [ 'type' ],
'initial_payment' => $plan [ 'initial_payment' ],
'payment_period' => json_decode ( $plan [ 'payment_period' ], true ),
'allow_change_on_close' => $plan [ 'allow_change_on_close' ],
'interest_rate' => $plan [ 'interest_rate' ],
'comment' => $plan [ 'comment' ],
'house_installment_end_date' => $plan [ 'house_installment_end_date' ]
];
}
while ( $room = $this -> db -> fetch_assoc ( $rooms_q )) {
$roomIds [] = $room [ 'id' ];
$room_id = $room [ 'id' ];
$attributes_sql = "
SELECT complex_room_id , id , attribute_type , area
FROM complex_rooms_attribute
WHERE complex_room_id = $room_id
" ;
$attributes_q = $this -> db -> query ( $attributes_sql );
$room [ 'attributes' ] = [];
while ( $attributes = $this -> db -> fetch_assoc ( $attributes_q )){
$room [ 'attributes' ][] = $attributes ;
}
if ( ! isset ( $room [ 'attributes' ]) || ! is_array ( $room [ 'attributes' ])) {
$room [ 'attributes' ] = [];
}
$hasRoom = false ;
$hasBathroom = false ;
$hasBalcony = false ;
$hasLoggia = false ;
foreach ( $room [ 'attributes' ] as $attr ) {
if ( $attr [ 'attribute_type' ] === 'room' ) {
$hasRoom = true ;
} elseif ( $attr [ 'attribute_type' ] === 'bathroom' ) {
$hasBathroom = true ;
} elseif ( $attr [ 'attribute_type' ] === 'balcony' ) {
$hasBalcony = true ;
} elseif ( $attr [ 'attribute_type' ] === 'loggia' ) {
$hasLoggia = true ;
}
}
if ( ! $hasRoom ) {
$room [ 'attributes' ][] = [ 'attribute_type' => 'room' , 'area' => null ];
}
if ( ! $hasBathroom ) {
$room [ 'attributes' ][] = [ 'attribute_type' => 'bathroom' , 'area' => null ];
}
if ( ! $hasBalcony && ! $hasLoggia ) {
$room [ 'attributes' ][] = [ 'attribute_type' => 'balcony' , 'area' => null ];
}
$room [ 'floor' ] = $floor [ 'position' ];
// $room['floor_has_light_angle'] = $floor['has_light_angle'];
// $room['floor_light_angle'] = $floor['light_angle'];
$room [ 'entrance_name' ] = $entrance [ 'name' ];
$room [ 'entrance_id' ] = $entrance [ 'id' ];
$room [ 'house_name' ] = $entrance [ 'house_name' ];
// $room['house_name'] = $entrance['house_name'];
$room [ 'house_security' ] = $entrance [ 'house_security' ];
$room [ 'house_parking' ] = $entrance [ 'house_parking' ];
$room [ 'house_fenced_area' ] = $entrance [ 'house_fenced_area' ];
$room [ 'house_sports_ground' ] = $entrance [ 'house_sports_ground' ];
$room [ 'house_play_ground' ] = $entrance [ 'house_play_ground' ];
$room [ 'house_school' ] = $entrance [ 'house_school' ];
$room [ 'house_kinder_garten' ] = $entrance [ 'house_kinder_garten' ];
$room [ 'house_id' ] = $entrance [ 'house_id' ];
$room [ 'complex_name' ] = $entrance [ 'complex_name' ];
// Add installment plans only if INSTALLMENT exists in room.payment_types
$paymentTypes = json_decode ( $room [ 'payment_types' ] ? $room [ 'payment_types' ] : '[]' );
if ( is_array ( $paymentTypes ) && in_array ( 'INSTALLMENT' , $paymentTypes )) {
$room [ 'installment_plans' ] = $installment_plans ;
} else {
$room [ 'installment_plans' ] = [];
}
if ( in_array (( string ) $room [ 'id' ], $_SESSION [ 'to_send_complexes' ])) {
$room [ 'inPdf' ] = true ;
}
$room [ 'requisitions' ] = $this -> get_room_requisitions ( $room [ 'id' ]);
$room [ 'reservations' ] = $this -> get_room_reservations ( $room [ 'id' ]);
$room [ 'can_change_queue' ] = $room [ 'reservations' ][ 'can_change_queue' ];
unset ( $room [ 'reservations' ][ 'can_change_queue' ]);
// Переопределяем статусы при наличии токена
if ( $has_token ) {
if ( $room [ 'status_type' ] == 'available' ) {
$room [ 'status_name' ] = 'Свободные' ;
} elseif ( $room [ 'status_type' ] == 'reservation' ) {
$room [ 'status_name' ] = 'Бронь' ;
}
}
if ( $partner_id > 0 ){
// if($room['status_type'] == 'sold'){
// $temp_status = $complex_status->getDefaultStatusStatus('not_for_sale');
// if(!empty($temp_status)){
// $room['status_type'] = $temp_status['status'];
// $room['status_name'] = $temp_status['name'];
// $room['status_color'] = $temp_status['color'];
// $room['status_id'] = $temp_status['id'];
// }
// } else {
$temp_status = $complex_status -> getDefaultStatusStatus ( $room [ 'status_type' ]);
if ( ! empty ( $temp_status )){
$room [ 'status_type' ] = $temp_status [ 'status' ];
$room [ 'status_name' ] = $temp_status [ 'name' ];
$room [ 'status_color' ] = $temp_status [ 'color' ];
$room [ 'status_id' ] = $temp_status [ 'id' ];
}
// }
}
$room [ 'complex_status_info' ] = [
'status_id' => $room [ 'status_id' ],
'status_name' => $room [ 'status_name' ],
'status_type' => $room [ 'status_type' ],
'status_color' => $room [ 'status_color' ]
];
if ( $room [ 'status_type' ] != 'reservation' && is_array ( $room [ 'reservations' ]) && count ( $room [ 'reservations' ]))
{
// if($partner_id > 0){
// $temp_status = $complex_status->getDefaultStatusStatus('reservation');
// if(!empty($temp_status)){
// $room['complex_status_info'] = [
// 'status_id' => $temp_status['id'],
// 'status_name' => $temp_status['name'],
// 'status_type' => $temp_status['status'],
// 'status_color' => $temp_status['color']
// ];
// }
// } else {
$room [ 'complex_status_info' ] = [
'status_id' => $room [ 'reservations' ][ 0 ][ 'status_id' ],
'status_name' => $room [ 'reservations' ][ 0 ][ 'status_name' ],
'status_type' => $room [ 'reservations' ][ 0 ][ 'status_type' ],
'status_color' => $room [ 'reservations' ][ 0 ][ 'status_color' ],
];
// }
}
$floor [ 'rooms' ][] = $room ;
}
}
$result [] = $floor ;
}
//ищем статусы размещения в рекламу для квартир
$objAdsErrors = [];
$objAdsSended = [];
//начитываем ошибки и ссылки размещения объектов в рекламе
$sql_ads = " SELECT `object_id`, `service_id`, `errors`, `url` FROM `ads_stats_complex` WHERE `object_id` IN ( " . implode ( " , " , $roomIds ) . " ) " ;
$rezAdsErrors = mysql_query ( $sql_ads );
if ( mysql_num_rows ( $rezAdsErrors ) > 0 ) {
while ( $objAdsInfo = mysql_fetch_assoc ( $rezAdsErrors )) {
$object_id = $objAdsInfo [ 'object_id' ];
$service_id = $objAdsInfo [ 'service_id' ];
if ( $objAdsInfo [ 'errors' ]) {
$objAdsErrors [ $object_id ][ $service_id ] = json_decode ( $objAdsInfo [ 'errors' ]);
} else {
$objAdsSended [ $object_id ][ $service_id ] = $objAdsInfo [ 'url' ];
}
}
}
//идем по всем помещениям и проставляем
foreach ( $result as $key => $floor ) {
foreach ( $floor [ 'rooms' ] as $keyRoom => $room ) {
//домклик
if ( $objAdsErrors [ $room [ 'id' ]][ 4 ]) {
$result [ $key ][ 'rooms' ][ $keyRoom ][ 'ads_domclick_error' ] = $objAdsErrors [ $room [ 'id' ]][ 4 ];
}
if ( $objAdsSended [ $room [ 'id' ]][ 4 ]) {
$result [ $key ][ 'rooms' ][ $keyRoom ][ 'ads_domclick_url' ] = $objAdsSended [ $room [ 'id' ]][ 4 ];
}
//авито
if ( $objAdsErrors [ $room [ 'id' ]][ 1 ]) {
$result [ $key ][ 'rooms' ][ $keyRoom ][ 'ads_avito_error' ] = $objAdsErrors [ $room [ 'id' ]][ 1 ];
}
if ( $objAdsSended [ $room [ 'id' ]][ 1 ]) {
$result [ $key ][ 'rooms' ][ $keyRoom ][ 'ads_avito_url' ] = $objAdsSended [ $room [ 'id' ]][ 1 ];
}
//циан
if ( $objAdsErrors [ $room [ 'id' ]][ 2 ]) {
$result [ $key ][ 'rooms' ][ $keyRoom ][ 'ads_cian_error' ] = $objAdsErrors [ $room [ 'id' ]][ 2 ];
}
if ( $objAdsSended [ $room [ 'id' ]][ 2 ]) {
$result [ $key ][ 'rooms' ][ $keyRoom ][ 'ads_cian_url' ] = $objAdsSended [ $room [ 'id' ]][ 2 ];
}
//яндекс
if ( $objAdsErrors [ $room [ 'id' ]][ 3 ]) {
$result [ $key ][ 'rooms' ][ $keyRoom ][ 'ads_yandex_error' ] = $objAdsErrors [ $room [ 'id' ]][ 3 ];
}
if ( $objAdsSended [ $room [ 'id' ]][ 3 ]) {
$result [ $key ][ 'rooms' ][ $keyRoom ][ 'ads_yandex_url' ] = $objAdsSended [ $room [ 'id' ]][ 3 ];
}
}
}
//идем по всем помещениям и проставляем
foreach ( $result as $key => $floor ) {
foreach ( $floor [ 'rooms' ] as $keyRoom => $room ) {
$result [ $key ][ 'rooms' ][ $keyRoom ][ 'advStat' ] = [];
$result [ $key ][ 'rooms' ][ $keyRoom ][ 'advStat' ][ 'avito' ] = [];
$result [ $key ][ 'rooms' ][ $keyRoom ][ 'advStat' ][ 'cian' ] = [];
$result [ $key ][ 'rooms' ][ $keyRoom ][ 'advStat' ][ 'yandex' ] = [];
$result [ $key ][ 'rooms' ][ $keyRoom ][ 'advStat' ][ 'domclick' ] = [];
$sqlSumStat = " SELECT asc2.*, (select sum(asc1.views) as sum_view_count from ads_stats_complex asc1 where asc1.object_id = asc2.object_id) as sum_view_count from ads_stats_complex asc2 where asc2.object_id = { $room [ 'id' ] } " ;
$rezSumStat = $this -> db -> query ( $sqlSumStat );
while ( $stat = $this -> db -> fetch_assoc ( $rezSumStat )) {
$result [ $key ][ 'rooms' ][ $keyRoom ][ 'advStat' ][ 'allViews' ] = $stat [ 'sum_view_count' ];
$service_id = $stat [ 'service_id' ];
if ( $service_id == 1 ) {
$result [ $key ][ 'rooms' ][ $keyRoom ][ 'advStat' ][ 'avito' ][ 'views' ] = $stat [ 'views' ];
$result [ $key ][ 'rooms' ][ $keyRoom ][ 'advStat' ][ 'avito' ][ 'contacts' ] = $stat [ 'contacts' ];
$result [ $key ][ 'rooms' ][ $keyRoom ][ 'advStat' ][ 'avito' ][ 'favorites' ] = $stat [ 'favorites' ];
$result [ $key ][ 'rooms' ][ $keyRoom ][ 'advStat' ][ 'avito' ][ 'calls' ] = $stat [ 'calls' ];
}
if ( $service_id == 2 ) {
$result [ $key ][ 'rooms' ][ $keyRoom ][ 'advStat' ][ 'cian' ][ 'views' ] = $stat [ 'views' ];
$result [ $key ][ 'rooms' ][ $keyRoom ][ 'advStat' ][ 'cian' ][ 'contacts' ] = $stat [ 'contacts' ];
$result [ $key ][ 'rooms' ][ $keyRoom ][ 'advStat' ][ 'cian' ][ 'favorites' ] = $stat [ 'favorites' ];
$result [ $key ][ 'rooms' ][ $keyRoom ][ 'advStat' ][ 'cian' ][ 'calls' ] = $stat [ 'calls' ];
}
if ( $service_id == 3 ) {
$result [ $key ][ 'rooms' ][ $keyRoom ][ 'advStat' ][ 'yandex' ][ 'views' ] = $stat [ 'views' ];
$result [ $key ][ 'rooms' ][ $keyRoom ][ 'advStat' ][ 'yandex' ][ 'contacts' ] = $stat [ 'contacts' ];
$result [ $key ][ 'rooms' ][ $keyRoom ][ 'advStat' ][ 'yandex' ][ 'favorites' ] = $stat [ 'favorites' ];
$result [ $key ][ 'rooms' ][ $keyRoom ][ 'advStat' ][ 'yandex' ][ 'calls' ] = $stat [ 'calls' ];
}
if ( $service_id == 4 ) {
$result [ $key ][ 'rooms' ][ $keyRoom ][ 'advStat' ][ 'domclick' ][ 'views' ] = $stat [ 'views' ];
$result [ $key ][ 'rooms' ][ $keyRoom ][ 'advStat' ][ 'domclick' ][ 'contacts' ] = $stat [ 'contacts' ];
$result [ $key ][ 'rooms' ][ $keyRoom ][ 'advStat' ][ 'domclick' ][ 'favorites' ] = $stat [ 'favorites' ];
$result [ $key ][ 'rooms' ][ $keyRoom ][ 'advStat' ][ 'domclick' ][ 'calls' ] = $stat [ 'calls' ];
}
}
}
}
return $result ;
}
public function get_room_figures ( $room_id )
{
$figures_sql = " SELECT
JSON_OBJECT (
'id' , c_f_p_f . id ,
'floor_plan_id' , c_f_p_f . floor_plan_id ,
'room_plan_id' , c_f_p_f . room_plan_id ,
'points' , c_f_p_f . points ,
'background' , c_f_p_f . background
) AS figures
FROM complex_rooms
JOIN complex_rooms_plans c_room_p ON c_room_p . room_id = complex_rooms . id
2026-07-15 09:58:57 +02:00
JOIN complex_house_plans_images c_house_p_i ON c_room_p . plan_id = c_house_p_i . plan_id
2026-05-22 20:21:54 +02:00
JOIN complex_house_plans c_house_p ON c_room_p . plan_id = c_house_p . id
JOIN complex_floor_plan_figures c_f_p_f ON c_f_p_f . room_plan_id = c_house_p . id
WHERE complex_rooms . id = { $room_id };
" ;
$figures_q = $this -> db -> query ( $figures_sql );
return json_decode ( $this -> db -> fetch_assoc ( $figures_q )[ 'figures' ]);
}
//Установка страниц
public function set_page_obj ( $page_obj )
{
$this -> page_obj = $page_obj ;
}
public function set_page ( $page )
{
$this -> page = $page ;
}
//Установка id юзера
public function set_user_id ( $user_id )
{
if ( $user_id > 0 ) {
$this -> user_id = $user_id ;
}
}
//Установка юзера
public function set_user ()
{
if ( empty ( $this -> user )) {
$user = new User ;
$user_id = 0 ;
if ( $this -> user_id > 0 ) {
$user_id = $this -> user_id ;
} else {
$user_id = $_SESSION [ 'id' ];
}
$user -> get ( $user_id );
$this -> user = $user ;
}
}
//Установка юзеров агенства
public function set_users_ids ()
{
if ( empty ( $this -> userIds )) {
$userIds = array ();
$this -> set_user ();
$agency_id = $this -> user -> agencyId ;
$userIds [] = $agency_id ;
$sql_users = " SELECT id FROM users WHERE id in (select id from users where id= { $agency_id } or id_manager= { $agency_id } or id_manager in
( select id from users where id_manager = { $agency_id } or id_manager in
( select id from users where id_manager = { $agency_id }))) " ;
$q_users = $this -> db -> query ( $sql_users );
while ( $r_users = $this -> db -> fetch_assoc ( $q_users )) {
$userIds [] = ( int ) $r_users [ 'id' ];
}
$this -> userIds = array_unique ( $userIds );
}
}
private function set_types_complex ()
{
$this -> types_comples = array (
array ( 'code' => 'complex' , 'name' => 'Жилой комплекс в новостройке' ),
array ( 'code' => 'comerc' , 'name' => 'Коммерция' ),
array ( 'code' => 'cottage_village' , 'name' => 'Коттеджный поселок' )
);
}
public function get_types_complex ()
{
return $this -> types_comples ;
}
/**
*
*/
private function set_sphinx ()
{
$pdo = new MysqlPdo ( hstsph , null , null , null , true , '9306' );
$sql = " SET NAMES 'utf8mb4' " ;
$pdo -> query ( $sql );
$this -> sphinx = $pdo ;
}
private function set_sphinx2 ()
{
$pdo = new MysqlPdo ( hstsph2 , null , null , null , true , '9306' );
$sql = " SET NAMES 'utf8mb4' " ;
$pdo -> query ( $sql );
$this -> sphinx2 = $pdo ;
}
/**
*
*/
private function set_payment_types ()
{
$this -> paymentTypes = array (
array ( 'code' => 1 , 'name' => 'Субсидия' ),
array ( 'code' => 2 , 'name' => 'Ипотека' ),
array ( 'code' => 3 , 'name' => 'Военная ипотека' ),
);
}
/**
*
*/
public function get_payment_types ()
{
$this -> set_payment_types ();
return $this -> paymentTypes ;
}
/**
*
*/
private function set_housing_class ()
{
$this -> housingClass = array (
array ( 'code' => 1 , 'name' => 'Эконом' ),
array ( 'code' => 2 , 'name' => 'Комфорт' ),
array ( 'code' => 3 , 'name' => 'Комфорт+' ),
array ( 'code' => 4 , 'name' => 'Бизнес' ),
array ( 'code' => 5 , 'name' => 'Элитный' ),
);
}
/**
* Получение отделки
*/
public function get_decarations ()
{
$rezult = array ( 'list' => array (), 'options' => array ());
$sql = " SELECT * FROM avito_decoration_types order by id " ;
$rez = $this -> db -> query ( $sql );
while ( $newFlatDecorationType = $this -> db -> fetch_assoc ( $rez )) {
$rezult [ 'list' ][ $newFlatDecorationType [ 'id' ]] = $newFlatDecorationType [ 'name' ];
$rezult [ 'options' ][] = array ( 'code' => $newFlatDecorationType [ 'id' ], 'name' => $newFlatDecorationType [ 'name' ]);
}
$this -> listDecorations = $rezult ;
return $this -> listDecorations ;
}
public function get_housing_class ()
{
$this -> set_housing_class ();
return $this -> housingClass ;
}
public function get_decorations ()
{
$sql = " SELECT * FROM decoration_types where id <= 10 ORDER BY name " ;
$rez = $this -> db -> query ( $sql );
$decorationTypes = array ();
if ( $this -> db -> num_rows ( $rez ) > 0 ) {
while ( $dbObject = $this -> db -> fetch_assoc ( $rez )) {
$decorationTypes [] = array ( 'code' => $dbObject [ 'id' ], 'name' => $dbObject [ 'name' ]);
}
}
return $decorationTypes ;
}
/**
* Страны
* @ return array
*
*/
public function get_country ()
{
$result = array ();
$country = array ();
$country_list = array ();
$countryListQuery = $this -> db -> query ( " select * from country_list where id=171 union select * from country_list where id <> 171 " );
while ( $countryList = $this -> db -> fetch_assoc ( $countryListQuery )) {
$country [] = array ( 'code' => $countryList [ 'id' ], 'name' => $countryList [ 'name' ]);
$country_list [ $countryList [ 'id' ]] = $countryList ;
}
$result [ 'country' ] = $country ;
$result [ 'country_list' ] = $country_list ;
return $result ;
}
/**
* Регионы
* @ return array
*/
public function get_rf_regions ()
{
$result = array ();
$regions = array ();
$regions_list = array ();
$region_id_user = 0 ;
$this -> set_user ();
$region_id_user = $this -> user -> region_rf_id ;
$regions_rf = $this -> db -> query ( " select * from rf_regions where parent = 0 " );
while ( $region_rf = $this -> db -> fetch_assoc ( $regions_rf )) {
$regions [] = array (
'code' => $region_rf [ 'id' ],
'name' => $region_rf [ 'name' ],
'rayons' => $this -> get_rf_region_rayons ( $region_rf [ 'id' ])
);
$regions_list [ $region_rf [ 'id' ]] = array ( 'kladr' => $region_rf [ 'kladr' ], 'label' => mb_strtolower ( $region_rf [ 'name' ]));
}
$result [ 'regions' ] = $regions ;
$result [ 'region_id_user' ] = $region_id_user ;
$result [ 'regions_list' ] = $regions_list ;
return $result ;
}
public function get_rf_region_rayons ( $rf_region_id )
{
$result = [];
$sql = $this -> db -> query ( " SELECT id, name FROM regions WHERE rf_region_id = { $rf_region_id } " );
while ( $row = $this -> db -> fetch_assoc ( $sql )) {
$result [] = $row ;
}
return $result ;
}
/**
* Метро
* @ param int $region_id
* @ return array
*/
public function get_metro ( $region_id )
{
$result = array ();
$metroRegion = $region_id ;
if ( $region_id == 19 ) {
$metroRegion = 1432 ;
}
if ( $region_id == 1 ) {
$metroRegion = 80 ;
}
if ( $region_id == 2 ) {
$metroRegion = 81 ;
}
if ( $region_id == 37 ) {
$metroRegion = 1468 ;
}
if ( $region_id == 55 ) {
$metroRegion = 1500 ;
}
if ( $region_id == 57 ) {
$metroRegion = 1504 ;
}
if ( $region_id == 66 ) {
$metroRegion = 1520 ;
}
if ( $region_id == 69 ) {
$metroRegion = 1526 ;
}
$sql = empty ( $region_id ) ? " SELECT * from metro " : " SELECT * from metro where region_rf_id = $metroRegion " ;
$metros_query = $this -> db -> query ( $sql );
while ( $metro = $this -> db -> fetch_assoc ( $metros_query )) {
$result [] = array ( 'code' => $metro [ 'id' ], 'name' => $metro [ 'metro' ]);
}
return $result ;
}
public function getUniquePeriods ()
{
$result = [];
$sql = " SELECT DISTINCT deadline FROM buildings GROUP BY deadline LIMIT 1000 " ;
$rez = $this -> db -> query ( $sql );
$date = Date :: getLastPeriodDate ( time ());
$currentTs = strtotime ( $date );
if ( $this -> db -> num_rows ( $rez ) > 0 ) {
while ( $dbObject = $this -> db -> fetch_assoc ( $rez )) {
$date = Date :: getLastPeriodDate ( strtotime ( $dbObject [ 'deadline' ]));
$ts = strtotime ( $date );
$name = Date :: getFormatedEndingPeriod ( $date );
if ( $currentTs < $ts ) {
$result [ $ts ] = $name ;
}
}
}
$result [ $currentTs ] = Date :: DEADLINE_DONE ;
ksort ( $result );
$res = array ();
foreach ( $result as $key => $period ) {
$res [] = array ( 'code' => $key , 'name' => $period );
}
return $res ;
}
/**
* Список застройщиков
* @ return array
*/
private function building_list ()
{
$building_list = array ();
$building_query = $this -> db -> query ( " SELECT * FROM buildings " );
while ( $building = $this -> db -> fetch_assoc ( $building_query )) {
$building_list [ $building [ 'block_id' ]][] = $building ;
}
return $building_list ;
}
/**
* ЖК новостройки
* @ return array
*/
public function get_blocks ()
{
$result = array ();
$building_list = $this -> building_list ();
$sql = " SELECT * FROM `blocks` order by name " ;
$block_query = $this -> db -> query ( $sql );
while ( $block = $this -> db -> fetch_assoc ( $block_query )) {
$result [ 'block_list' ][] = array ( 'code' => $block [ 'id' ], 'name' => $block [ 'name' ]);
if ( isset ( $building_list [ $block [ 'id' ]]) && ! empty ( $building_list [ $block [ 'id' ]])) {
foreach ( $building_list [ $block [ 'id' ]] as $building ) {
if ( ! isset ( $block [ 'lines' ][( int ) $building [ 'line' ]])) {
$block [ 'lines' ][( int ) $building [ 'line' ]] = array (
'name' => ( int ) $building [ 'line' ], 'isDiv' => true ,
'isEdit' => false , 'corpuses' => array (), 'isInput' => false
);
}
$block [ 'lines' ][( int ) $building [ 'line' ]][ 'corpuses' ][] = array (
'corpus' => $building [ 'corp' ],
'period' => Date :: getFormatedEndingPeriod ( $building [ 'deadline' ]),
'deadline' => date ( 'd.m.Y' , strtotime ( $building [ 'deadline' ])),
'isDiv' => true ,
'isEdit' => false ,
'date' => '' ,
);
}
} else {
$block [ 'lines' ] = array ();
}
$result [ 'blocks' ][ $block [ 'id' ]] = $block ;
}
return $result ;
}
/**
* Фото комплекса
* @ param int block_id
* @ return array $photos
*/
public function getPhotos ( $block_id )
{
$photos = array ();
$sql = " SELECT image FROM blocks WHERE id= { $block_id } " ;
$rez = $this -> db -> query ( $sql );
$appendedFiles = array ();
if ( $this -> db -> num_rows ( $rez ) > 0 ) {
while ( $dbObject = $this -> db -> fetch_assoc ( $rez )) {
$ph_url = $dbObject [ 'image' ];
$name = $dbObject [ 'image' ];
$pathInfo = pathinfo ( $name );
$appendedFiles [] = array (
" name " => $ph_url ,
" file " => $ph_url ,
" type " => " image/ " . $pathInfo [ 'extension' ],
" data " => array (
" url " => $ph_url ,
" thumbnail " => $ph_url
)
);
}
}
$sql = " SELECT image FROM block_images WHERE model_id=' { $block_id } ' AND type != 10 " ;
$rez = $this -> db -> query ( $sql );
if ( $this -> db -> num_rows ( $rez ) > 0 ) {
while ( $dbObject = $this -> db -> fetch_assoc ( $rez )) {
$ph_url = $dbObject [ 'image' ];
$name = $dbObject [ 'image' ];
$pathInfo = pathinfo ( $name );
$appendedFiles [] = array (
" name " => $ph_url ,
" file " => $ph_url ,
" type " => " image/ " . $pathInfo [ 'extension' ],
" data " => array (
" url " => $ph_url ,
" thumbnail " => $ph_url
)
);
}
}
return $appendedFiles ;
}
/**
* Преобразование корпуса
* @ param string $deadline
* @ param string $corpus
* @ return array $corpusNew
*/
public function corpus_convert ( $corpus , $deadline , $corpus_id , $corpus_floors , $corpus_floors_ready , $corpus_fz_214 , $corpus_status )
{
$corpusNew = array ();
$newDeadline = date ( 'Y-m-d' , strtotime ( $deadline ));
$period = Date :: getFormatedEndingPeriod ( $newDeadline );
$corpusNew = array (
'corpus' => $corpus ,
'period' => $period ,
'deadline' => date ( 'd.m.Y' , strtotime ( $newDeadline )),
'isDiv' => true ,
'isEdit' => false ,
'date' => '' ,
'corpus_id' => $corpus_id ,
'corpus_floors' => $corpus_floors ,
'corpus_floors_ready' => $corpus_floors_ready ,
'corpus_fz_214' => $corpus_fz_214 ,
'corpus_status' => $corpus_status
);
return $corpusNew ;
}
/**
* Список застройщиков
* @ return array
*/
public function get_builder_list ( $agency_id = null )
{
$builder_list = array ();
$builder_query = $this -> db -> query ( " SELECT id, name, logo, phone, link
FROM (
SELECT builders . id , builders . name , builders . logo , complex_builders . phone , complex_builders . link
FROM builders
LEFT JOIN complex_builders ON complex_builders . builder_id = builders . id
UNION ALL
SELECT id , name , logo , phone , link
FROM complex_builders
WHERE name IS NOT NULL AND name != ''
) AS combined_results
ORDER BY name " );
$complex_builder_ids = array ();
if ( $agency_id > 0 ) {
$sql = " SELECT id , builder_id FROM complex_list WHERE agency_id = { $agency_id } AND deleted = 0 AND arhive = 0 " ;
$q = $this -> db -> query ( $sql );
while ( $r = $this -> db -> fetch_assoc ( $q )) {
if (( int ) $r [ 'builder_id' ] > 0 ) {
$complex_builder_ids [] = ( int ) $r [ 'builder_id' ];
}
}
}
while ( $builders = $this -> db -> fetch_assoc ( $builder_query )) {
if ( $agency_id > 0 ) {
if ( in_array ( $builders [ 'id' ], $complex_builder_ids )) {
$builder_list [ 'list' ][ $builders [ 'id' ]] = $builders ;
$builder_list [ 'options' ][] = array ( 'code' => $builders [ 'id' ], 'name' => $builders [ 'name' ]);
}
} else {
$builder_list [ 'list' ][ $builders [ 'id' ]] = $builders ;
$builder_list [ 'options' ][] = array ( 'code' => $builders [ 'id' ], 'name' => $builders [ 'name' ]);
}
}
return $builder_list ;
}
/**
* Добавить застройщика
* @ param string $name
* @ return array
*/
public function addBuilder ( $name , $phone , $link )
{
$result = array ();
$this_name = trim ( $name );
$sql_b = " SELECT id FROM builders WHERE name = ' { $this_name } ' " ;
$q_b = $this -> db -> query ( $sql_b );
if ( $this -> db -> num_rows ( $q_b ) > 0 ) {
$res = $this -> db -> fetch_assoc ( $q_b );
$id = ( int ) $res [ 'id' ];
$sql_info = " SELECT * FROM complex_builders WHERE builder_id = { $id } " ;
$q_info = $this -> db -> query ( $sql_info );
if ( $this -> db -> num_rows ( $q_info ) > 0 ) {
$sql_up = " UPDATE complex_builders SET phone=' { $phone } ', link=' { $link } ' WHERE builder_id = { $id } " ;
} else {
$sql_up = " INSERT INTO complex_builders SET phone=' { $phone } ', link=' { $link } ', builder_id = { $id } " ;
}
$this -> db -> query ( $sql_up );
$result [ 'result' ] = 'old' ;
$result [ 'builder_id' ] = ( int ) $id ;
} else {
$sql_in = " INSERT INTO complex_builders SET name = ' { $this_name } ', phone=' { $phone } ', link=' { $link } ' " ;
$this -> db -> query ( $sql_in , true );
$id = $this -> db -> insert_id ();
$result [ 'result' ] = 'new' ;
$result [ 'builder_id' ] = ( int ) $id ;
}
return $result ;
}
/**
*
*/
public function get_complexes ()
{
$this -> set_user ();
$result = array ();
$sql = " SELECT id, name FROM complex_list WHERE agency_id= { $this -> user -> agencyId } AND deleted=0 AND arhive=0 " ;
//echo $sql;
$q = $this -> db -> query ( $sql );
while ( $complex = $this -> db -> fetch_assoc ( $q )) {
$result [] = array ( 'code' => $complex [ 'id' ], 'name' => $complex [ 'name' ]);
}
return $result ;
}
/**
*
*/
public function get_types_room ()
{
$result = array ();
$sql = " SELECT * FROM room_types ORDER BY name " ;
$rez = $this -> db -> query ( $sql );
while ( $type_room = $this -> db -> fetch_assoc ( $rez )) {
$result [] = array ( 'code' => $type_room [ 'id' ], 'name' => $type_room [ 'name' ]);
}
return $result ;
}
/**
* Установка комплекса
* @ param array $complex
* @ return void ()
*/
public function set_complex ( $complex )
{
$this -> complex = $complex ;
}
/**
* Тип дома
*/
public function get_house_types ()
{
$result = array ();
$sql = " SELECT * FROM house_material ORDER BY name " ;
$rez = $this -> db -> query ( $sql );
while ( $house_material = $this -> db -> fetch_assoc ( $rez )) {
$result [] = array ( 'code' => $house_material [ 'id' ], 'name' => $house_material [ 'name' ]);
}
return $result ;
}
/**
* Материал дома
*/
public function get_house_material ()
{
$result = array ();
$sql = " SELECT * FROM house_material ORDER BY name " ;
$rez = $this -> db -> query ( $sql );
while ( $house_material = $this -> db -> fetch_assoc ( $rez )) {
$result [] = array ( 'code' => $house_material [ 'id' ], 'name' => $house_material [ 'name' ]);
}
return $result ;
}
/**
* Сохранение фото
* @ param array $photos
* @ return array $photo_links
*/
private function save_photo ( $photos )
{
$this -> set_user ();
$Selectel = SelectelApi :: getTokenAndUrl ();
$token = $Selectel [ 0 ];
$storageUrl = $Selectel [ 1 ];
if ( ! is_dir ( $_SERVER [ 'DOCUMENT_ROOT' ] . " /photos " )) {
mkdir ( $_SERVER [ 'DOCUMENT_ROOT' ] . " /photos " );
}
if ( ! is_dir ( $_SERVER [ 'DOCUMENT_ROOT' ] . " /photos/complexes " )) {
mkdir ( $_SERVER [ 'DOCUMENT_ROOT' ] . " /photos/complexes " );
}
foreach ( $photos as $filePos ) {
if ( strpos ( $filePos [ 'file' ], " https:// " ) !== false ) {
$newPhotos [ $filePos [ 'index' ]] = $filePos [ 'file' ];
} else {
if ( strpos ( $filePos [ 'file' ], " 0:/ " ) !== false ) {
$originalName = str_replace ( " 0:/ " , " " , $filePos [ 'file' ]);
$strArray = explode ( " . " , $originalName );
$ext = end ( $strArray );
if ( $ext == " pjpeg " ) {
$ext = " jpeg " ;
}
$ext = mb_strtolower ( $ext );
$name = md5 ( $originalName . time ()) . " . " . $ext ;
$one = mb_substr ( $name , 0 , 1 );
if ( ! is_dir ( $_SERVER [ 'DOCUMENT_ROOT' ] . " /photos/complexes/ $one " )) {
mkdir ( $_SERVER [ 'DOCUMENT_ROOT' ] . " /photos/complexes/ $one " );
}
$two = mb_substr ( $name , 1 , 1 );
if ( ! is_dir ( $_SERVER [ 'DOCUMENT_ROOT' ] . " /photos/complexes/ $one / $two " )) {
mkdir ( $_SERVER [ 'DOCUMENT_ROOT' ] . " /photos/complexes/ $one / $two " );
}
$three = mb_substr ( $name , 3 , 1 );
if ( ! is_dir ( $_SERVER [ 'DOCUMENT_ROOT' ] . " /photos/complexes/ $one / $two / $three " )) {
mkdir ( $_SERVER [ 'DOCUMENT_ROOT' ] . " /photos/complexes/ $one / $two / $three " );
}
$new_path = " $one / $two / $three / $name " ;
$photo = " /photos/complexes/ " . $new_path ;
$oldPath = $_SERVER [ 'DOCUMENT_ROOT' ] . " /photos/complexes/complex_temp/ " . $_SESSION [ 'id' ] . " / " . $originalName ;
try {
copy ( $oldPath , $_SERVER [ 'DOCUMENT_ROOT' ] . $photo );
$oldPathList [] = $oldPath ;
$index = $filePos [ 'index' ];
if ( isset ( $filePos [ 'editor' ])) {
$editor = $filePos [ 'editor' ];
} else {
$editor = [];
}
resize ( $_SERVER [ 'DOCUMENT_ROOT' ] . $photo , null , null , null , ( isset ( $editor [ 'crop' ]) ? $editor [ 'crop' ] : null ), 100 , ( isset ( $editor [ 'rotation' ]) ? $editor [ 'rotation' ] : null ));
$image = new Imagick ();
$image -> readImage ( $_SERVER [ 'DOCUMENT_ROOT' ] . $photo );
$resolution = 1024 ;
if ( $this -> user -> agencyId == 10919 || $this -> user -> agencyId == 8826 || $this -> user -> agencyId == 12482 || $this -> user -> agencyId == 11916 ) {
$resolution = 1920 ;
}
if ( $image -> getImageWidth () > $resolution ) {
$image -> scaleImage ( $resolution , $resolution , true );
}
$image -> writeImage ();
//загрузка в Selectel
$fp = $_SERVER [ 'DOCUMENT_ROOT' ] . " /photos/complexes/ " . $new_path ;
$SelectelApi = new SelectelApi ();
$r = $SelectelApi -> uploadFile ( $storageUrl , $token , $fp , '/complexes/' . $new_path , 'image/' . $ext );
//если выложили в Selectel
if ( $r ) {
//заменяем путь на новый
$new_path = " https://data.joywork.ru/complexes/ " . $new_path ;
//удаляем файл с локального сервера
unlink ( $fp );
}
if ( $index >= 0 ) {
$newPhotos [ $index ] = $new_path ;
} else {
$newPhotos [] = $new_path ;
}
} catch ( Exception $e ) {
$err = " Проблема загрузки фотографии " . $originalName . " , возможно, фото повреждено или е г о формат не соответствует расширению " ;
}
}
}
}
if ( isset ( $err )) {
$result [ 'error' ] = $err ;
}
if ( isset ( $newPhotos )) {
$result = $newPhotos ;
}
return $result ;
}
/**
* Добавить фото для комплекса
* @ param array $photos
* @ param array $complex
*
*/
public function addPhotoToComplex ( $photos , $complex_id )
{
$newPhotos = $this -> uploadPhotosToEntity ( $photos , 'complexes' , $complex_id );
if ( isset ( $newPhotos )) {
// $filesToDelete = array();
// $r = $this->db->query("SELECT `image` FROM complex_images WHERE complex_id = {$complex_id}");
// while ($row = $this->db->fetch_assoc($r)) {
// $filesToDelete[] = $row['image'];
// }
// $this->deleteFiles($filesToDelete);
// $this->db->query("DELETE FROM complex_images WHERE complex_id = {$complex_id}", true);
foreach ( $newPhotos as & $image ) {
$sql_in_image = " INSERT INTO complex_images SET complex_id = { $complex_id } , image = ' { $image [ 'url' ] } ' " ;
$this -> db -> query ( $sql_in_image , true );
$image [ 'id' ] = ( int ) $this -> db -> insert_id ();
$image [ 'complex_id' ] = ( int ) $complex_id ;
}
return $newPhotos ;
}
return '' ;
}
public function updateComplexPhoto ( $photo , $photo_id )
{
$r = $this -> db -> query ( " SELECT * FROM complex_images WHERE id = { $photo_id } " );
$row = $this -> db -> fetch_assoc ( $r );
$fileToDelete = $row [ 'image' ];
$this -> deleteFiles ([ $fileToDelete ]);
$newPhotos = $this -> uploadPhotosToEntity ([ $photo ], 'complexes' , $row [ 'complex_id' ]);
if ( count ( $newPhotos )) {
$sqlUpdate = " UPDATE complex_images SET image = ' { $newPhotos [ 0 ][ 'url' ] } ' WHERE id = { $photo_id } " ;
$this -> db -> query ( $sqlUpdate );
$row [ 'image' ] = $newPhotos [ 0 ][ 'url' ];
}
return $row ;
}
public function addPhotosToHouse ( $photos , $house_id )
{
$newPhotos = $this -> uploadPhotosToEntity ( $photos , 'houses' , $house_id );
if ( isset ( $newPhotos )) {
foreach ( $newPhotos as & $image ) {
$sql_in_image = " INSERT INTO complex_house_images SET house_id = { $house_id } , `url` = ' { $image [ 'url' ] } ', `name` = ' { $image [ 'name' ] } ' " ;
$this -> db -> query ( $sql_in_image , true );
$image [ 'id' ] = ( int ) $this -> db -> insert_id ();
$image [ 'house_id' ] = ( int ) $house_id ;
}
return $newPhotos ;
}
return '' ;
}
public function saveHouseDecoration ( $house_id , $desc = null , $id = null , $decorationId = null , $photo = null , $photo2 = null , $photo3 = null , $photo4 = null , $photo5 = null )
{
if ( empty ( $house_id )) {
return [ 'status' => false ];
}
$SQLSet = [ " `house_id` = { $house_id } " ];
if ( $photo === null ) {
if ( $id ) {
$selectSql = $this -> db -> query ( " SELECT photo FROM complex_house_decoration WHERE id = $id " );
$foundDecoration = $this -> db -> fetch_assoc ( $selectSql );
if ( $foundDecoration ) {
$this -> deleteFiles ([ $foundDecoration [ 'photo' ]]);
}
}
$SQLSet [] = " `photo` = NULL " ;
} else if ( $photo ) {
if ( is_string ( $photo ) && strpos ( $photo , " https:// " ) !== false ) {
$SQLSet [] = " `photo` = ' $photo ' " ;
} else {
$newPhotos = $this -> uploadPhotosToEntity ([ $photo ], 'decoration' , $house_id );
if ( isset ( $newPhotos [ 0 ])) {
$img = $newPhotos [ 0 ];
$SQLSet [] = " `photo` = ' { $img [ 'url' ] } ' " ;
}
}
}
if ( $photo2 === null ) {
if ( $id ) {
$selectSql = $this -> db -> query ( " SELECT photo FROM complex_house_decoration WHERE id = $id " );
$foundDecoration = $this -> db -> fetch_assoc ( $selectSql );
if ( $foundDecoration ) {
$this -> deleteFiles ([ $foundDecoration [ 'photo2' ]]);
}
}
$SQLSet [] = " `photo2` = NULL " ;
} else if ( $photo2 ) {
if ( is_string ( $photo2 ) && strpos ( $photo2 , " https:// " ) !== false ) {
$SQLSet [] = " `photo2` = ' $photo2 ' " ;
} else {
$newPhotos = $this -> uploadPhotosToEntity ([ $photo2 ], 'decoration' , $house_id );
if ( isset ( $newPhotos [ 0 ])) {
$img = $newPhotos [ 0 ];
$SQLSet [] = " `photo2` = ' { $img [ 'url' ] } ' " ;
}
}
}
if ( $photo3 === null ) {
if ( $id ) {
$selectSql = $this -> db -> query ( " SELECT photo FROM complex_house_decoration WHERE id = $id " );
$foundDecoration = $this -> db -> fetch_assoc ( $selectSql );
if ( $foundDecoration ) {
$this -> deleteFiles ([ $foundDecoration [ 'photo3' ]]);
}
}
$SQLSet [] = " `photo3` = NULL " ;
} else if ( $photo3 ) {
if ( is_string ( $photo3 ) && strpos ( $photo3 , " https:// " ) !== false ) {
$SQLSet [] = " `photo3` = ' $photo3 ' " ;
} else {
$newPhotos = $this -> uploadPhotosToEntity ([ $photo3 ], 'decoration' , $house_id );
if ( isset ( $newPhotos [ 0 ])) {
$img = $newPhotos [ 0 ];
$SQLSet [] = " `photo3` = ' { $img [ 'url' ] } ' " ;
}
}
}
if ( $photo4 === null ) {
if ( $id ) {
$selectSql = $this -> db -> query ( " SELECT photo FROM complex_house_decoration WHERE id = $id " );
$foundDecoration = $this -> db -> fetch_assoc ( $selectSql );
if ( $foundDecoration ) {
$this -> deleteFiles ([ $foundDecoration [ 'photo4' ]]);
}
}
$SQLSet [] = " `photo4` = NULL " ;
} else if ( $photo4 ) {
if ( is_string ( $photo4 ) && strpos ( $photo4 , " https:// " ) !== false ) {
$SQLSet [] = " `photo4` = ' $photo4 ' " ;
} else {
$newPhotos = $this -> uploadPhotosToEntity ([ $photo4 ], 'decoration' , $house_id );
if ( isset ( $newPhotos [ 0 ])) {
$img = $newPhotos [ 0 ];
$SQLSet [] = " `photo4` = ' { $img [ 'url' ] } ' " ;
}
}
}
if ( $photo5 === null ) {
if ( $id ) {
$selectSql = $this -> db -> query ( " SELECT photo FROM complex_house_decoration WHERE id = $id " );
$foundDecoration = $this -> db -> fetch_assoc ( $selectSql );
if ( $foundDecoration ) {
$this -> deleteFiles ([ $foundDecoration [ 'photo5' ]]);
}
}
$SQLSet [] = " `photo5` = NULL " ;
} else if ( $photo5 ) {
if ( is_string ( $photo5 ) && strpos ( $photo5 , " https:// " ) !== false ) {
$SQLSet [] = " `photo5` = ' $photo5 ' " ;
} else {
$newPhotos = $this -> uploadPhotosToEntity ([ $photo5 ], 'decoration' , $house_id );
if ( isset ( $newPhotos [ 0 ])) {
$img = $newPhotos [ 0 ];
$SQLSet [] = " `photo5` = ' { $img [ 'url' ] } ' " ;
}
}
}
if ( $decorationId ) {
$SQLSet [] = " `decoration_id` = { $decorationId } " ;
}
if ( $desc ) {
$SQLSet [] = " `desc` = ' $desc ' " ;
}
// EDIT
if ( $id ) {
$sql_in_image = " UPDATE complex_house_decoration SET " . implode ( ', ' , $SQLSet ) . " WHERE id = $id " ;
} else {
$sql_in_image = " INSERT INTO complex_house_decoration SET " . implode ( ', ' , $SQLSet );
}
$this -> db -> query ( $sql_in_image , true );
if ( ! $id ) {
$id = ( int ) $this -> db -> insert_id ();
}
return $id ;
}
public function deleteHouseDecoration ( $id )
{
if ( $id ) {
$selectSql = $this -> db -> query ( " SELECT photo FROM complex_house_decoration WHERE id = $id " );
$foundDecoration = $this -> db -> fetch_assoc ( $selectSql );
if ( $foundDecoration ) {
$this -> deleteFiles ([ $foundDecoration [ 'photo' ], $foundDecoration [ 'photo2' ], $foundDecoration [ 'photo3' ], $foundDecoration [ 'photo4' ], $foundDecoration [ 'photo5' ]]);
}
$this -> db -> query ( " DELETE FROM complex_house_decoration WHERE id = $id " );
return [ 'status' => true ];
} else {
return [ 'status' => false , 'message' => 'field id required' ];
}
}
public function saveHouseUTP ( $house_id , $desc = null , $id = null , $title = null , $photo )
{
if ( empty ( $house_id )) {
return [ 'status' => false ];
}
$SQLSet = [ " `house_id` = { $house_id } " ];
if ( $photo === null ) {
if ( $id ) {
$selectSql = $this -> db -> query ( " SELECT photo FROM complex_house_UTP WHERE id = $id " );
$foundUtp = $this -> db -> fetch_assoc ( $selectSql );
if ( $foundUtp ) {
$this -> deleteFiles ([ $foundUtp [ 'photo' ]]);
}
}
$SQLSet [] = " `photo` = NULL " ;
} else if ( $photo ) {
$newPhotos = $this -> uploadPhotosToEntity ([ $photo ], 'utp' , $house_id );
if ( isset ( $newPhotos [ 0 ])) {
$img = $newPhotos [ 0 ];
$SQLSet [] = " `photo` = ' { $img [ 'url' ] } ' " ;
}
}
if ( $title ) {
$SQLSet [] = " `title` = ' $title ' " ;
}
if ( $desc ) {
$SQLSet [] = " `desc` = ' $desc ' " ;
}
// EDIT
if ( $id ) {
$sql_in_image = " UPDATE complex_house_UTP SET " . implode ( ', ' , $SQLSet ) . " WHERE id = $id " ;
} else {
$sql_in_image = " INSERT INTO complex_house_UTP SET " . implode ( ', ' , $SQLSet );
}
$this -> db -> query ( $sql_in_image , true );
if ( ! $id ) {
$id = ( int ) $this -> db -> insert_id ();
}
return $id ;
}
public function deleteHouseUTP ( $id )
{
if ( $id ) {
$selectSql = $this -> db -> query ( " SELECT photo FROM complex_house_UTP WHERE id = $id " );
$foundUtp = $this -> db -> fetch_assoc ( $selectSql );
if ( $foundUtp ) {
$this -> deleteFiles ([ $foundUtp [ 'photo' ]]);
}
$this -> db -> query ( " DELETE FROM complex_house_UTP WHERE id = $id " );
return [ 'status' => true ];
} else {
return [ 'status' => false , 'message' => 'field id required' ];
}
}
public function uploadPhotosToEntity ( $photos , $entity_name , $entity_id = null )
{
if ( ! $entity_id ) {
$entity_id = 'new' ;
}
$Selectel = SelectelApi :: getTokenAndUrl ();
$token = $Selectel [ 0 ];
$storageUrl = $Selectel [ 1 ];
$uploaddir = $_SERVER [ 'DOCUMENT_ROOT' ] . " /photos/ $entity_name / " ;
$newPhotos = [];
foreach ( $photos as $photo ) {
$originalName = $photo [ 'name' ];
$strArray = explode ( " . " , $originalName );
$ext = mb_strtolower ( end ( $strArray ));
if ( $ext == " pjpeg " ) {
$ext = " jpeg " ;
}
$name = md5 ( time () . $originalName ) . " . " . $ext ;
$one = mb_substr ( $name , 0 , 1 );
$two = mb_substr ( $name , 1 , 1 );
$three = mb_substr ( $name , 3 , 1 );
$new_path = " $one / $two / $three / $name " ;
$fp = $uploaddir . $new_path ;
// create directories
if ( ! is_dir ( $uploaddir )) {
mkdir ( $uploaddir , 0777 , true );
}
if ( ! is_dir ( " $uploaddir / $one / $two / $three " )) {
mkdir ( " $uploaddir / $one / $two / $three " , 0777 , true );
}
if ( move_uploaded_file ( $photo [ 'tmp_name' ], $fp )) {
$fileSize = filesize ( $fp ); // get size before deletion
$SelectelApi = new SelectelApi ();
$remotePath = " / $entity_name / " . $entity_id . '/' . $new_path ;
$r = $SelectelApi -> uploadFile (
$storageUrl ,
$token ,
$fp ,
$remotePath ,
'image/' . $ext
);
if ( $r ) {
$url = " https://data.joywork.ru/ $entity_name / " . $entity_id . " / " . $new_path ;
// remove local file
unlink ( $fp );
$newPhotos [] = [
'file_path' => $remotePath , // or $fp if you prefer local
'original_name' => $originalName ,
'file_size' => $fileSize ,
'thumbnail_path' => null ,
'url' => $url
];
}
}
}
return $newPhotos ;
}
public function addPlanToHouse ( $house_id , $photos , $position )
{
$sql = " INSERT INTO complex_house_plans SET house_id = { $house_id } " ;
$r = $this -> db -> query ( $sql , true );
$plan_id = $this -> db -> insert_id ();
$plan_sql = " SELECT * FROM complex_house_plans WHERE id = { $plan_id } " ;
$plan_r = $this -> db -> query ( $plan_sql , true );
$plan = $this -> db -> fetch_assoc ( $plan_r );
$plan [ 'images' ] = $this -> addPhotosToRoomPlan ( $photos , $plan_id , $position );
return $plan ;
}
public function addMediaToHouse ( $house_id , $photos )
{
$medias = $this -> uploadPhotosToEntity ( $photos , " medias " , $house_id );
$result = [];
$thmbResult = null ;
$retval = null ;
$worker_script = dirname ( __FILE__ ) . '/worker_thumbnails.php' ;
$logFile = $_SERVER [ 'DOCUMENT_ROOT' ] . '/cron/logs/media-thumbnail.log' ;
foreach ( $medias as $media ) {
// safe fallback escaping
$file_path = addslashes ( $media [ 'file_path' ]);
$original_name = addslashes ( $media [ 'original_name' ]);
$file_size = ( int ) $media [ 'file_size' ];
$thumbnail_path = isset ( $media [ 'thumbnail_path' ]) && $media [ 'thumbnail_path' ]
? " ' " . addslashes ( $media [ 'thumbnail_path' ]) . " ' "
: " NULL " ;
$sql = "
INSERT INTO complex_house_media SET
complex_house_id = { $house_id },
file_path = '{$file_path}' ,
original_name = '{$original_name}' ,
file_size = { $file_size },
thumbnail_path = { $thumbnail_path },
created_at = NOW (),
updated_at = NOW ()
" ;
$this -> db -> query ( $sql , true );
$media [ 'id' ] = $this -> db -> insert_id ();
$mediaId = $media [ 'id' ];
exec ( " php $worker_script $mediaId $logFile >> $logFile 2>&1 & " , $thmbResult , $retval );
$result [] = [
'id' => ( int ) $media [ 'id' ],
'name' => $media [ 'original_name' ],
'size' => ( int ) $media [ 'file_size' ],
'url' => 'https://data.joywork.ru' . $media [ 'file_path' ],
'thumbnail_url' => $media [ 'thumbnail_path' ] ? 'https://data.joywork.ru/' . $media [ 'thumbnail_path' ] : null ,
'rooms' => []
];
}
return $result ;
}
public function deleteMediaFromHouse ( $house_id , $media_ids )
{
if ( empty ( $media_ids )) {
return [ 'status' => false , 'message' => 'No media IDs provided' ];
}
// ensure IDs are integers to prevent SQL injection
$media_ids = array_map ( 'intval' , $media_ids );
$ids_str = implode ( ',' , $media_ids );
// fetch only needed columns for this house
$sql = " SELECT file_path, thumbnail_path
FROM complex_house_media
WHERE complex_house_id = { $house_id }
AND id IN ({ $ids_str }) " ;
$r = $this -> db -> query ( $sql );
$medias = [];
while ( $row = $this -> db -> fetch_assoc ( $r )) {
$medias [] = $row ;
}
if ( empty ( $medias )) {
return [ 'status' => false , 'message' => 'No media found' ];
}
$baseUrl = 'https://data.joywork.ru' ;
$filesToDelete = [];
foreach ( $medias as $media ) {
if ( ! empty ( $media [ 'file_path' ])) {
$filesToDelete [] = $baseUrl . $media [ 'file_path' ];
}
if ( ! empty ( $media [ 'thumbnail_path' ])) {
$filesToDelete [] = $baseUrl . $media [ 'thumbnail_path' ];
}
}
// delete files
if ( ! empty ( $filesToDelete )) {
$this -> deleteFiles ( $filesToDelete );
}
// delete from DB
$deleteSql = " DELETE FROM complex_house_media
WHERE complex_house_id = { $house_id }
AND id IN ({ $ids_str }) " ;
$this -> db -> query ( $deleteSql );
return [ 'status' => true , 'deleted_count' => count ( $medias )];
}
public function getHouseMedia ( $house_id )
{
$sql = " SELECT * FROM complex_house_media WHERE complex_house_id = { $house_id } ORDER BY created_at DESC " ;
$q = $this -> db -> query ( $sql );
$result = [];
while ( $media = $this -> db -> fetch_assoc ( $q )) {
$result [] = [
'id' => ( int ) $media [ 'id' ],
'name' => $media [ 'original_name' ],
'size' => ( int ) $media [ 'file_size' ],
'url' => 'https://data.joywork.ru' . $media [ 'file_path' ],
'thumbnail_url' => $media [ 'thumbnail_path' ] ? 'https://data.joywork.ru/' . $media [ 'thumbnail_path' ] : null ,
'rooms' => []
];
}
return $result ;
}
public function addMediaSetToHouse ( $house_id , $mediaSetName , $photos = null )
{
$house_id = ( int ) $house_id ;
$color = $this -> generateUniqueColor ( $house_id );
// 1. Create set
$sql = "
INSERT INTO complex_house_media_set ( complex_house_id , name , color , created_at )
VALUES ({ $house_id }, '{$mediaSetName}' , '{$color}' , NOW ())
" ;
$this -> db -> query ( $sql );
$set_id = $this -> db -> insert_id ();
return [
'id' => $set_id ,
'name' => $mediaSetName ,
'color' => $color ,
'items' => [],
'rooms' => []
];
}
public function deleteMediaSetFromHouse ( $house_id , $set_id )
{
try {
$house_id = ( int ) $house_id ;
$set_id = ( int ) $set_id ;
$sql = " DELETE FROM complex_house_media_set
WHERE id = $set_id AND complex_house_id = $house_id " ;
$this -> db -> query ( $sql );
return [ 'status' => true ];
} catch ( \Throwable $th ) {
return [ 'status' => false ];
}
}
public function getMediaSetsForHouse ( $house_id )
{
$house_id = ( int ) $house_id ;
// 1. Fetch all sets for the house
$sql = " SELECT * FROM complex_house_media_set WHERE complex_house_id = { $house_id } ORDER BY created_at DESC " ;
$q = $this -> db -> query ( $sql );
$sets = [];
while ( $set = $this -> db -> fetch_assoc ( $q )) {
$set_id = ( int ) $set [ 'id' ];
$rooms = $this -> getMediaSetRooms ( $set_id );
// 2. Fetch items for this set, ordered by sort_order
$itemsSql = "
SELECT m . id , m . original_name AS name , m . file_size AS size , m . file_path AS url , m . thumbnail_path AS thumbnail_url , si . sort_order as sort_order
FROM complex_house_media_set_item si
JOIN complex_house_media m ON m . id = si . media_id
WHERE si . set_id = { $set_id }
ORDER BY si . sort_order ASC
" ;
$itemsQ = $this -> db -> query ( $itemsSql );
$items = [];
while ( $item = $this -> db -> fetch_assoc ( $itemsQ )) {
$items [] = [
'id' => ( int ) $item [ 'id' ],
'name' => $item [ 'name' ],
'size' => ( int ) $item [ 'size' ],
'url' => 'https://data.joywork.ru' . $item [ 'url' ],
'thumbnail_url' => $item [ 'thumbnail_url' ] ? 'https://data.joywork.ru/' . $item [ 'thumbnail_url' ] : null ,
'sort_order' => ( int ) $item [ 'sort_order' ]
];
}
// 3. Add set with items
$sets [] = [
'id' => $set_id ,
'name' => $set [ 'name' ],
'color' => $set [ 'color' ],
'items' => $items ,
'rooms' => $rooms
];
}
return $sets ;
}
public function updateMediaSet ( $set_id , $items , $name = null )
{
$sql = "
DELETE FROM complex_house_media_set_item
WHERE set_id = { $set_id }
" ;
$this -> db -> query ( $sql );
// Prepare bulk insert
$values = [];
foreach ( $items as $item ) {
$media_id = ( int ) $item [ 'media_id' ];
$sort_order = ( int ) $item [ 'sort_order' ];
$values [] = " ( { $set_id } , { $media_id } , { $sort_order } ) " ;
}
if ( ! empty ( $values )) {
$sql = "
INSERT INTO complex_house_media_set_item ( set_id , media_id , sort_order )
VALUES " . implode(',', $values );
$this -> db -> query ( $sql );
}
if ( $name ) {
$sql = "
UPDATE complex_house_media_set
SET name = '{$name}'
WHERE id = { $set_id }
" ;
$this -> db -> query ( $sql );
}
return [ 'status' => true ];
}
public function removeItemFromMediaSet ( $set_id , $media_id )
{
$set_id = ( int ) $set_id ;
$media_id = ( int ) $media_id ;
// Get the sort_order of the item being deleted
$sql = "
SELECT sort_order
FROM complex_house_media_set_item
WHERE set_id = { $set_id } AND media_id = { $media_id }
LIMIT 1
" ;
$result = $this -> db -> query ( $sql );
$row = $this -> db -> fetch_assoc ( $result );
if ( ! $row ) {
return [ 'status' => false , 'error' => 'Item not found' ];
}
$deletedOrder = ( int ) $row [ 'sort_order' ];
try {
// Delete the item
$sql = "
DELETE FROM complex_house_media_set_item
WHERE set_id = { $set_id } AND media_id = { $media_id }
" ;
$this -> db -> query ( $sql );
// Shift remaining items up
$sql = "
UPDATE complex_house_media_set_item
SET sort_order = sort_order - 1
WHERE set_id = { $set_id } AND sort_order > { $deletedOrder }
" ;
$this -> db -> query ( $sql );
return [ 'status' => true ];
} catch ( \Exception $e ) {
return [ 'status' => false , 'error' => $e -> getMessage ()];
}
}
public function addRoomsToMediaSet ( $set_id , $room_ids )
{
if ( empty ( $set_id )) {
return [];
}
$sqlDelete = " DELETE FROM complex_house_media_set_room WHERE set_id = $set_id " ;
$q = $this -> db -> query ( $sqlDelete );
if ( ! empty ( $room_ids )) {
// Prepare IDs safely
$room_ids = array_map ( 'intval' , $room_ids );
$idsStr = implode ( ',' , $room_ids );
// 1. Remove rooms from ANY set (including current one)
$sqlDeleteRooms = "
DELETE FROM complex_house_media_set_room
WHERE complex_room_id IN ( $idsStr )
" ;
$this -> db -> query ( $sqlDeleteRooms );
// 2. Insert into new set
$insertValues = [];
foreach ( $room_ids as $room_id ) {
$insertValues [] = " ( $set_id , $room_id ) " ;
}
$valuesStr = implode ( ', ' , $insertValues );
$sqlInsert = "
INSERT INTO complex_house_media_set_room ( set_id , complex_room_id )
VALUES $valuesStr
" ;
$this -> db -> query ( $sqlInsert );
}
return $this -> getMediaSetRooms ( $set_id );
}
public function getMediaSetRooms ( $set_id )
{
$sql = " SELECT r.id, r.position, r.type, r.number FROM complex_house_media_set_room msr JOIN complex_rooms r ON msr.complex_room_id = r.id WHERE msr.set_id = $set_id " ;
$q = $this -> db -> query ( $sql );
$rooms = [];
while ( $room = $this -> db -> fetch_assoc ( $q )) {
$rooms [] = [
'id' => ( int ) $room [ 'id' ],
'position' => ( int ) $room [ 'position' ],
'type' => $room [ 'type' ],
'number' => $room [ 'number' ]
];
}
return $rooms ;
}
public function updateMediaItemSortOrder ( $set_id , $media_id , $oldIndex , $newIndex )
{
$set_id = ( int ) $set_id ;
$media_id = ( int ) $media_id ;
$oldIndex = ( int ) $oldIndex ;
$newIndex = ( int ) $newIndex ;
if ( $oldIndex === $newIndex ) {
return [ 'status' => true , 'message' => 'No change needed' ];
}
// If DB sort_order is 1-based, add 1
$oldOrder = $oldIndex + 1 ;
$newOrder = $newIndex + 1 ;
try {
if ( $newOrder < $oldOrder ) {
// Moving up: shift items down
$sql = "
UPDATE complex_house_media_set_item
SET sort_order = sort_order + 1
WHERE set_id = { $set_id }
AND sort_order >= { $newOrder }
AND sort_order < { $oldOrder }
" ;
} else {
// Moving down: shift items up
$sql = "
UPDATE complex_house_media_set_item
SET sort_order = sort_order - 1
WHERE set_id = { $set_id }
AND sort_order > { $oldOrder }
AND sort_order <= { $newOrder }
" ;
}
$this -> db -> query ( $sql );
// Update moved item
$sql = "
UPDATE complex_house_media_set_item
SET sort_order = { $newOrder }
WHERE set_id = { $set_id } AND media_id = { $media_id }
" ;
$this -> db -> query ( $sql );
return [ 'status' => true ];
} catch ( \Exception $e ) {
return [ 'status' => false , 'error' => $e -> getMessage ()];
}
}
public function getMediaSetForRoom ( $roomId )
{
// 1. Получаем сам set
$sql = "
SELECT s . id , s . name , s . color
FROM complex_house_media_set_room msr
JOIN complex_house_media_set s ON s . id = msr . set_id
WHERE msr . complex_room_id = " . (int) $roomId . "
LIMIT 1
" ;
$q = $this -> db -> query ( $sql );
$set = $this -> db -> fetch_assoc ( $q );
if ( ! $set ) {
return null ; // у комнаты нет набора
}
$set_id = ( int ) $set [ 'id' ];
// 2. Получаем items (медиа)
$sql = "
SELECT
m . id ,
m . file_path ,
m . thumbnail_path ,
m . original_name ,
m . file_size ,
si . sort_order
FROM complex_house_media_set_item si
JOIN complex_house_media m ON m . id = si . media_id
WHERE si . set_id = $set_id
ORDER BY si . sort_order
" ;
$q = $this -> db -> query ( $sql );
$items = [];
while ( $row = $this -> db -> fetch_assoc ( $q )) {
$items [] = [
'id' => ( int ) $row [ 'id' ],
'url' => 'https://data.joywork.ru' . $row [ 'file_path' ],
'thumbnail_url' => $row [ 'thumbnail_path' ] ? 'https://data.joywork.ru/' . $row [ 'thumbnail_path' ] : null ,
'original_name' => $row [ 'original_name' ],
'file_size' => ( int ) $row [ 'file_size' ],
'sort_order' => ( int ) $row [ 'sort_order' ],
];
}
// 4. Собираем итог
return [
'id' => $set_id ,
'name' => $set [ 'name' ],
'color' => $set [ 'color' ],
'items' => $items ,
];
}
public function getHouseMediaCompletionPercentage ( $house_id )
{
$sql = "
SELECT
COUNT ( DISTINCT r . id ) AS total_rooms ,
COUNT ( DISTINCT msr . complex_room_id ) AS used_rooms
FROM complex_rooms r
INNER JOIN complex_floors f
ON r . floor_id = f . id
INNER JOIN complex_entrances e
ON f . complex_entrance_id = e . id
LEFT JOIN complex_house_media_set_room msr
ON msr . complex_room_id = r . id
WHERE e . complex_house_id = { $house_id }
" ;
$q = $this -> db -> query ( $sql );
$r = $this -> db -> fetch_assoc ( $q );
return round (( $r [ 'used_rooms' ] / $r [ 'total_rooms' ]) * 100 );
}
public function get_media_entrances ( $house_id )
{
$this -> set_user ();
$result = array ();
$sql = " SELECT complex_entrances.*, ch.name as house_name, ch.parking as house_parking, ch.security as house_security, ch.fenced_area as house_fenced_area, ch.sports_ground as house_sports_ground, ch.play_ground as house_play_ground, ch.school as house_school, ch.kinder_garten as house_kinder_garten, ch.id as house_id, cl.name as complex_name FROM complex_entrances
JOIN complex_houses ch ON ch . id = complex_entrances . complex_house_id
JOIN complex_list cl ON cl . id = ch . complex_id
WHERE complex_entrances . complex_house_id = { $house_id } " ;
$q = $this -> db -> query ( $sql );
while ( $entrance = $this -> db -> fetch_assoc ( $q )) {
$floors = $this -> get_media_entrance_floors ( $entrance );
$entrance [ 'floors' ] = $floors ;
$result [] = $entrance ;
}
return $result ;
}
public function get_media_entrance_floors ( $entrance )
{
$this -> set_user ();
$entrance_id = $entrance [ 'id' ];
$sql = " SELECT DISTINCT complex_floors.*, floor_plans.has_light_angle as has_light_angle, floor_plans.light_angle as light_angle FROM complex_floors
LEFT JOIN complex_floors_plans floor_plan_link ON floor_plan_link . floor_id = complex_floors . id
LEFT JOIN complex_house_floor_plans floor_plans ON floor_plans . id = floor_plan_link . floor_plan_id
WHERE complex_entrance_id = { $entrance_id } " ;
$q = $this -> db -> query ( $sql );
$floors = [];
while ( $floor = $this -> db -> fetch_assoc ( $q )) {
$floor [ 'rooms' ] = [];
$floorId = ( int ) $floor [ 'id' ];
$sql = " SELECT
complex_rooms . id ,
position ,
type ,
number ,
layout_feature ,
rooms_count ,
cs . name as status_name ,
cs . status as status_type ,
cs . color as status_color
FROM complex_rooms
LEFT JOIN complex_status cs
ON complex_rooms . complex_status_id = cs . id
AND cs . is_archive = 0
WHERE floor_id = $floorId " ;
$roomsResult = $this -> db -> query ( $sql );
while ( $room = $this -> db -> fetch_assoc ( $roomsResult )) {
$room [ 'complex_status_info' ] = [
'status_name' => $room [ 'status_name' ],
'status_type' => $room [ 'status_type' ],
'status_color' => $room [ 'status_color' ]
];
unset ( $room [ 'status_name' ], $room [ 'status_type' ], $room [ 'status_color' ]);
$floor [ 'rooms' ][] = $room ;
}
$floors [] = $floor ;
}
return $floors ;
}
public function addFloorPlanToHouse ( $house_id , $photo )
{
$sql = " INSERT INTO complex_house_floor_plans SET house_id = { $house_id } " ;
$r = $this -> db -> query ( $sql , true );
$plan_id = $this -> db -> insert_id ();
$this -> addPhotoToFloorPlan ( $photo , $plan_id );
$plan_sql = " SELECT * FROM complex_house_floor_plans WHERE id = { $plan_id } " ;
$plan_r = $this -> db -> query ( $plan_sql , true );
$plan = $this -> db -> fetch_assoc ( $plan_r );
return $plan ;
}
public function addPhotoToFloorPlan ( $photo , $floor_plan_id )
{
$newPhotos = $this -> uploadPhotosToEntity ([ $photo ], " floor_plans " , $floor_plan_id );
$q = $this -> db -> query ( " DELETE FROM complex_floor_plan_figures WHERE floor_plan_id = { $floor_plan_id } " ); // TODO
$result = '' ;
if ( count ( $newPhotos )) {
$image = $newPhotos [ 0 ];
$sql_in_image = " UPDATE complex_house_floor_plans SET `image` = ' { $image [ 'url' ] } ', `name` = ' { $image [ 'name' ] } ' WHERE `id` = { $floor_plan_id } " ;
$r = $this -> db -> query ( $sql_in_image , true );
$result = $image ;
}
return $result ;
}
public function addPhotosToRoomPlan ( $photos , $plan_id , $position )
{
$newPhotos = $this -> uploadPhotosToEntity ( $photos , " plans " , $plan_id );
$result = [];
foreach ( $newPhotos as $image ) {
$sql_in_image = " INSERT INTO complex_house_plans_images SET plan_id = { $plan_id } , position = { $position } , url=' { $image [ 'url' ] } ', name=' { $image [ 'name' ] } ' " ;
$r = $this -> db -> query ( $sql_in_image , true );
$image_id = $this -> db -> insert_id ();
$r = $this -> db -> query ( " SELECT * FROM complex_house_plans_images where id= { $image_id } " );
$plan_image = $this -> db -> fetch_assoc ( $r );
$result [] = $plan_image ;
}
return $result ;
}
/**
*
*/
public function save_photo2 ( $photos , $patch )
{
$this -> set_user ();
$Selectel = SelectelApi :: getTokenAndUrl ();
$token = $Selectel [ 0 ];
$storageUrl = $Selectel [ 1 ];
foreach ( $photos as $filePos ) {
if ( ! isset ( $filePos -> file ) && strpos ( $filePos , " https:// " ) !== false ) {
$newPhotos [] = $filePos ;
} elseif ( isset ( $filePos -> file ) && strpos ( $filePos -> file , " https:// " ) !== false ) {
$newPhotos [] = $filePos -> file ;
} else {
if ( strpos ( $filePos -> file , " 0:/ " ) !== false ) {
$originalName = str_replace ( " 0:/ " , " " , $filePos -> file );
$strArray = explode ( " . " , $originalName );
$ext = end ( $strArray );
if ( $ext == " pjpeg " ) {
$ext = " jpeg " ;
}
$ext = mb_strtolower ( $ext );
$name = md5 ( time () . $originalName ) . " . " . $ext ;
$one = mb_substr ( $name , 0 , 1 );
$two = mb_substr ( $name , 1 , 1 );
$three = mb_substr ( $name , 3 , 1 );
$new_path = " $one / $two / $three / $name " ;
// $photo = "/photos/complexes/" . $new_path;
$oldPath = $_SERVER [ 'DOCUMENT_ROOT' ] . " /photos/complexes/complex_temp/ " . $patch . " / " . $_SESSION [ 'id' ] . " / " . $originalName ;
//загрузка в Selectel
$fp = $oldPath ;
$SelectelApi = new SelectelApi ();
$r = $SelectelApi -> uploadFile ( $storageUrl , $token , $fp , '/complexes/' . $patch . '/' . $new_path , 'image/' . $ext );
//если выложили в Selectel
if ( $r ) {
//заменяем путь на новый
$new_path = " https://data.joywork.ru/complexes/ " . $patch . " / " . $new_path ;
//удаляем файл с локального сервера
unlink ( $fp );
}
// echo $new_path."\n";
$newPhotos [] = $new_path ;
}
}
}
if ( isset ( $err )) {
$result [ 'error' ] = $err ;
}
if ( isset ( $newPhotos )) {
$result = $newPhotos ;
} else {
$result = '' ;
}
return $result ;
}
/**
* Сохранение комплекса
* @ return array $result
*/
public function save ( $linkBuilder , $phoneBuilder , $photo = null )
{
$this -> set_user ();
$photo_links = [];
if ( ! empty ( $photo ) && ! isset ( $photo [ 'error' ])){
$photo_links = $this -> save_photo ( $photo );
}
$result = '' ;
$complex_id = ( int ) $this -> complex -> id ;
$builder_id = ( int ) $this -> complex -> builder_id ;
if ( $builder_id > 0 ) {
$sql_info = " SELECT id FROM complex_builders WHERE builder_id = { $builder_id } or id = { $builder_id } " ;
$q_info = $this -> db -> query ( $sql_info );
if ( $this -> db -> num_rows ( $q_info ) > 0 ) {
$this -> db -> fetch_assoc ( $q_info );
$sql_up = " UPDATE complex_builders SET phone=' { $phoneBuilder } ', link=' { $linkBuilder } ' WHERE builder_id = { $builder_id } or id = { $builder_id } " ;
} else {
$sql_up = " INSERT INTO complex_builders SET phone=' { $phoneBuilder } ', link=' { $linkBuilder } ', builder_id = { $builder_id } " ;
}
// echo $sql_up."\n";
$this -> db -> query ( $sql_up );
}
$arrayComplexList = array ( 'name' , 'type' , 'country_id' , 'rf_region_id' , 'rayon_id' , 'builder_id' , 'payment_types' , 'contract_type' , 'house_type' , 'cian_id' , 'avito_id' , 'yandex_id' , 'domclick_id' , 'domclick_builder_id' , 'has_show_room' , 'cadastral_number' , 'domrf_id' ,
'housing_class_id' , 'number_apartments' , 'first_floor' , 'last_floor' , 'ceiling_height' , 'decoration_id' , 'house_material' , 'parking' , 'closed_area' , 'protected_area' , 'concierge' );
$arrayComplexSet = array ();
$arrayComplexAddress = array ( 'address' , 'rayon' , 'city' , 'street' , 'korpus' , 'dom' , 'litera' , 'kladr_id' , 'latitude' , 'longitude' );
$arrayComplexAddressSet = array ();
//$arrayComplexInfrastructure = array('complex_id', 'school', 'kindergarten', 'playgrounds', 'sportsgrounds', 'cafes', 'shops', 'beautysalons', 'fitnessclub', 'park', 'trc', 'commercialobjects');
$arrayComplexInfrastructureSet = array ();
$arrayComplexMetroSet = array ();
$arrayComplexDop = array ();
$arrayComplexUTP = array ();
$arrayComplexUTP2 = array ();
foreach ( $this -> complex as $key => $complex_val ) {
if ( in_array ( $key , $arrayComplexList )) {
if (( $key === 'rayon_id' || $key === " domclick_id " || $key === " domclick_builder_id " || $key === " cian_id " || $key === " avito_id " || $key === " yandex_id " || $key === " domrf_id " ) && empty ( $complex_val )) {
$arrayComplexSet [] = $key . " = 0 " ;
} else if ( $key == 'payment_types' ) {
$arrayComplexSet [] = $key . " = ' " . json_encode ( $complex_val ) . " ' " ;
} else {
$arrayComplexSet [] = $key . " = ' " . $complex_val . " ' " ;
}
}
if ( $key == 'address' ) {
foreach ( $complex_val as $address_key => $address_value ) {
if ( in_array ( $address_key , $arrayComplexAddress )) {
$arrayComplexAddressSet [] = $address_key . " = ' " . $address_value . " ' " ;
}
}
}
if ( $key == 'infrastructure' ) {
foreach ( $complex_val as $keyi => $infrastructure_val ) {
$arrayComplexInfrastructureSet [] = $keyi . " = " . $infrastructure_val ;
}
}
if ( $key == 'metros' ) {
if ( $this -> complex -> id > 0 ) {
$this -> db -> query ( " DELETE FROM complex_metro WHERE complex_id = { $this -> complex -> id } " );
foreach ( $complex_val as $metro ) {
foreach ( $metro as $keym => $metro_val ) {
if ( $keym == 'id' ) {
continue ;
}
if ( $keym != 'metro' ) {
if ( ! is_numeric ( $metro_val )) {
$metro_val = " ' $metro_val ' " ;
}
$arrayComplexMetroSet [] = $keym . " = $metro_val " ;
}
}
$arrayComplexMetroSet [] = 'complex_id = ' . $this -> complex -> id ;
$sql_in_metro = " INSERT INTO complex_metro SET " . implode ( ',' , $arrayComplexMetroSet );
$this -> db -> query ( $sql_in_metro , true );
$arrayComplexMetroSet = [];
}
}
}
if ( $key == 'dop' ) {
foreach ( $complex_val as $key_dop => $dop_val ) {
if ( $key_dop != 'complex_id' && $key_dop != 'UTP' && $key_dop != 'UTP2' && $key_dop != 'workdays_op' ) {
$arrayComplexDop [] = $key_dop . " = ' " . $dop_val . " ' " ;
} else if ( $key_dop == 'UTP' ) {
$arrayComplexUTP = $dop_val ;
} else if ( $key_dop == 'UTP2' ) {
$arrayComplexUTP2 = $dop_val ;
} else if ( $key_dop == 'workdays_op' ) {
if ( empty ( $dop_val ) || $dop_val == 'null' ) {
$arrayComplexDop [] = $key_dop . " = '' " ;
} else {
$arrayComplexDop [] = $key_dop . " = ' " . json_encode ( $dop_val , JSON_UNESCAPED_UNICODE ) . " ' " ;
}
}
}
}
}
$arrayComplexSet [] = 'user_id = ' . $this -> user -> id ;
$arrayComplexSet [] = 'agency_id = ' . $this -> user -> agencyId ;
$sql_in = '' ;
$set_query_complex = implode ( ',' , $arrayComplexSet );
if ( $this -> complex -> id > 0 ) {
$sql_in = " UPDATE " . $this -> table . " SET " . $set_query_complex . " WHERE id = " . $this -> complex -> id ;
} else {
$sql_in = " INSERT INTO " . $this -> table . " SET " . $set_query_complex ;
}
if ( $this -> db -> query ( $sql_in , true )) {
$complex_id = $this -> db -> insert_id ();
if ( $this -> complex -> id > 0 ) {
$sql_in_infrastructure = " UPDATE complex_infrastructure SET " . implode ( ',' , $arrayComplexInfrastructureSet ) . " WHERE complex_id = " . $this -> complex -> id ;
$sql_in_address = " UPDATE complex_address SET " . implode ( ',' , $arrayComplexAddressSet ) . " WHERE complex_id = " . $this -> complex -> id ;
// $sql_in_metro = "UPDATE complex_metro SET " . implode(',', $arrayComplexMetroSet) . " WHERE complex_id = " . $this->complex->id;
if ( $this -> db -> num_rows ( $this -> db -> query ( " SELECT id FROM complex_dop WHERE complex_id = { $this -> complex -> id } " )) > 0 ) {
$sql_in_dop = " UPDATE complex_dop SET " . implode ( ', ' , $arrayComplexDop ) . " WHERE complex_id = " . $this -> complex -> id ;
} else {
$arrayComplexDop [] = 'complex_id = ' . $this -> complex -> id ;
$sql_in_dop = " INSERT INTO complex_dop SET " . implode ( ', ' , $arrayComplexDop );
}
} else {
$arrayComplexInfrastructureSet [] = 'complex_id = ' . $complex_id ;
$arrayComplexAddressSet [] = 'complex_id = ' . $complex_id ;
$arrayComplexMetroSet = [];
if ( isset ( $this -> complex -> metros )) {
foreach ( $this -> complex -> metros as $metro ) {
foreach ( $metro as $keym => $metro_val ) {
if ( $keym != 'metro' ) {
if ( ! is_numeric ( $metro_val )) {
$metro_val = " ' $metro_val ' " ;
}
$arrayComplexMetroSet [] = $keym . " = $metro_val " ;
}
}
$arrayComplexMetroSet [] = 'complex_id = ' . $complex_id ;
$sql_in_metro = " INSERT INTO complex_metro SET " . implode ( ',' , $arrayComplexMetroSet );
$this -> db -> query ( $sql_in_metro , true );
$arrayComplexMetroSet = [];
}
}
// $arrayComplexMetroSet[] = 'complex_id = ' . $complex_id;
$arrayComplexDop [] = 'complex_id = ' . $complex_id ;
$sql_in_infrastructure = " INSERT INTO complex_infrastructure SET " . implode ( ',' , $arrayComplexInfrastructureSet );
$sql_in_address = " INSERT INTO complex_address SET " . implode ( ',' , $arrayComplexAddressSet );
// var_dump($sql_in_address);die;
// if(!empty($arrayComplexDop)){
$sql_in_dop = " INSERT INTO complex_dop SET " . implode ( ',' , $arrayComplexDop );
// }
}
//echo $sql_in_dop."\n";
$this -> db -> query ( $sql_in_address , true );
$this -> db -> query ( $sql_in_infrastructure , true );
$this -> db -> query ( $sql_in_dop , true );
if ( $complex_id == 0 && $this -> complex -> id > 0 ) {
$complex_id = $this -> complex -> id ;
}
if ( count ( $photo_links )) {
$this -> db -> query ( " DELETE FROM complex_images WHERE complex_id = { $complex_id } " , true );
foreach ( $photo_links as $image ) {
$sql_in_image = " INSERT INTO complex_images SET complex_id = { $complex_id } , image = ' " . $image . " ' " ;
$this -> db -> query ( $sql_in_image , true );
}
}
if ( property_exists ( $this -> complex , 'lines' )) {
foreach ( $this -> complex -> lines as $lines ) {
foreach ( $lines -> corpuses as $deadline ) {
$period = ( int ) strtotime ( $deadline -> deadline );
// var_dump($deadline);
$deadline_base = date ( 'Y-m-d' , $period );
if ( $deadline -> del == 0 and $deadline -> id == 0 ) {
$sql_in_deadline = " INSERT INTO complex_corpuses SET
complex_id = { $complex_id },
corpus = '{$deadline->corpus}' ,
line = '{$lines->name}' ,
deadline = '{$deadline_base}' ,
period = '{$period}' ,
corpus_id = '{$deadline->corpus_id}' ,
corpus_floors = { $deadline -> corpus_floors },
corpus_floors_ready = { $deadline -> corpus_floors_ready },
corpus_fz_214 = { $deadline -> corpus_fz_214 },
corpus_status = '{$deadline->corpus_status}'
" ;
$this -> db -> query ( $sql_in_deadline , true );
} else if ( $deadline -> del == 0 and $deadline -> id > 0 ) {
$sql_in_deadline = " UPDATE complex_corpuses SET
complex_id = { $complex_id },
corpus = '{$deadline->corpus}' ,
line = '{$lines->name}' ,
deadline = '{$deadline_base}' ,
period = '{$period}' ,
corpus_id = '{$deadline->corpus_id}' ,
corpus_floors = { $deadline -> corpus_floors },
corpus_floors_ready = { $deadline -> corpus_floors_ready },
corpus_fz_214 = { $deadline -> corpus_fz_214 },
corpus_status = '{$deadline->corpus_status}'
WHERE id = { $deadline -> id }
" ;
$this -> db -> query ( $sql_in_deadline , true );
} else if ( $deadline -> del > 0 && $deadline -> id > 0 ) {
$sql_del_deadline = " DELETE FROM complex_corpuses WHERE id = { $deadline -> id } " ;
$this -> db -> query ( $sql_del_deadline );
}
}
}
}
$this -> saveUTP ( $arrayComplexUTP , $complex_id );
$this -> saveUTP ( $arrayComplexUTP2 , $complex_id , 'secondary' );
// $this->saveActions($this->complex->actions, $complex_id);
$result = array ( 'result' => 'done' , 'complex_id' => $complex_id , 'sql' => $sql_in_dop );
} else {
$result = 'error' ;
}
//echo $sql_in;
return $result ;
}
/**
*
*/
public function saveUTP ( $arrayUTP , $complex_id , $type = 'main' )
{
$this -> db -> query ( " DELETE FROM complex_UTP WHERE complex_id = { $complex_id } and type=' { $type } ' " );
foreach ( $arrayUTP as $utp ) {
$set = '' ;
$set = " title = ' { $utp -> title } ', desck = ' { $utp -> desc } ' " ;
// if(!empty($utp->images)){
//var_dump($utp->images);
if ( $type == 'main' ) {
$images = $this -> save_photo2 ( $utp -> images , 'UTP' );
} else if ( $type == 'secondary' ) {
$images = $this -> save_photo2 ( $utp -> images , 'UTP2' );
}
//if(!empty($images)){
$photos = json_encode ( $images );
//var_dump($photos);
if ( $photos == 'null' ) $photos = '' ;
$set .= " , photos = ' { $photos } ' " ;
$set .= " , type = ' { $type } ' " ;
//}
//}
$set .= " , complex_id = { $complex_id } " ;
$sql_insert = " INSERT INTO complex_UTP SET { $set } " ;
//echo $sql_insert."\n";
$this -> db -> query ( $sql_insert );
}
}
// public function saveActions($actions, $complex_id)
// {
// $this->db->query("DELETE FROM complex_actions WHERE complex_id = {$complex_id}");
// foreach ($actions as $action) {
// //var_dump($action);
// $set = '';
// if (empty($action->name)) $action->name = 'Название не указано';
// $set .= "name = '{$action->name}', `desc` = '{$action->desc}', link = '{$action->link}'";
// $images = $this->save_photo2($action->images, 'Action');
// $photos = json_encode($images);
// if ($photos == 'null') $photos = '';
// $set .= ", images = '{$photos}'";
// $set .= ", complex_id = {$complex_id}";
// $sql_insert = "INSERT INTO complex_actions SET {$set}";
// //echo $sql_insert;
// $this->db->query($sql_insert);
// }
// }
public function saveComplexAction ( $name , $desc , $image , $link , $id , $complex_id )
{
if ( empty ( $complex_id )) {
return [ 'status' => false , 'message' => 'complex_id required' ];
}
if ( empty ( $name )) $name = 'Название не указано' ;
$set = [];
if ( ! empty ( $name )) {
$set [] = " `name` = ' $name ' " ;
}
if ( ! empty ( $desc )) {
$set [] = " `desc` = ' $desc ' " ;
}
if ( ! empty ( $link )) {
$set [] = " `link` = ' $link ' " ;
}
$image = $this -> uploadPhotosToEntity ([ $image ], 'ComplexAction' , $complex_id );
$photo = isset ( $image [ 0 ]) ? $image [ 0 ] : '' ;
$set [] = " `image` = ' { $photo [ 'url' ] } ' " ;
$set [] = " `complex_id` = { $complex_id } " ;
if ( $id ) {
$sql_insert = " UPDATE complex_actions SET " . implode ( ', ' , $set ) . " WHERE id = $id " ;
} else {
$sql_insert = " INSERT INTO complex_actions SET " . implode ( ', ' , $set ) . " " ;
}
//echo $sql_insert;
$this -> db -> query ( $sql_insert , true );
if ( ! $id ) {
$id = ( int ) $this -> db -> insert_id ();
}
return [
'status' => true ,
'action' => [
'id' => $id ,
'name' => $name ,
'desc' => $desc ,
'link' => $link ,
'complex_id' => $complex_id ,
'image' => $photo [ 'url' ]
]
];
}
public function deletecComplesAction ( $id )
{
if ( $id ) {
$selectSql = $this -> db -> query ( " SELECT image FROM complex_actions WHERE id = $id " );
$foundUtp = $this -> db -> fetch_assoc ( $selectSql );
if ( $foundUtp ) {
$this -> deleteFiles ([ $foundUtp [ 'image' ]]);
}
$this -> db -> query ( " DELETE FROM complex_actions WHERE id = $id " );
return [ 'status' => true ];
} else {
return [ 'status' => false , 'message' => 'field id required' ];
}
}
/**
* Добавление дома
*/
public function add_edit_house ( $house )
{
$this -> set_user ();
$house = json_decode ( json_encode ( $house ), true );
// var_dump($house);
$arrColumnHouse = [
'id' ,
'complex_id' ,
'name' ,
'address' ,
'type_building' ,
'placement_type' ,
'decoration_id' ,
'house_type' ,
'status_corpus' ,
'deadline_quarter' ,
'deadline_year' ,
'development_start_quarter' ,
'development_start_year' ,
'development_end_quarter' ,
'development_end_year' ,
'sales_start_month' ,
'sales_start_year' ,
'sales_end_month' ,
'sales_end_year' ,
'is_archive' ,
'agency_id' ,
'user_id' ,
'security' ,
'parking' ,
'fenced_area' ,
'sports_ground' ,
'play_ground' ,
'school' ,
'kinder_garten' ,
'cian_id' ,
'avito_id' ,
'yandex_id' ,
'domclick_id' ,
'domclick_builder_id' ,
'is_partner_show' ,
'domrf_id' ,
];
$arrUTPColumns = [
'id' ,
'house_id' ,
'title' ,
'desck' ,
'type' ,
'photo'
];
$arrUKeys = array ();
$arrUVals = array ();
$arrKeys = array ();
$arrVals = array ();
foreach ( $arrColumnHouse as $column ) {
if ( $column == 'deadline_quarter' || $column == 'development_end_quarter' || $column == 'development_start_quarter' ) {
$temp_column = str_replace ( '_quarter' , '' , $column );
if ( isset ( $house [ $temp_column ][ 'quarter' ]) && ( $house [ $temp_column ][ 'quarter' ] != null || $house [ $temp_column ][ 'quarter' ] != 0 )) {
$arrKeys [] = $column ;
$arrVals [] = " ' " . $house [ $temp_column ][ 'quarter' ] . " ' " ;
}
} else if ( $column == 'deadline_year' || $column == 'development_start_year' || $column == 'development_end_year' || $column == 'sales_start_year' || $column == 'sales_end_year' ) {
$temp_column = str_replace ( '_year' , '' , $column );
if ( isset ( $house [ $temp_column ][ 'year' ]) && ( $house [ $temp_column ][ 'year' ] != null || $house [ $temp_column ][ 'year' ] != 0 )) {
$arrKeys [] = $column ;
$arrVals [] = " ' " . $house [ $temp_column ][ 'year' ] . " ' " ;
}
} else if ( $column == 'sales_start_month' || $column == 'sales_end_month' ) {
$temp_column = str_replace ( '_month' , '' , $column );
// var_dump($temp_column);
// var_dump($house[$temp_column]);
if ( isset ( $house [ $temp_column ][ 'month' ]) && ( $house [ $temp_column ][ 'month' ] != null || $house [ $temp_column ][ 'month' ] != 0 )) {
$arrKeys [] = $column ;
$arrVals [] = " ' " . $house [ $temp_column ][ 'month' ] . " ' " ;
}
} else if ( $column == 'agency_id' ) {
$arrKeys [] = $column ;
$arrVals [] = $this -> user -> agencyId ;
} else if ( $column == 'user_id' ) {
$arrKeys [] = $column ;
$arrVals [] = $this -> user -> id ;
} else {
if ( isset ( $house [ $column ]) && ( $house [ $column ] !== null || $house [ $column ] !== 0 )) {
$arrKeys [] = $column ;
if ( $column == 'is_archive' ) {
$arrVals [] = ( int ) $house [ $column ];
} else if ( $column == 'is_partner_show' ) {
$arrVals [] = ( int ) $house [ $column ];
} else if ( $column == 'security' ) {
$arrVals [] = ( int ) $house [ $column ];
} else if ( $column == 'sports_ground' ) {
$arrVals [] = ( int ) $house [ $column ];
} else if ( $column == 'play_ground' ) {
$arrVals [] = ( int ) $house [ $column ];
} else if ( $column == 'school' ) {
$arrVals [] = ( int ) $house [ $column ];
} else if ( $column == 'kinder_garten' ) {
$arrVals [] = ( int ) $house [ $column ];
} else if ( $column == 'fenced_area' ) {
$arrVals [] = ( int ) $house [ $column ];
} else {
$arrVals [] = " ' " . $house [ $column ] . " ' " ;
}
} else if ( isset ( $house [ $column ]) && filter_var ( $house [ $column ], FILTER_VALIDATE_BOOLEAN )) {
$arrVals [] = $house [ $column ] == 'true' ? 1 : 0 ;
} else if ( isset ( $house [ $column ]) && is_string ( $house [ $column ])) {
$arrVals [] = " ' $house[$column] ' " ;
}
}
}
if ( $house [ 'id' ] > 0 ) {
$sql = " UPDATE `complex_houses` SET " ;
$updatePairs = array ();
foreach ( $arrKeys as $index => $key ) {
$updatePairs [] = " ` $key ` = " . $arrVals [ $index ];
}
$sql .= implode ( ',' , $updatePairs );
$sql .= " WHERE id = { $house [ 'id' ] } " ;
if ( $this -> db -> query ( $sql )) {
// Сохраняем связи с программами рассрочек
if ( is_array ( $house [ 'installments' ])) {
$house_id = ( int ) $house [ 'id' ];
( new Installments ()) -> updateHouseInstallments ( $house_id , $house [ 'installments' ]);
}
$result = array ( 'id' => $house [ 'id' ]);
} else {
$result = array ( 'error' => $this -> db -> error ());
}
return $result ;
} else {
$sql = " INSERT INTO `complex_houses` ( " . implode ( ',' , $arrKeys ) . " ) VALUES ( " . implode ( ',' , $arrVals ) . " ) " ;
// echo $sql;
if ( $this -> db -> query ( $sql )) {
$id = $this -> db -> insert_id ();
// Сохраняем связи с программами рассрочек
if ( is_array ( $house [ 'installments' ])) {
$house_id = $house [ 'id' ] > 0 ? ( int ) $house [ 'id' ] : $id ;
( new Installments ()) -> updateHouseInstallments ( $house_id , $house [ 'installments' ]);
}
$result = array ( 'id' => $id );
} else {
$result = array ( 'error' => $this -> db -> error ());
}
return $result ;
}
}
/**
* Очериди комплекса
* @ param int complex_id
*/
public function get_corpuses ( $complex_id )
{
$result = array ();
$sql = " SELECT * FROM complex_corpuses WHERE complex_id = { $complex_id } " ;
$q = $this -> db -> query ( $sql );
while ( $corpus = $this -> db -> fetch_assoc ( $q )) {
$corpus [ 'deadline' ] = Date :: getFormatedEndingPeriod ( $corpus [ 'deadline' ]);
$result [] = $corpus ;
}
return $result ;
}
/**
*
*/
private function showAds ( $obj )
{
$showAds = true ;
if (( in_array ( $_SESSION [ 'agency_id' ], array ( 8353 , 8375 , 8376 , 8399 , 8867 , 8910 , 9082 , 9072 , 9077 , 9110 , 9588 , 9805 , 9973 , 7864 , 10203 , 10041 , 10493 , 4873 , 10876 , 10982 , 11086 , 10933 , 11456 , 11501 , 11397 , 7507 , 8826 ))) && ! in_array ( $_SESSION [ 'id' ], array ( 8373 , 8353 , 8375 , 8376 , 8399 , 8867 , 8910 , 9082 , 9072 , 9077 , 9110 , 9588 , 9805 , 9973 , 7864 , 10203 , 10041 , 10493 , 4873 , 10876 , 10982 , 11086 , 10933 , 11456 , 11501 , 11397 , 7507 , 8826 ))) {
$showAds = false ;
}
if ( $showAds && $obj [ 'archive' ])
$showAds = false ;
/* if ( $post [ 'selected' ] == " potential " || $post [ 'selected' ] == " favor " )
$showAds = false ; */
if ( $_SESSION [ 'agency_id' ] == 8435 && ( ! in_array ( $_SESSION [ 'id' ], array ( 8435 , 8532 , 8541 , 8555 ))))
$showAds = false ;
if ( $_SESSION [ 'agency_id' ] == 8649 && ( ! in_array ( $_SESSION [ 'id' ], array ( 8649 , 8653 )))) {
$showAds = false ;
}
if ( $_SESSION [ 'agency_id' ] == 8867 && ( ! in_array ( $_SESSION [ 'id' ], array ( 8867 , 8910 , 9082 , 9072 , 9077 )))) {
$showAds = false ;
}
if ( $_SESSION [ 'id' ] == 9170 ) {
$showAds = true ;
}
if ( $_SESSION [ 'id' ] == 9588 || $_SESSION [ 'id' ] == 9904 ) {
$showAds = true ;
}
if ( $_SESSION [ 'id' ] == 9110 || $_SESSION [ 'id' ] == 9892 ) {
$showAds = true ;
}
if ( $_SESSION [ 'id' ] == 9805 || $_SESSION [ 'id' ] == 9927 ) {
$showAds = true ;
}
if ( $_SESSION [ 'id' ] == 9973 ) {
$showAds = true ;
}
if ( $_SESSION [ 'id' ] == 10203 ) {
$showAds = true ;
}
if ( $_SESSION [ 'id' ] == 10041 ) {
$showAds = true ;
}
if ( $_SESSION [ 'id' ] == 7864 || $_SESSION [ 'id' ] == 8118 || $_SESSION [ 'id' ] == 7866 || $_SESSION [ 'id' ] == 8432 || $_SESSION [ 'id' ] == 9152 || $_SESSION [ 'id' ] == 9426 ) {
$showAds = true ;
}
if ( $_SESSION [ 'id' ] == 10493 || $_SESSION [ 'id' ] == 10606 ) {
$showAds = true ;
}
if ( $_SESSION [ 'id' ] == 4873 ) {
$showAds = true ;
}
if ( $_SESSION [ 'id' ] == 10876 ) {
$showAds = true ;
}
if ( $_SESSION [ 'id' ] == 10982 || $_SESSION [ 'id' ] == 10992 || $_SESSION [ 'id' ] == 11299 ) {
$showAds = true ;
}
if ( $_SESSION [ 'id' ] == 11086 ) {
$showAds = true ;
}
if ( $_SESSION [ 'id' ] == 10933 || $_SESSION [ 'id' ] == 11547 || $_SESSION [ 'id' ] == 11538 ) {
$showAds = true ;
}
if ( $_SESSION [ 'id' ] == 11456 || $_SESSION [ 'id' ] == 11552 ) {
$showAds = true ;
}
if ( $_SESSION [ 'id' ] == 11501 || $_SESSION [ 'id' ] == 11549 ) {
$showAds = true ;
}
if ( $_SESSION [ 'id' ] == 11397 || $_SESSION [ 'id' ] == 11583 ) {
$showAds = true ;
}
if ( in_array (( int ) $_SESSION [ 'id' ], [ 11378 , 11688 , 11690 , 11691 , 11694 , 11696 , 11698 , 11700 , 11702 , 11864 , 11865 , 11868 , 11873 , 8829 , 11799 , 11801 , 11803 , 11806 , 11808 , 11810 , 11812 , 11814 , 11816 , 11818 , 11819 , 11821 , 11822 , 11824 , 11825 , 11827 , 11830 , 11831 , 11833 , 11835 , 11850 , 11837 , 11839 , 11840 , 11841 , 11843 , 11845 , 11847 , 11849 , 11851 , 11854 , 11856 , 11859 , 11861 , 11683 , 11877 , 11879 , 11880 , 11882 , 11705 , 11709 , 11711 , 11713 , 11715 , 11720 , 11722 , 11723 , 11725 , 11726 , 11728 , 11731 , 11733 , 11735 , 11737 , 11739 , 11741 , 11743 , 11745 , 11747 , 11749 , 11753 , 11763 , 11765 , 11769 , 11770 , 11771 , 11772 , 11773 , 11774 , 11775 , 11776 , 11777 , 11779 , 11781 , 11784 , 11786 , 11788 , 11791 , 11793 , 11795 , 11796 , 11797 , 11798 , 11800 , 11802 , 11804 , 11807 , 11809 , 11811 , 11813 , 11815 , 11817 , 11820 , 11823 , 11826 , 11828 , 11829 , 11832 , 11834 , 11836 , 11838 , 11842 , 11844 , 11846 , 11848 , 11852 , 11853 , 11855 , 11857 , 11858 , 11860 , 11862 , 11863 , 11866 , 11869 , 11871 , 11872 , 11875 , 11876 , 11878 , 11881 , 11703 , 11704 , 11706 , 11708 , 11710 , 11712 , 11714 , 11716 , 11717 , 11718 , 11719 , 11721 , 11724 , 11727 , 11729 , 11730 , 11732 , 11734 , 11736 , 11738 , 11740 , 11742 , 11744 , 11746 , 11748 , 11750 , 11751 , 11752 , 11754 , 11755 , 11756 , 11757 , 11758 , 11759 , 11760 , 11761 , 11762 , 11764 , 11766 , 11767 , 11768 , 11778 , 11780 , 11782 , 11783 , 11785 , 11787 , 11789 , 11790 , 11792 , 11794 , 11883 , 11884 , 11885 , 11886 , 11887 , 11888 , 11889 , 11890 , 11891 , 11892 , 11893 , 11894 , 11895 , 11679 , 11680 , 11681 , 11682 , 11684 , 11685 , 11686 , 11687 , 11689 , 11692 , 11693 , 11695 , 11697 , 11699 , 11701 , 11896 , 11897 , 11898 , 11899 , 11900 , 11901 , 11902 , 11903 , 11904 , 11905 , 11906 ])) {
$showAds = false ;
}
if ( in_array (( int ) $_SESSION [ 'id' ], [ 8826 , 8827 , 11867 , 11870 , 11874 ])) {
$showAds = true ;
}
if ( in_array (( int ) $_SESSION [ 'id' ], [ 7507 , 7719 , 7513 , 8787 , 9878 , 10483 , 10815 , 7514 , 7516 , 7517 , 7518 , 7519 , 7614 , 7762 , 8364 , 10484 , 9047 , 9928 , 10386 , 10522 , 10530 , 10531 , 7548 , 7931 , 8893 , 9048 , 9809 , 11039 , 11805 , 10589 , 11329 , 11516 , 9770 , 10338 , 7905 , 8569 , 11641 , 11707 , 7520 , 7540 , 7541 , 7826 , 8729 , 8737 , 9861 , 10156 , 11034 , 7508 , 7509 , 7510 , 7512 , 7515 , 7543 , 7553 , 10499 ])) // А Н О О О МИДОМ
$showAds = false ;
if ( in_array (( int ) $_SESSION [ 'id' ], [ 7507 , 7509 , 7543 , 7905 , 8364 , 11707 ]))
$showAds = true ;
return $showAds ;
}
private function object_details ( $obj )
{
global $SROK_ARENDY ;
global $etaz_first_types ;
// var_dump($hasAutoSearchLayout);
$obj [ 'price' ] = number_format ( $obj [ 'stoim' ], 0 , ',' , ' ' );
$sql_nb_info = " SELECT id, nb_end_date, zipal_new_flat_decoration_type_id FROM object_nb_info WHERE object_id = { $obj [ 'id' ] } " ;
$info_obj = $this -> db -> fetch_assoc ( $this -> db -> query ( $sql_nb_info ));
$obj [ 'nb_end_date' ] = Date :: getFormatedEndingPeriod ( $info_obj [ 'nb_end_date' ]);
$obj [ 'decaration' ] = " " ;
if ( isset ( $this -> listDecorations [ 'list' ][ $info_obj [ 'zipal_new_flat_decoration_type_id' ]])) {
$obj [ 'decaration' ] = $this -> listDecorations [ 'list' ][ $info_obj [ 'zipal_new_flat_decoration_type_id' ]];
}
$obj [ 'plan' ] = '' ;
$sqlP = " SELECT * FROM objects_plan WHERE object_id = { $obj [ 'id' ] } " ;
$rez_plan = $this -> db -> query ( $sqlP );
if ( $this -> db -> num_rows ( $rez_plan ) > 0 ) {
$obj_plan = $this -> db -> fetch_assoc ( $rez_plan );
if ( $obj_plan [ 'img_plan' ] != '' ) {
if ( stripos ( $obj_plan [ 'img_plan' ], " http:// " ) === false && stripos ( $obj_plan [ 'img_plan' ], " https:// " ) === false ) {
$obj_plan [ 'img_plan' ] = " /photos/ " . $obj_plan [ 'img_plan' ];
}
$obj [ 'plan' ] = $obj_plan [ 'img_plan' ];
}
}
$obj [ 'photos' ] = array ();
$sqlPhotoInfo = " SELECT oop.sort_order, p.photo FROM objects_object_photo oop, object_photo p WHERE p.id = oop.object_photo_id AND oop.object_id = { $obj [ 'id' ] } ORDER BY oop.sort_order " ;
$rezPhotoInfo = $this -> db -> query ( $sqlPhotoInfo );
if ( $this -> db -> num_rows ( $rezPhotoInfo ) > 0 ) {
while ( $photoInfo = $this -> db -> fetch_assoc ( $rezPhotoInfo )) {
if ( stripos ( $photoInfo [ 'photo' ], " http:// " ) === false && stripos ( $photoInfo [ 'photo' ], " https:// " ) === false ) {
$obj [ 'photos' ][] = '/photos/' . $photoInfo [ 'photo' ];
} else {
$obj [ 'photos' ][] = $photoInfo [ 'photo' ];
}
}
}
//Доп обработка
if ( ! $obj [ 'etazh' ]) {
$obj [ 'etazh' ] = Filter :: getFloorFromName ( $obj [ 'nazv' ], true );
} else {
Filter :: getFloorFromName ( $obj [ 'nazv' ], true );
}
if ( ! $obj [ 'etazh_iz' ]) {
$obj [ 'etazh_iz' ] = Filter :: getMaxFloorFromName ( $obj [ 'nazv' ], true );
} else {
Filter :: getMaxFloorFromName ( $obj [ 'nazv' ], true );
}
Filter :: getSpaceFromName ( $obj [ 'nazv' ], true );
$obj [ 'nazv' ] = Filter :: name ( $obj [ 'nazv' ]);
$obj [ 'sobstv' ] = Filter :: replaceSobstv ( $obj [ 'sobstv' ]);
$obj [ 'opis' ] = cleanHtml ( $obj [ 'opis' ], '<p><br><strong><em><ul><ol><li>' );
if ( $obj [ 'stoim_prim' ] == 0 ) {
$obj [ 'stoim_prim' ] = '' ;
}
//$canEdit = false;
$date_add_temp = explode ( " " , date ( " d.m.Y H:i " , strtotime ( $obj [ 'date_add' ])));
if ( isset ( $obj [ 'date' ])) $date_add_temp = explode ( " " , date ( " d.m.Y H:i " , strtotime ( $obj [ 'date' ])));
list ( $dateAdd , $timeAdd ) = $date_add_temp ;
list ( $d , $m , $y ) = explode ( " . " , $dateAdd );
$date_add = $d . " " . getRusMonth ( $m ) . " " . $y ;
$date = $date_add . " " . $timeAdd ;
$obj [ 'date' ] = $date ;
if ( $obj [ 'operation_type' ] == 0 ) {
$obj [ 'SROK_AREND' ] = " Сдается " . $SROK_ARENDY [ $obj [ 'srok' ]];
if ( ! empty ( $obj [ 'prim_srok' ])) {
$obj [ 'SROK_AREND' ] .= " ( " . $obj [ 'prim_srok' ] . " ) " ;
}
}
$canDeleteOwn = false ;
if ( ! empty ( $this -> user )) {
if ( $this -> user -> agencyId == 8307 ) {
$canDeleteOwn = false ;
if ( $_SESSION [ 'id' ] == 8307 ) {
$canDeleteOwn = true ;
}
} else {
if ( $_SESSION [ 'id' ] == 10499 ) {
$canDeleteOwn = false ;
} else {
if ( $this -> user -> agency == 1 || $this -> user -> users_admin == 1 ) {
$canDeleteOwn = true ;
}
}
}
}
$obj [ 'canDeleteOwn' ] = $canDeleteOwn ;
$filesTotal = 0 ;
$sql_f = " SELECT * FROM clients_files WHERE object_id = { $obj [ 'id' ] } AND event_id > 0 " ;
$q_f = $this -> db -> query ( $sql_f );
$filesTotal += $this -> db -> num_rows ( $q_f );
$obj [ 'filesTotal' ] = $filesTotal ;
//$obj['hasAutoSearchLayout'] = $hasAutoSearchLayout;
$mtr = array ();
$sql = " SELECT metro.metro FROM metro, sp_metro WHERE sp_metro.id_metro = metro.id AND sp_metro.id_obj = { $obj [ 'id' ] } " ;
$result = $this -> db -> query ( $sql );
while ( $m = $this -> db -> fetch_row ( $result )) {
$mtr [] = $m [ 0 ];
}
if ( ! empty ( $obj [ 'rayon' ])) {
$obj [ 'rayon' ] = str_replace ([ ' район' , 'район' , ' р -н' , 'р -н' ], '' , $obj [ 'rayon' ]) . ' район' ;
}
$obj [ 'mtr' ] = $mtr ;
$objCoordinates = [];
$obj [ 'address' ] = '' ;
if ( isset ( $objCoordinatesArray )) {
foreach ( $objCoordinatesArray as $objCoords ) {
if ( $objCoords [ 'object_id' ] == $obj [ 'id' ]) {
$objCoordinates = $objCoords ;
break ;
}
}
} else {
$sql_coordinates = " SELECT address FROM object_location WHERE object_id= " . $obj [ 'id' ];
$rezCoordinates = $this -> db -> query ( $sql_coordinates );
if ( $this -> db -> num_rows ( $rezCoordinates ) > 0 ) {
$objCoordinates = $this -> db -> fetch_assoc ( $rezCoordinates );
}
}
if ( $objCoordinates && isset ( $objCoordinates [ 'address' ])) {
$obj [ 'address' ] = $objCoordinates [ 'address' ];
} else {
$obj [ 'address' ] = $obj [ 'adres' ];
if ( $obj [ 'dom' ]) {
$obj [ 'address' ] .= " , " . $obj [ 'dom' ];
}
if ( $obj [ 'korpus' ]) {
$obj [ 'address' ] .= " , корпус " . $obj [ 'korpus' ];
}
if ( $obj [ 'litera' ]) {
$obj [ 'address' ] .= " , литера " . $obj [ 'litera' ];
}
}
if (( int ) $obj [ 'etazh' ] > 0 ) {
if (( int ) $obj [ 'etazh' ] == 1 && ! empty ( $obj [ 'etaz_first_type' ])) {
$obj [ 'etazh' ] = $etaz_first_types [ $obj [ 'etaz_first_type' ]];
} else {
$obj [ 'etazh' ] = $obj [ 'etazh' ] . ' этаж' ;
}
}
$objClientsArrayCurrent = [];
$clients_count = 0 ;
if ( isset ( $objClientsArray )) {
foreach ( $objClientsArray as $objClient ) {
if ( strpos ( $objClient [ " objects " ], $obj [ 'id' ]) !== false ) {
$clients_count ++ ;
$objClientsArrayCurrent [] = $objClient ;
}
}
} else {
$objClientsArray = [];
$clientObjIds = [];
$sql_cl_obj = " SELECT client_id FROM client_objects WHERE object_id = { $obj [ 'id' ] } " ;
$q_cl_obj = mysql_query ( $sql_cl_obj );
while ( $r_cl_obj = mysql_fetch_assoc ( $q_cl_obj )) {
$clientObjIds [] = $r_cl_obj [ 'client_id' ];
}
if ( ! empty ( $clientObjIds )) {
$sql_clients = " SELECT `id`, `fio`, `email`, `phone` FROM `clients` WHERE id in ( " . implode ( ',' , $clientObjIds ) . " ) " ;
$q_client = $this -> db -> query ( $sql_clients );
$clients_count = $this -> db -> num_rows ( $q_client );
if ( $clients_count > 0 ) {
while ( $objCl = $this -> db -> fetch_assoc ( $q_client )) {
$objClientsArrayCurrent [] = $objCl ;
}
}
}
}
$obj [ 'clientsArrayCurrent' ] = $objClientsArrayCurrent ;
$obj [ 'isPdf' ] = 0 ;
if ( in_array ( $obj [ 'id' ], $_SESSION [ 'to_send' ])) {
$obj [ 'isPdf' ] = 1 ;
}
$obj [ 'isVK' ] = 0 ;
if ( $this -> user -> agencyId != 5530 || $this -> user -> agencyId == 5530 ) {
if ( ! empty ( $this -> user -> vk_token )) {
$obj [ 'isVK' ] = 1 ;
}
}
$notes_bd_usl = ' true' ;
$sql_count_notes = " SELECT COUNT(*) FROM object_notes WHERE object_id = $obj[id] AND $notes_bd_usl " ;
$obj [ 'notes' ] = $this -> db -> result ( $this -> db -> query ( $sql_count_notes ), 0 );
$requestsCount = 0 ;
if ( $this -> objRequisitionsArray ) {
foreach ( $this -> objRequisitionsArray as $objRequisition ) {
if ( $objRequisition [ " object_id " ] == $obj [ " id " ]) {
$requestsCount = $objRequisition [ " cnt " ];
break ;
}
}
} else {
$sqlRequest = " SELECT id FROM requisitions WHERE type_id=4 and object_id = $obj[id] and cancel=0 " ;
$qRequest = $this -> db -> query ( $sqlRequest );
$requestsCount = $this -> db -> num_rows ( $qRequest );
}
if ( $this -> objPricesArray ) {
foreach ( $this -> objPricesArray as $objPrice ) {
if ( $objPrice [ " object_id " ] == $obj [ " id " ]) {
if ( ! is_null ( $objPrice [ 'prep_price' ])) {
$obj [ 'prep_price' ] = $objPrice [ 'prep_price' ];
}
if ( ! is_null ( $objPrice [ 'start_price' ])) {
$obj [ 'start_price' ] = $objPrice [ 'start_price' ];
}
if ( ! is_null ( $objPrice [ 'fact_price' ])) {
$obj [ 'fact_price' ] = $objPrice [ 'fact_price' ];
}
break ;
}
}
}
$obj [ 'requestsCount' ] = $requestsCount ;
$obj [ 'showAds' ] = $this -> showAds ( $obj );
$obj [ 'stoim_format' ] = number_format ( $obj [ 'stoim' ], 0 , ',' , ' ' );
if ( ! isset ( $obj [ 'prep_price' ]))
$obj [ 'prep_price' ] = 0 ;
if ( ! isset ( $obj [ 'start_price' ]))
$obj [ 'start_price' ] = 0 ;
if ( ! isset ( $obj [ 'fact_price' ]))
$obj [ 'fact_price' ] = 0 ;
//if(isset())
$obj [ 'prep_price' ] = number_format ( $obj [ 'prep_price' ], 0 , ',' , ' ' );
$obj [ 'start_price' ] = number_format ( $obj [ 'start_price' ], 0 , ',' , ' ' );
$obj [ 'fact_price' ] = number_format ( $obj [ 'fact_price' ], 0 , ',' , ' ' );
$obj [ 'objPriceHistory' ] = array ();
$sqlPriceHistory = " SELECT date_change_price, price, price_ku FROM objects_price_history WHERE object_id = { $obj [ 'id' ] } " ;
$rezPriceHistory = $this -> db -> query ( $sqlPriceHistory );
while ( $objPriceHistory = $this -> db -> fetch_assoc ( $rezPriceHistory )) {
$objPriceHistory [ 'price' ] = number_format ( $objPriceHistory [ 'price' ], 0 , ',' , ' ' );
$objPriceHistory [ 'date_change_price' ] = date ( 'd.m.Y' , strtotime ( $objPriceHistory [ 'date_change_price' ]));
$obj [ 'objPriceHistory' ][] = $objPriceHistory ;
}
$obj [ 'type_k' ] = " - " ;
if (( int ) $obj [ 'komnat' ] > 0 ) {
$obj [ 'type_k' ] = ( int ) $obj [ 'komnat' ] . " к.кв. " ;
if ( $obj [ 'studio_flag' ] > 0 ) {
$obj [ 'type_k' ] = " студия " ;
}
}
$result = $obj ;
return $result ;
}
/**
*
*/
public function set_filter ( $filter )
{
$this -> filter = $filter ;
}
/**
* Комплекс
* @ param int $complex_id
*/
public function get_complex_one ( $complex_id , $photo_visible = true , $objects_list = true , $object_info_id = 0 )
{
$this -> get_decarations ();
$this -> set_user ();
$sql = " SELECT * FROM complex_list WHERE id= { $complex_id } AND agency_id= { $this -> user -> agencyId } " ;
$q = $this -> db -> query ( $sql );
$complex = $this -> db -> fetch_assoc ( $q );
if ( ! $complex ) {
echo ( json_encode ([
'error' => 'Complex not Found'
]));
exit ;
}
$result [ 'images' ] = array ();
$result [ 'builder' ] = array ();
$result = array ();
$complex [ 'can_delete' ] = 0 ;
if ( $this -> user -> agency > 0 || $this -> user -> users_admin ) {
$complex [ 'can_delete' ] = 1 ;
}
$result = $complex ;
//С фотками
if ( $photo_visible ) {
$appendedFiles = array ();
$sql_images = " SELECT * FROM complex_images WHERE complex_id = { $complex_id } " ;
$q_images = $this -> db -> query ( $sql_images );
while ( $r_images = $this -> db -> fetch_assoc ( $q_images )) {
$result [ 'images' ][] = $r_images ;
$ph_url = $r_images [ 'image' ];
$name = $r_images [ 'image' ];
$pathInfo = pathinfo ( $name );
$appendedFiles [] = array (
" name " => $ph_url ,
" file " => $ph_url ,
" type " => " image/ " . $pathInfo [ 'extension' ],
" data " => array (
" url " => $ph_url ,
" thumbnail " => $ph_url
)
);
}
$result [ 'images_uploader' ] = $appendedFiles ;
}
$sql_builder = " SELECT * FROM builders WHERE id = { $complex [ 'builder_id' ] } " ;
if ( $complex [ 'builder_id' ] >= 10000 ) {
$sql_builder = " SELECT * FROM complex_builders WHERE id = { $complex [ 'builder_id' ] } " ;
}
$q_builder = $this -> db -> query ( $sql_builder );
if ( $this -> db -> num_rows ( $q_builder ) > 0 ) {
$logo = '' ;
$builder = $this -> db -> fetch_assoc ( $q_builder );
if ( ! empty ( $builder [ 'logo' ]) && file_exists ( $_SERVER [ 'DOCUMENT_ROOT' ] . '/photos/builder/' . $builder [ 'logo' ])) {
$logo = '/photos/builder/' . $builder [ 'logo' ];
}
$result [ 'builder' ] = array ( 'name' => $builder [ 'name' ], 'logo' => $logo );
} else {
$result [ 'builder' ] = array ( 'name' => '' , 'logo' => '' );
}
$sql_metro = " SELECT metro.id, metro.metro, m.metro_id, m.subway_time, m.subway_type FROM complex_metro as m
JOIN metro on metro . id = m . metro_id
WHERE m . complex_id = { $complex_id } " ;
$result [ 'metros' ] = [];
$mQuery = $this -> db -> query ( $sql_metro );
while ( $metro = $this -> db -> fetch_assoc ( $mQuery )) {
$result [ 'metros' ][] = $metro ;
}
$result [ 'dop' ] = array ( 'domclick_id' => null );
$sql_dop = " SELECT * FROM complex_dop WHERE complex_id= { $complex_id } " ;
$dop = $this -> db -> fetch_assoc ( $this -> db -> query ( $sql_dop ));
if ( $dop ) {
$result [ 'dop' ] = $dop ;
if ( $result [ 'dop' ][ 'domclick_id' ] == 0 ) $result [ 'dop' ][ 'domclick_id' ] = null ;
if ( ! empty ( $result [ 'dop' ][ 'workdays_op' ])) $result [ 'dop' ][ 'workdays_op' ] = json_decode ( $result [ 'dop' ][ 'workdays_op' ], true );
$result [ 'dop' ][ 'UTP' ] = array ();
$result [ 'dop' ][ 'UTP2' ] = array ();
$sql_dop_utp = " SELECT * FROM complex_UTP WHERE complex_id = { $complex_id } " ;
$q_dop_utp = $this -> db -> query ( $sql_dop_utp );
while ( $r_dop_utp = $this -> db -> fetch_assoc ( $q_dop_utp )) {
$otpImages = [];
if ( ! empty ( $r_dop_utp [ 'photos' ])) {
// echo $r_dop_utp['photos'];
$otpImages = json_decode ( $r_dop_utp [ 'photos' ], true );
}
if ( $r_dop_utp [ 'type' ] == 'main' ) {
$result [ 'dop' ][ 'UTP' ][] = array ( 'title' => $r_dop_utp [ 'title' ], 'desc' => $r_dop_utp [ 'desck' ], 'isDiv' => true , 'isEdit' => false , 'images' => $otpImages , 'imagesUTP' => $otpImages , 'isInput' => false );
} else if ( $r_dop_utp [ 'type' ] == 'secondary' ) {
$result [ 'dop' ][ 'UTP2' ][] = array ( 'title' => $r_dop_utp [ 'title' ], 'desc' => $r_dop_utp [ 'desck' ], 'isDiv' => true , 'isEdit' => false , 'images' => $otpImages , 'imagesUTP' => $otpImages , 'isInput' => false );
}
}
}
$result [ 'actions' ] = [];
$sql_action = " SELECT * FROM complex_actions WHERE complex_id = { $complex_id } " ;
$q_action = $this -> db -> query ( $sql_action );
while ( $r_action = $this -> db -> fetch_assoc ( $q_action )) {
$result [ 'actions' ][] = $r_action ;
}
$sql_address = " SELECT * FROM complex_address WHERE complex_id= { $complex_id } " ;
$q_address = $this -> db -> query ( $sql_address );
$result [ 'address' ] = $this -> db -> fetch_assoc ( $q_address );
$decoration = '' ;
$decoration_res = $this -> db -> fetch_assoc ( $this -> db -> query ( " SELECT name FROM decoration_types WHERE id= { $complex [ 'decoration_id' ] } " ));
if ( isset ( $decoration_res [ 'name' ])) {
$decoration = $decoration_res [ 'name' ];
}
$result [ 'decoration' ] = $decoration ;
//Тип дома
$house_types = '' ;
if ( $complex [ 'house_type' ] > 0 ) {
$house_types_res = $this -> db -> fetch_assoc ( $this -> db -> query ( " SELECT name FROM house_material WHERE id= { $complex [ 'house_type' ] } " ));
if ( isset ( $house_types_res [ 'name' ])) {
$house_types = $house_types_res [ 'name' ];
}
}
$result [ 'house_type_name' ] = $house_types ;
$house_material = '' ;
if ( $complex [ 'house_material' ] > 0 ) {
$house_material_res = $this -> db -> fetch_assoc ( $this -> db -> query ( " SELECT name FROM house_material WHERE id= { $complex [ 'house_material' ] } " ));
if ( isset ( $house_material_res [ 'name' ])) {
$house_material = $house_material_res [ 'name' ];
}
}
$result [ 'house_material_name' ] = $house_material ;
$result [ 'infrastructure' ] = array ();
$infrastructure = $this -> db -> fetch_assoc ( $this -> db -> query ( " SELECT * FROM complex_infrastructure WHERE complex_id = { $complex [ 'id' ] } " ));
$result [ 'infrastructure' ] = $infrastructure ;
$result [ 'corpuses' ] = $this -> get_corpuses ( $complex_id );
$result [ 'lines_info' ] = array ();
/* $block [ 'lines' ][( int ) $building [ 'line' ]][ 'corpuses' ][] = array ( 'corpus' => $building [ 'corp' ],
'period' => Date :: getFormatedEndingPeriod ( $building [ 'deadline' ]),
'deadline' => date ( 'd.m.Y' , strtotime ( $building [ 'deadline' ])),
'isDiv' => true ,
'isEdit' => false ,
'date' => '' ,
); */
foreach ( $result [ 'corpuses' ] as $corpus ) {
// var_dump($corpus);
if ( ! isset ( $result [ 'lines_info' ][ $corpus [ 'line' ]])) $result [ 'lines_info' ][ $corpus [ 'line' ]] = array ();
$result [ 'lines_info' ][ $corpus [ 'line' ]][ 'corpuses' ][] = array (
'id' => $corpus [ 'id' ],
'corpus' => $corpus [ 'corpus' ],
'period' => $corpus [ 'deadline' ],
'deadline' => date ( 'd.m.Y' , $corpus [ 'period' ]),
'isDiv' => true ,
'isEdit' => false ,
'date' => '' ,
'corpus_id' => $corpus [ 'corpus_id' ],
'corpus_floors' => $corpus [ 'corpus_floors' ],
'corpus_floors_ready' => $corpus [ 'corpus_floors_ready' ],
'corpus_fz_214' => $corpus [ 'corpus_fz_214' ],
'corpus_status' => $corpus [ 'corpus_status' ],
'del' => 0
);
}
// var_dump($result['lines']);
$result [ 'use_in_advert' ] = 0 ;
$result [ 'add_to_bn_feed' ] = 0 ;
$result [ 'add_to_yandex_feed' ] = 0 ;
$result [ 'add_to_domclick_feed' ] = 0 ;
$result [ 'add_to_avito_feed' ] = 0 ;
$result [ 'add_to_emls_feed' ] = 0 ;
$result [ 'add_to_cian_feed' ] = 0 ;
$result [ 'add_to_zipal' ] = 0 ;
$sql_advert = " SELECT * FROM complex_advert WHERE complex_id = { $complex_id } " ;
$q_advert = $this -> db -> query ( $sql_advert );
if ( $this -> db -> num_rows ( $q_advert ) > 0 ) {
$r_advert = $this -> db -> fetch_assoc ( $q_advert );
$result [ 'use_in_advert' ] = ( int ) $r_advert [ 'use_in_advert' ];
$result [ 'add_to_bn_feed' ] = ( int ) $r_advert [ 'add_to_bn_feed' ];
$result [ 'add_to_yandex_feed' ] = ( int ) $r_advert [ 'add_to_yandex_feed' ];
$result [ 'add_to_domclick_feed' ] = ( int ) $r_advert [ 'add_to_domclick_feed' ];
$result [ 'add_to_avito_feed' ] = ( int ) $r_advert [ 'add_to_avito_feed' ];
$result [ 'add_to_emls_feed' ] = ( int ) $r_advert [ 'add_to_emls_feed' ];
$result [ 'add_to_cian_feed' ] = ( int ) $r_advert [ 'add_to_cian_feed' ];
$result [ 'add_to_zipal' ] = ( int ) $r_advert [ 'add_to_zipal' ];
}
$this -> set_sphinx2 ();
$result [ 'objects_total' ] = 0 ;
$sql_obj_total = " SELECT id FROM objects WHERE archive=0 and complex_id = { $complex_id } LIMIT 1000000 OPTION max_matches=1000000 " ;
$q_obj_total = $this -> sphinx2 -> query ( $sql_obj_total );
$result [ 'objects_total' ] = $this -> sphinx2 -> num_rows ( $q_obj_total );
/* $sql_obj_total = " SELECT count(*) as total FROM complex_objects WHERE complex_id = { $complex_id } " ;
$q_obj_total = $this -> db -> query ( $sql_obj_total );
$result [ 'objects_total' ] = $this -> db -> result ( $q_obj_total ); */
//Инфа по заданному объекту
if ( $object_info_id > 0 ) {
$sql_object = " SELECT * FROM complex_objects WHERE object_id = { $object_info_id } " ;
$q_object = $this -> db -> query ( $sql_object );
if ( $this -> db -> num_rows ( $q_object ) > 0 ) {
$compl_obj = $this -> db -> fetch_assoc ( $q_object );
$result [ 'corpus_id_object' ] = $compl_obj [ 'corpus_id' ];
} else {
$result [ 'corpus_id_object' ] = 0 ;
}
}
//С объектами
if ( $objects_list ) {
$result [ 'objects' ] = array ();
$obj_ids = array ();
$objLines = array ();
$objCorpuses = array ();
$whereObjects = '' ;
if ( ! empty ( $this -> filter )) {
//Фильтр
if ( ! empty ( $this -> filter -> metros )) {
$whereObjects .= " AND id_metro in ( " . implode ( ',' , $this -> filter -> metros ) . " ) " ;
}
if ( ! empty ( $this -> filter -> period )) {
$whereObjects .= " AND nb_end_date <= { $this -> filter -> period } " ;
}
if ( ! empty ( $this -> filter -> sq_all_ot )) {
$whereObjects .= " AND ploshad >= { $this -> filter -> sq_all_ot } " ;
}
if ( ! empty ( $this -> filter -> sq_all_do )) {
$whereObjects .= " AND ploshad <= { $this -> filter -> sq_all_do } " ;
}
if ( ! empty ( $this -> filter -> flat_floor_ot )) {
$whereObjects .= " AND etazh >= { $this -> filter -> flat_floor_ot } " ;
}
if ( ! empty ( $this -> filter -> flat_floor_do )) {
$whereObjects .= " AND etazh <= { $this -> filter -> flat_floor_do } " ;
}
if ( ! empty ( $this -> filter -> stoim_ot )) {
$whereObjects .= " AND stoim >= { $this -> filter -> stoim_ot } " ;
}
if ( ! empty ( $this -> filter -> stoim_do )) {
$whereObjects .= " AND stoim <= { $this -> filter -> stoim_do } " ;
}
if ( ! empty ( $this -> filter -> types_room )) {
$types_room = array ();
$sql = " SELECT * FROM room_types where id in ( " . implode ( ',' , $this -> filter -> types_room ) . " ) " ;
$rez = $this -> db -> query ( $sql );
while ( $type_room = $this -> db -> fetch_assoc ( $rez )) {
$types_room [] = ( int ) $type_room [ 'name' ];
}
$whereObjects .= " AND komnat in ( " . implode ( ',' , $types_room ) . " ) " ;
}
if ( ! empty ( $this -> filter -> decaration_types )) {
$objDIds = array ();
$sql_d = " SELECT id, object_id FROM object_nb_info WHERE zipal_new_flat_decoration_type_id in ( " . implode ( ',' , $this -> filter -> decaration_types ) . " ) " ;
$rez_d = $this -> db -> query ( $sql_d );
while ( $r_d = $this -> db -> fetch_assoc ( $rez_d )) {
$objDIds [] = ( int ) $r_d [ 'object_id' ];
}
if ( ! empty ( $objDIds )) {
$whereObjects .= " AND id in ( " . implode ( ',' , $objDIds ) . " ) " ;
} else {
$whereObjects .= " AND id in (0) " ;
}
}
}
$this -> set_users_ids ();
/* if ( ! empty ( $whereObjects )){
$complexObjIds = array ();
$this -> set_sphinx2 ();
//$sql_obj = "SELECT id FROM objects WHERE archive=0 and complex_id = {$complex_id} and id_add_user in (".implode(',', $this->userIds).") {$whereObjects} LIMIT 1000000 OPTION max_matches=1000000";
echo $sql_obj ;
$q_obj = $this -> sphinx2 -> query ( $sql_obj , true );
while ( $r_obj = $this -> sphinx2 -> fetch_assoc ( $q_obj )){
$complexObjIds [] = ( int ) $r_obj [ 'id' ];
}
} */
$obj_ids = array ();
$objects = array ();
$limitSqlObj = " limit 10 " ;
if ( $_SESSION [ 'id' ] == 5238 ) {
$this -> limit = 2 ;
}
if ( $this -> page_obj > 0 ) {
$limitSqlObj = ' limit ' . ( $this -> page_obj - 1 ) * $this -> limit . ', ' . $this -> limit ;
}
$sql_obj_total = " SELECT id FROM objects WHERE archive=0 and complex_id = { $complex_id } and id_add_user in ( " . implode ( ',' , $this -> userIds ) . " ) { $whereObjects } LIMIT 1000000 OPTION max_matches=1000000 " ;
$q_obj_total = $this -> sphinx2 -> query ( $sql_obj_total );
$result [ 'objects_total' ] = $this -> sphinx2 -> num_rows ( $q_obj_total );
$sql_obj = " SELECT * FROM objects WHERE archive=0 and complex_id = { $complex_id } and id_add_user in ( " . implode ( ',' , $this -> userIds ) . " ) { $whereObjects } order by date_add desc { $limitSqlObj } OPTION max_matches=1000000 " ;
// echo $sql_obj;
$q_obj = $this -> sphinx2 -> query ( $sql_obj , true );
while ( $r_obj = $this -> sphinx2 -> fetch_assoc ( $q_obj )) {
$objects [] = $r_obj ;
$obj_ids [] = ( int ) $r_obj [ 'id' ];
}
if ( ! empty ( $obj_ids )) {
$sql_complex_object = " SELECT * FROM complex_objects WHERE complex_id = { $complex_id } and object_id in ( " . implode ( " , " , $obj_ids ) . " ) " ;
//echo $sql_complex_object;
$q_complex_object = $this -> db -> query ( $sql_complex_object );
while ( $complex_obj = $this -> db -> fetch_assoc ( $q_complex_object )) {
//$obj_ids[] = $complex_obj['object_id'];
$objLines [ $complex_obj [ 'object_id' ]] = array ();
$objCorpuses [ $complex_obj [ 'object_id' ]] = array ();
if ( $complex_obj [ 'corpus_id' ] > 0 ) {
$sql_line = " SELECT * FROM complex_corpuses WHERE id = { $complex_obj [ 'corpus_id' ] } " ;
$q_line = $this -> db -> query ( $sql_line );
$r_line = $this -> db -> fetch_assoc ( $q_line );
$objLines [ $complex_obj [ 'object_id' ]] = $r_line ;
} else {
$objLines [ $complex_obj [ 'object_id' ]] = array ( 'line' => 1 , 'corpus' => 1 );
}
}
}
//var_dump($objLines);
$objAddInfoList = array ();
$objSaleInfoList = array ();
if ( ! empty ( $obj_ids )) {
//Доп инфа
$sqlAddInfo = " SELECT * FROM objects_additional_information WHERE object_id in ( " . implode ( " , " , $obj_ids ) . " ) " ;
$rezAddInfo = $this -> db -> query ( $sqlAddInfo );
while ( $objAddInfo = $this -> db -> fetch_assoc ( $rezAddInfo )) {
$objAddInfoList [ $objAddInfo [ 'object_id' ]] = $objAddInfo ;
}
//sale инфа
$sqlSaleInfo = " SELECT * FROM sale_objects WHERE object_id in ( " . implode ( " , " , $obj_ids ) . " ) " ;
$rezSaleInfo = $this -> db -> query ( $sqlSaleInfo );
while ( $objSaleInfo = $this -> db -> fetch_assoc ( $rezSaleInfo )) {
$objSaleInfoList [ $objSaleInfo [ 'object_id' ]] = $objSaleInfo ;
}
//начитываем кол-во заявок для объектов
$objRequisitionsArray = [];
$sqlRequisitions = " SELECT count(id) as cnt, object_id FROM requisitions WHERE (type_id = 4 or type_id in (SELECT id FROM requisitions_type WHERE heir = 4 AND agency_id = { $this -> user -> agencyId } )) AND cancel = 0 AND object_id in ( " . implode ( " , " , $obj_ids ) . " ) GROUP BY object_id " ;
$qRequisitions = $this -> db -> query ( $sqlRequisitions );
if ( $this -> db -> num_rows ( $qRequisitions ) > 0 ) {
while ( $objRequisitions = $this -> db -> fetch_assoc ( $qRequisitions )) {
$objRequisitionsArray [] = $objRequisitions ;
}
}
$this -> objRequisitionsArray = $objRequisitionsArray ;
$objPricesArray = [];
$sqlPrices = " SELECT * FROM `object_prices`
WHERE `object_id` in ( " . implode( " , " , $obj_ids ) . " ) AND `agency_id` = '{$this->user->agencyId}' " ;
if ( $queryPrices = $this -> db -> query ( $sqlPrices )) {
if ( $this -> db -> num_rows ( $queryPrices ) > 0 ) {
while ( $objPrice = $this -> db -> fetch_assoc ( $queryPrices )) {
$objPricesArray [] = $objPrice ;
}
}
}
$this -> objPricesArray = $objPricesArray ;
$objects1 = array ();
$sql_obj1 = " SELECT *, DATE_FORMAT(date_add,'%d.%m.%Y %H:%i') as date_add
FROM objects
WHERE id in ( " . implode( " , " , $obj_ids ) . " ) " ;
// echo $sql_obj;
$q_obj1 = $this -> db -> query ( $sql_obj1 );
while ( $r_obj1 = $this -> db -> fetch_assoc ( $q_obj1 )) {
$objects1 [ $r_obj1 [ 'id' ]] = $r_obj1 ;
}
//var_dump($objects1);
$result [ 'allPages' ] = ceil ( $result [ 'objects_total' ] / $this -> limit );
foreach ( $objects as $obj ) {
// var_dump($obj);
$obj [ 'line' ] = $objLines [ $obj [ 'id' ]][ 'line' ];
if ( isset ( $objAddInfoList [ $obj [ 'id' ]])) {
$obj [ 'flat_number' ] = $objAddInfoList [ $obj [ 'id' ]][ 'flat_number' ];
} else {
$obj [ 'flat_number' ] = " - " ;
}
$obj [ 'nazv' ] = $objects1 [ $obj [ 'id' ]][ 'nazv' ];
$obj [ 'opis' ] = $objects1 [ $obj [ 'id' ]][ 'opis' ];
$obj [ 'etazh' ] = $objects1 [ $obj [ 'id' ]][ 'etazh' ];
$obj [ 'ploshad' ] = $objects1 [ $obj [ 'id' ]][ 'ploshad' ];
$obj [ 'ploshad_komn' ] = $objects1 [ $obj [ 'id' ]][ 'ploshad_komn' ];
$obj [ 'ploshad_k' ] = $objects1 [ $obj [ 'id' ]][ 'ploshad_k' ];
$obj [ 'etazh_iz' ] = $objects1 [ $obj [ 'id' ]][ 'etazh_iz' ];
$obj [ 'sobstv' ] = $objects1 [ $obj [ 'id' ]][ 'sobstv' ];
$obj [ 'date_add' ] = $objects1 [ $obj [ 'id' ]][ 'date_add' ];
$obj [ 'korpus' ] = $objLines [ $obj [ 'id' ]][ 'corpus' ];
$obj [ 'stoim' ] = $objects1 [ $obj [ 'id' ]][ 'stoim' ];
// $obj['zipal_new_flat_decoration_type_id']
if ( isset ( $objSaleInfoList [ $obj [ 'id' ]])) {
$obj [ 'entrance_number' ] = $objSaleInfoList [ $obj [ 'id' ]][ 'entrance_number' ];
} else {
$obj [ 'entrance_number' ] = " - " ;
}
$result [ 'objects' ][ 'object_' . $obj [ 'id' ]] = $this -> object_details ( $obj );
}
}
}
return $result ;
}
public function getComplexNames ( $use_empty_rooms = false )
{
$result = array ();
$this -> set_user ();
$this -> set_users_ids ();
// $use_empty_rooms = true;
if ( $use_empty_rooms ) {
$query = $this -> db -> query ( " SELECT id, `name`
FROM complex_list
WHERE agency_id = { $this -> user -> agencyId }
AND complex_list . arhive = 0
AND complex_list . deleted = 0
" );
} else {
$query = $this -> db -> query ( " SELECT complex_list.id, complex_list.name FROM complex_list
LEFT JOIN complex_houses ON complex_houses . complex_id = complex_list . id
LEFT JOIN complex_metro ON complex_metro . complex_id = complex_list . id
LEFT JOIN complex_address ON complex_address . complex_id = complex_list . id
LEFT JOIN complex_entrances complex_entrances ON complex_entrances . complex_house_id = complex_houses . id
LEFT JOIN complex_floors complex_floors ON complex_floors . complex_entrance_id = complex_entrances . id
LEFT JOIN complex_rooms complex_rooms ON complex_rooms . floor_id = complex_floors . id
WHERE complex_list . agency_id = { $this -> user -> agencyId }
AND complex_list . arhive = 0
AND complex_list . deleted = 0
AND complex_houses . id IS NOT NULL AND complex_rooms . id IS NOT NULL
GROUP BY complex_list . id
HAVING COUNT ( complex_houses . id ) > 0 AND COUNT ( complex_rooms . id ) > 0
ORDER BY complex_list . id DESC
" );
}
// print_r($query);die;
while ( $row = $this -> db -> fetch_assoc ( $query )) {
$result [] = $row ;
}
// var_dump($result);die;
return $result ;
}
/**
* Поиск
*/
public function search ( $filter , $use_empty_rooms = false )
{
$whereComplex = '' ;
$whereRoom = '' ;
$whereAddress = '' ;
$whereHouse = '' ;
$whereFloor = '' ;
$priceFilterKey = ' complex_rooms.total_amount ' ;
$havingComplex = " " ;
if ( ! $use_empty_rooms ) {
$havingComplex .= " HAVING COUNT(complex_houses.id) > 0 AND COUNT(complex_rooms.id) > 0 " ;
$whereComplex .= " AND complex_houses.id IS NOT NULL AND complex_rooms.id IS NOT NULL " ;
// $whereHouse .= " AND COUNT(complex_rooms.id) > 0 ";
}
if ( $filter ) {
if ( ! empty ( $filter -> selectedDecorations )) {
$whereRoom .= " AND complex_rooms.decoration_id in ( " . implode ( ',' , $filter -> selectedDecorations ) . " ) " ;
}
if ( ! empty ( $filter -> selectedTypes )) {
$whereRoom .= " AND complex_rooms.type in (' " . implode ( '\',\'' , $filter -> selectedTypes ) . " ') " ;
}
if ( ! empty ( $filter -> rooms )) {
$isMoreThenFive = in_array ( '5-more' , $filter -> rooms );
$isSelectedStudio = in_array ( 'studio' , $filter -> rooms );
$filteredArray = array_filter ( $filter -> rooms , function ( $element ) {
return ! in_array ( $element , [ " 5-more " , " studio " ]);
});
if ( $isSelectedStudio ) {
$whereRoom .= " AND complex_rooms.layout_feature = 'studio' " ;
}
if ( count ( $filteredArray )) {
if ( $isMoreThenFive ) {
$whereRoom .= " AND (complex_rooms.rooms_count >= 5 OR complex_rooms.rooms_count IN ( " . implode ( ',' , $filteredArray ) . " )) " ;
} else {
$whereRoom .= " AND complex_rooms.rooms_count IN ( " . implode ( ',' , $filteredArray ) . " ) " ;
}
} else if ( $isMoreThenFive ) {
$whereRoom .= " AND complex_rooms.rooms_count >= 5 " ;
}
}
if ( ! empty ( $filter -> rayons )) {
$whereComplex .= " AND ( " ;
foreach ( $filter -> rayons as $index => $rayon ) {
$whereComplex .= " complex_address.rayon LIKE '% { $rayon } %' " ;
if ( isset ( $filter -> rayons [ $index + 1 ])) {
$whereComplex .= " OR " ;
}
}
$whereComplex .= " ) " ;
// var_dump($whereAddress);die;
}
if ( ! empty ( $filter -> selectedMetros )) {
$whereComplex .= " AND complex_metro.metro_id in ( " . implode ( ',' , $filter -> selectedMetros ) . " ) " ;
}
if ( ! empty ( $filter -> complexes )) {
$whereComplex .= " AND complex_list.id in ( " . implode ( ',' , $filter -> complexes ) . " ) " ;
}
if ( ! empty ( $filter -> address )) {
$whereComplex .= " AND complex_address.address like '% { $filter -> address } %' " ;
}
if ( ! empty ( $filter -> squareKitchen_min )) {
$whereRoom .= " AND complex_rooms.kitchen_area >= { $filter -> squareKitchen_min } " ;
}
if ( ! empty ( $filter -> squareKitchen_max )) {
$whereRoom .= " AND complex_rooms.kitchen_area <= { $filter -> squareKitchen_max } " ;
}
if ( ! empty ( $filter -> area_from )) {
$whereRoom .= " AND complex_rooms.area >= { $filter -> area_from } " ;
}
if ( ! empty ( $filter -> area_to )) {
$whereRoom .= " AND complex_rooms.area <= { $filter -> area_to } " ;
}
if ( filter_var ( $filter -> useSquarePrice , FILTER_VALIDATE_BOOLEAN )) {
$priceFilterKey = " complex_rooms.total_amount / complex_rooms.area " ;
}
if ( ! empty ( $filter -> price_from )) {
$whereRoom .= " AND { $priceFilterKey } >= { $filter -> price_from } " ;
}
if ( ! empty ( $filter -> price_to )) {
$whereRoom .= " AND { $priceFilterKey } <= { $filter -> price_to } " ;
}
if ( ! empty ( $filter -> floor_from )) {
$whereFloor .= " AND complex_floors.position >= { $filter -> floor_from } " ;
}
if ( ! empty ( $filter -> floor_to )) {
$whereFloor .= " AND complex_floors.position <= { $filter -> floor_to } " ;
}
if ( ! empty ( $filter -> selectedComplexTypes )) {
$whereComplex .= " AND complex_list.type in (' " . implode ( '\',\'' , $filter -> selectedComplexTypes ) . " ') " ;
}
if ( ! empty ( $filter -> period )) {
if ( $filter -> period == 'completed' ) {
$currentMonth = date ( 'n' );
$currentYear = date ( 'Y' );
$currentQuarter = ceil ( $currentMonth / 3 );
$whereHouse .= " AND complex_houses.deadline_quarter <= $currentQuarter AND complex_houses.deadline_year <= $currentYear " ;
} else {
list ( $year , $quarter ) = explode ( 'Q' , $filter -> period );
$whereHouse .= " AND complex_houses.deadline_quarter = $quarter AND complex_houses.deadline_year = $year " ;
}
}
if ( ! empty ( $filter -> is_partner_show )){
$whereHouse .= " AND complex_houses.is_partner_show = 1 " ;
}
if ( ! empty ( $filter -> is_archive )) {
$whereComplex .= " AND complex_list.arhive = 1 " ;
} else {
$whereComplex .= " AND complex_list.arhive = 0 " ;
}
// Фильтрация по способам оплаты
if ( ! empty ( $filter -> selectedPaymentTypes )) {
$conditions = [];
foreach ( $filter -> selectedPaymentTypes as $pt ) {
$conditions [] = " complex_rooms.payment_types LIKE '% \" { $pt } \" %' " ;
}
if ( ! empty ( $conditions )) {
$whereRoom .= " AND ( " . implode ( ' OR ' , $conditions ) . " ) " ;
}
// Installment-specific filtering
if ( in_array ( 'INSTALLMENT' , $filter -> selectedPaymentTypes )) {
$whereRoom .= " AND EXISTS (
SELECT 1
FROM complex_house_installments chi
JOIN complex_entrances ce ON ce . complex_house_id = chi . house_id
JOIN complex_floors cf ON cf . complex_entrance_id = ce . id
JOIN installments i ON i . id = chi . installment_id
WHERE cf . id = complex_rooms . floor_id
AND i . is_archive = 0 "
. ( ! empty ( $filter -> selectedInstallments )
? " AND chi.installment_id IN ( " . implode ( ',' , $filter -> selectedInstallments ) . " ) "
: " " )
. (( isset ( $filter -> initialPayment ) && is_numeric ( $filter -> initialPayment ))
? " AND complex_rooms.installment_price IS NOT NULL AND complex_rooms.installment_price > 0 AND ((i.initial_payment / 100.0) * complex_rooms.installment_price) <= " . ( float ) $filter -> initialPayment
: " " )
. (( isset ( $filter -> paymentTerm ) && is_numeric ( $filter -> paymentTerm ))
? " AND (DATEDIFF(chi.end_date, CURDATE()) / 30.44) >= " . ( float ) $filter -> paymentTerm
: " " )
. (( isset ( $filter -> installmentPrice -> min ) && is_numeric ( $filter -> installmentPrice -> min ))
? " AND complex_rooms.installment_price >= " . ( float ) $filter -> installmentPrice -> min
: " " )
. (( isset ( $filter -> installmentPrice -> max ) && is_numeric ( $filter -> installmentPrice -> max ))
? " AND complex_rooms.installment_price <= " . ( float ) $filter -> installmentPrice -> max
: " " )
. " ) " ;
}
}
}
$this -> limit = 12 ;
$limitSqlComolex = " limit { $this -> limit } " ;
$this -> set_user ();
$this -> set_users_ids ();
if ( $this -> page > 0 ) {
$limitSqlComolex = ' limit ' . ( $this -> page - 1 ) * $this -> limit . ', ' . $this -> limit ;
}
// var_dump($limitSqlComolex);die;
$result = array ();
$sql_total = " SELECT count(DISTINCT complex_list.id) as total, count( DISTINCT complex_houses.id) as houses_total, COUNT(DISTINCT complex_rooms.id) as total_rooms FROM complex_list
LEFT JOIN complex_houses ON complex_houses . complex_id = complex_list . id AND ( complex_houses . deleted_at IS NULL OR complex_houses . deleted_at = '0000-00-00 00:00:00' ) { $whereHouse }
LEFT JOIN complex_metro ON complex_metro . complex_id = complex_list . id
LEFT JOIN complex_address ON complex_address . complex_id = complex_list . id
LEFT JOIN complex_entrances complex_entrances ON complex_entrances . complex_house_id = complex_houses . id
LEFT JOIN complex_floors complex_floors ON complex_floors . complex_entrance_id = complex_entrances . id { $whereFloor }
LEFT JOIN complex_rooms complex_rooms ON complex_rooms . floor_id = complex_floors . id { $whereRoom }
WHERE complex_list . agency_id = { $this -> user -> agencyId }
AND complex_list . deleted = 0
{ $whereComplex }
{ $havingComplex }
ORDER BY complex_list . id DESC
" ;
$q_total = $this -> db -> query ( $sql_total );
$result [ 'total' ] = ( int ) $this -> db -> fetch_assoc ( $q_total )[ 'total' ];
$sql = " SELECT complex_list.*, count( DISTINCT CASE
WHEN ( complex_houses . deleted_at IS NULL OR complex_houses . deleted_at = '0000-00-00 00:00:00' )
THEN complex_houses . id
ELSE NULL
END ) as houses_total , COUNT ( DISTINCT CASE
WHEN ( complex_houses . deleted_at IS NULL OR complex_houses . deleted_at = '0000-00-00 00:00:00' )
THEN complex_rooms . id
ELSE NULL
END ) as total_rooms , MIN ( CASE
WHEN ( complex_houses . deleted_at IS NULL OR complex_houses . deleted_at = '0000-00-00 00:00:00' )
THEN complex_rooms . total_amount
ELSE NULL
END ) AS min_total_amount FROM complex_list
LEFT JOIN complex_houses ON complex_houses . complex_id = complex_list . id AND ( complex_houses . deleted_at IS NULL OR complex_houses . deleted_at = '0000-00-00 00:00:00' ) { $whereHouse }
LEFT JOIN complex_metro ON complex_metro . complex_id = complex_list . id
LEFT JOIN complex_address ON complex_address . complex_id = complex_list . id
LEFT JOIN complex_entrances complex_entrances ON complex_entrances . complex_house_id = complex_houses . id
LEFT JOIN complex_floors complex_floors ON complex_floors . complex_entrance_id = complex_entrances . id { $whereFloor }
LEFT JOIN complex_rooms complex_rooms ON complex_rooms . floor_id = complex_floors . id { $whereRoom }
WHERE complex_list . agency_id = { $this -> user -> agencyId }
AND complex_list . deleted = 0
{ $whereComplex }
GROUP BY complex_list . id
{ $havingComplex }
ORDER BY complex_list . id DESC { $limitSqlComolex }
" ;
$q = $this -> db -> query ( $sql );
// , MIN(complex_rooms.total_amount) AS min_total_amount
// echo '<pre>';
// print_r($q->queryString);
// echo '</pre>';
// die();
// var_dump($q);die;
// $result['total'] = $this->db->num_rows($q);
// var_dump('test');die;
$result [ 'allPages' ] = ceil ( $result [ 'total' ] / $this -> limit );
$result [ 'agency_name' ] = $this -> user -> agencyName ;
$result [ 'agency_logo' ] = $this -> user -> photo ;
$result [ 'agency_phone' ] = $this -> user -> agencyPhone ;
// var_dump($result['agency_phone']);die;
// var_dump($this->user);die;
// var_dump($result);die;
$complexIds = [];
while ( $r = $this -> db -> fetch_assoc ( $q )) {
$cid = ( int ) $r [ 'id' ];
$complexIds [] = $cid ;
$result [ 'list' ][ 'complex_' . $r [ 'id' ]] = $this -> get_complex_one ( $r [ 'id' ], true , false );
$result [ 'list' ][ 'complex_' . $r [ 'id' ]][ 'houses_total' ] = $r [ 'houses_total' ];
$result [ 'list' ][ 'complex_' . $r [ 'id' ]][ 'houses_total_unarchived' ] = 0 ;
$result [ 'list' ][ 'complex_' . $r [ 'id' ]][ 'total_rooms' ] = $r [ 'total_rooms' ];
$result [ 'list' ][ 'complex_' . $r [ 'id' ]][ 'total_rooms_unarchived' ] = 0 ;
$result [ 'list' ][ 'complex_' . $r [ 'id' ]][ 'min_total_amount' ] = $r [ 'min_total_amount' ];
// var_dump($r);die;
}
// var_dump($result);die;
//Подсчет кол-ва домов и комнат не в архиве
if ( ! empty ( $complexIds )) {
$idsString = implode ( ',' , $complexIds );
$sql_unarchived_counts = "
SELECT
cl . id as complex_id ,
COUNT ( DISTINCT ch . id ) as houses_total_unarchived ,
COUNT ( DISTINCT cr . id ) as total_rooms_unarchived
FROM complex_list cl
LEFT JOIN complex_houses ch
ON ch . complex_id = cl . id
AND ch . is_archive = 0
AND ( ch . deleted_at IS NULL OR ch . deleted_at = '0000-00-00 00:00:00' )
LEFT JOIN complex_metro cm ON cm . complex_id = cl . id
LEFT JOIN complex_address ca ON ca . complex_id = cl . id
LEFT JOIN complex_entrances ce ON ce . complex_house_id = ch . id
LEFT JOIN complex_floors cf ON cf . complex_entrance_id = ce . id
LEFT JOIN complex_rooms cr
ON cr . floor_id = cf . id
LEFT JOIN complex_status cs ON cs . id = cr . complex_status_id
WHERE
cl . id IN ({ $idsString })
AND cl . agency_id = { $this -> user -> agencyId }
AND cl . deleted = 0
AND cs . status = 'available'
GROUP BY cl . id
" ;
$q_unarchived = $this -> db -> query ( $sql_unarchived_counts );
if ( $q_unarchived ) {
while ( $u_r = $this -> db -> fetch_assoc ( $q_unarchived )) {
$cid = ( int ) $u_r [ 'complex_id' ];
if ( isset ( $result [ 'list' ][ 'complex_' . $cid ])) {
$result [ 'list' ][ 'complex_' . $cid ][ 'houses_total_unarchived' ] = ( int ) $u_r [ 'houses_total_unarchived' ];
$result [ 'list' ][ 'complex_' . $cid ][ 'total_rooms_unarchived' ] = ( int ) $u_r [ 'total_rooms_unarchived' ];
}
}
} else {
error_log ( " Ошибка выполнения запроса подсчета не архивных домов и доступных помещений: " . $this -> db -> error . " \n Запрос: " . $sql_unarchived_counts );
}
}
return $result ;
}
public function searchOLD ( $filter = array ())
{
$whereComplex = '' ;
$whereObjects = '' ;
$whereDecoration = '' ;
$complexIds = array ();
//Фильтр
if ( ! empty ( $filter )) {
//var_dump($filter);
// if (!empty($filter->country_id)) {
// $whereComplex .= " AND country_id = {$filter->country_id}";
// }
// if (!empty($filter->region_id)) {
// $whereComplex .= " AND rf_region_id = {$filter->region_id}";
// }
// if (!empty($filter->complexes)) {
// $complexIds = $filter->complexes;
// //$whereComplex .= " AND id in (".implode(',',$filter->complexes).")";
// }
if ( ! empty ( $filter -> selectedDecorations )) {
$whereComplex .= " AND type in (' " . implode ( '\',\'' , $filter -> selectedDecorations ) . " ') " ;
}
// if (!empty($filter->builders)) {
// $whereComplex .= " AND builder_id in (" . implode(',', $filter->builders) . ")";
// }
// if (!empty($filter->payment_types)) {
// $whereComplex .= " AND (JSON_EXTRACT(`payment_types`, '$[0]') in (" . implode(',', $filter->payment_types) . ")
// or JSON_EXTRACT(`payment_types`, '$[1]') in (" . implode(',', $filter->payment_types) . ")
// or JSON_EXTRACT(`payment_types`, '$[2]') in (" . implode(',', $filter->payment_types) . ")
// )";
// }
// if (!empty($filter->selectedMetros)) {
// $whereObjects .= " AND id_metro in (" . implode(',', $filter->selectedMetros) . ")";
// }
// if (!empty($filter->period)) {
// $whereObjects .= " AND nb_end_date <= {$filter->period}";
// }
// if (!empty($filter->area_from)) {
// $whereObjects .= " AND ploshad >= {$filter->area_from}";
// }
// if (!empty($filter->area_to)) {
// $whereObjects .= " AND ploshad <= {$filter->area_to}";
// }
// if (!empty($filter->floor_from)) {
// $whereObjects .= " AND etazh >= {$filter->floor_from}";
// }
// if (!empty($filter->floor_to)) {
// $whereObjects .= " AND etazh <= {$filter->floor_to}";
// }
// if (!empty($filter->price_from)) {
// $whereObjects .= " AND stoim >= {$filter->price_from}";
// }
// if (!empty($filter->price_to)) {
// $whereObjects .= " AND stoim <= {$filter->price_to}";
// }
if ( ! empty ( $filter -> types_room )) {
$types_room = array ();
$sql = " SELECT * FROM room_types WHERE id in ( " . implode ( ',' , $filter -> types_room ) . " ) " ;
$rez = $this -> db -> query ( $sql );
while ( $type_room = $this -> db -> fetch_assoc ( $rez )) {
$types_room [] = ( int ) $type_room [ 'name' ];
}
$whereObjects .= " AND komnat in ( " . implode ( ',' , $types_room ) . " ) " ;
}
if ( ! empty ( $filter -> decaration_types )) {
$whereDecoration = " AND decoration_id IN ( " . implode ( ',' , $filter -> decaration_types ) . " ) " ;
// $objDIds = array();
// $sql_d = "SELECT id, object_id FROM object_nb_info WHERE zipal_new_flat_decoration_type_id in (" . implode(',', $filter->decaration_types) . ")";
// $rez_d = $this->db->query($sql_d);
// while ($r_d = $this->db->fetch_assoc($rez_d)) {
// $objDIds[] = (int)$r_d['object_id'];
// }
// if (!empty($objDIds)) {
// $whereObjects .= " AND id in (" . implode(',', $objDIds) . ")";
// } else {
// $whereObjects .= " AND id in (0)";
// }
}
}
$this -> set_user ();
$this -> set_users_ids ();
// if (!empty($whereObjects)) {
// $complexIds = array();
// $complexTotalObject = array();
// $this->set_sphinx2();
// $sql_obj = "SELECT * FROM objects WHERE archive=0 and complex_id > 0 and id_add_user in (" . implode(',', $this->userIds) . ") {$whereObjects} LIMIT 1000000 OPTION max_matches=1000000";
// //echo $sql_obj;
// $q_obj = $this->sphinx2->query($sql_obj, true);
// while ($r_obj = $this->sphinx2->fetch_assoc($q_obj)) {
// $complexIds[] = (int)$r_obj['complex_id'];
// if (!isset($complexTotalObject[(int)$r_obj['complex_id']])) $complexTotalObject[(int)$r_obj['complex_id']] = 0;
// $complexTotalObject[(int)$r_obj['complex_id']]++;
// }
// }
if ( ! empty ( $complexIds )) {
$complexIds = array_unique ( $complexIds );
$whereComplex .= " AND id in ( " . implode ( ',' , $complexIds ) . " ) " ;
} else {
if ( ! empty ( $whereObjects ) || ! empty ( $filter -> complexes ))
$whereComplex .= " AND id in (-1) " ;
}
$limitSqlComolex = " limit 20 " ;
if ( $this -> page > 0 ) {
$limitSqlComolex = ' limit ' . ( $this -> page - 1 ) * $this -> limit . ', ' . $this -> limit ;
}
$result = array ();
$sql_total = " SELECT count(*) as total FROM complex_list
WHERE agency_id = { $this -> user -> agencyId }
AND arhive = 0
AND deleted = 0 { $whereComplex }
" ;
//echo $sql;
$q_total = $this -> db -> query ( $sql_total );
$result [ 'total' ] = ( int ) $this -> db -> fetch_assoc ( $q_total )[ 'total' ];
$sql = " SELECT * FROM complex_list WHERE agency_id= { $this -> user -> agencyId } AND arhive = 0 AND deleted = 0 { $whereComplex } ORDER BY id DESC { $limitSqlComolex } " ;
//echo $sql;
$q = $this -> db -> query ( $sql );
//$result['total'] = $this->db->num_rows($q);
$result [ 'allPages' ] = ceil ( $result [ 'total' ] / $this -> limit );
$complex_ids = array ();
while ( $r = $this -> db -> fetch_assoc ( $q )) {
$objects_list = true ;
$complex_ids [] = $r [ 'id' ];
if ( isset ( $complexTotalObject [ $r [ 'id' ]])) $objects_list = false ;
$result [ 'list' ][ 'complex_' . $r [ 'id' ]] = $this -> get_complex_one ( $r [ 'id' ], true , false );
if ( ! $objects_list ) $result [ 'list' ][ 'complex_' . $r [ 'id' ]][ 'objects_total' ] = $complexTotalObject [ $r [ 'id' ]];
}
$totalsHouse = array ();
if ( ! empty ( $complex_ids )) {
$sql_houses = " SELECT count(*) as total, complex_id FROM complex_houses WHERE complex_id in ( " . implode ( ',' , $complex_ids ) . " ) AND deleted_at IS NULL group by complex_id " ;
//echo $sql_houses;
$q_houses = $this -> db -> query ( $sql_houses );
while ( $r_houses = $this -> db -> fetch_assoc ( $q_houses )) {
$totalsHouse [ $r_houses [ 'complex_id' ]] = $r_houses [ 'total' ];
}
}
foreach ( $complex_ids as $id_c ) {
if ( isset ( $totalsHouse [ $id_c ])) {
$result [ 'list' ][ 'complex_' . $id_c ][ 'houses_total' ] = $totalsHouse [ $id_c ];
} else {
$result [ 'list' ][ 'complex_' . $id_c ][ 'houses_total' ] = 0 ;
}
$queryCountRooms = $this -> db -> query ( " SELECT SUM(cr.total_rooms) as total_rooms
FROM (
SELECT COUNT ( cr . id ) as total_rooms
FROM complex_houses as ch
LEFT JOIN complex_entrances ce ON ce . complex_house_id = ch . id
LEFT JOIN complex_floors cf ON cf . complex_entrance_id = ce . id
LEFT OUTER JOIN complex_rooms cr ON cr . floor_id = cf . id { $whereDecoration }
WHERE ch . complex_id = { $id_c }
GROUP BY ch . id
) as cr " );
$rowCount = $this -> db -> fetch_assoc ( $queryCountRooms );
$result [ 'list' ][ 'complex_' . $id_c ][ 'total_rooms' ] = ( int ) $rowCount [ 'total_rooms' ];
}
return $result ;
}
/**
*
*/
public function complex_add_object ( $complex_id , $object_id )
{
if ( $complex_id > 0 && $object_id > 0 ) {
$sql_complex = " SELECT id FROM complex_objects WHERE complex_id= { $complex_id } AND object_id= { $object_id } " ;
$q_complex = $this -> db -> query ( $sql_complex );
if ( $this -> db -> num_rows ( $q_complex ) == 0 ) {
$this -> db -> query ( " INSERT INTO complex_objects SET complex_id= { $complex_id } , object_id= { $object_id } " );
$this -> set_sphinx2 ();
$sql = " UPDATE objects SET complex_id = $complex_id
WHERE id = { $object_id } " ;
$this -> sphinx2 -> query ( $sql , true );
}
}
return 'done' ;
}
/**
*
*/
public function complex_archive ( $complex_id , $archive )
{
if ( $archive ) {
$this -> db -> query ( " UPDATE complex_list SET arhive=1 WHERE id = { $complex_id } " );
} else {
$this -> db -> query ( " UPDATE complex_list SET arhive=0 WHERE id = { $complex_id } " );
}
return array ( 'result' => 'done' , 'complex_id' => $complex_id );;
}
private function update_complex ( $complex_id , $fields , $table )
{
if ( $table == 'complex_advert' ) {
$sql = " SELECT id FROM { $table } WHERE complex_id = { $complex_id } " ;
$q = $this -> db -> query ( $sql );
if ( $this -> db -> num_rows ( $q ) == 0 ) {
$sql_in = " INSERT INTO { $table } SET " . implode ( ',' , $fields ) . " , complex_id = { $complex_id } " ;
} else {
$sql_in = " UPDATE { $table } SET " . implode ( ',' , $fields ) . " WHERE complex_id = { $complex_id } " ;
}
// echo $sql_in;
$this -> db -> query ( $sql_in );
}
}
/**
*
*/
public function complex_advert ( $complex_id , $yes_no = 1 )
{
$this -> set_sphinx2 ();
$obj_ids = array ();
$sql_complex_object = " SELECT * FROM complex_objects WHERE complex_id = { $complex_id } " ;
$q_complex_object = $this -> db -> query ( $sql_complex_object );
while ( $complex_obj = $this -> db -> fetch_assoc ( $q_complex_object )) {
$obj_ids [] = $complex_obj [ 'object_id' ];
}
$fields [] = " use_in_advert= { $yes_no } " ;
$this -> update_complex ( $complex_id , $fields , 'complex_advert' );
if ( ! empty ( $obj_ids ) && $yes_no > 0 ) {
$sql = " UPDATE objects SET archive = 0, use_in_advert=1, is_main = 0
WHERE id in ( " . implode(',', $obj_ids ) . " ) " ;
$this -> db -> query ( $sql );
//Запрос к сфинкс
$sql = " UPDATE objects SET archive = 0, use_in_advert=1
WHERE id in ( " . implode(',', $obj_ids ) . " ) " ;
$this -> sphinx2 -> query ( $sql , true );
}
if ( ! empty ( $obj_ids ) && $yes_no == 0 ) {
$sql = " UPDATE objects
SET use_in_advert = 0 ,
add_to_bn_feed = 0 ,
add_to_yandex_feed = 0 ,
add_to_domclick_feed = 0 ,
add_to_avito_feed = 0 ,
add_to_emls_feed = 0 ,
add_to_cian_feed = 0 ,
add_to_zipal = 0
WHERE id in ( " . implode(',', $obj_ids ) . " ) " ;
$this -> db -> query ( $sql );
$sql_sph = " UPDATE objects
SET use_in_advert = 0 ,
add_to_bn_feed = 0 ,
add_to_yandex_feed = 0 ,
add_to_domclick_feed = 0 ,
add_to_avito_feed = 0 ,
add_to_emls_feed = 0 ,
add_to_cian_feed = 0 ,
add_to_zipal = 0
WHERE id in ( " . implode(',', $obj_ids ) . " ) " ;
$this -> sphinx2 -> query ( $sql_sph , true );
}
}
/**
* Отправка объектов в рекламу на площадки
* @ param int $complex_id id комплекса
* @ param int $yes_no вкл / выкл
* @ param string $type
*/
public function complex_advert_plases ( $complex_id , $yes_no , $type , $days )
{
if ( $complex_id > 0 ) {
$this -> set_sphinx2 ();
$feed = '' ;
$stat_feed = '' ;
$user_id = ( int ) $_SESSION [ 'id' ];
switch ( $type ) {
case 'COMPLEX_YANDEX_JW_FEED' : {
$feed = 'add_to_bn_feed' ;
$stat_feed = 'YANDEX_JW_FEED' ;
$del_query = ' use_in_advert = IF (
add_to_yandex_feed = 0 AND
add_to_domclick_feed = 0 AND
add_to_avito_feed = 0 AND
add_to_emls_feed = 0 AND
add_to_cian_feed = 0 AND
add_to_zipal = 0 , 0 , 1 ) ' ;
$del_query_sph = ' if (
add_to_yandex_feed = 0 AND
add_to_domclick_feed = 0 AND
add_to_avito_feed = 0 AND
add_to_emls_feed = 0 AND
add_to_cian_feed = 0 AND
add_to_zipal = 0 , 0 , 1 ) ' ;
$advert_stat = 'yandex' ;
break ;
}
case 'COMPLEX_EMLS_JW_FEED' : {
$feed = 'add_to_emls_feed' ;
$stat_feed = 'EMLS_JW_FEED' ;
$del_query = ' use_in_advert = IF (
add_to_bn_feed = 0 AND
add_to_yandex_feed = 0 AND
add_to_domclick_feed = 0 AND
add_to_avito_feed = 0 AND
add_to_cian_feed = 0 AND
add_to_zipal = 0 , 0 , 1 ) ' ;
$del_query_sph = ' if (
add_to_bn_feed = 0 AND
add_to_yandex_feed = 0 AND
add_to_domclick_feed = 0 AND
add_to_avito_feed = 0 AND
add_to_cian_feed = 0 AND
add_to_zipal = 0 , 0 , 1 ) ' ;
$advert_stat = '' ;
break ;
}
case 'COMPLEX_DOMCLICK_JW_FEED' : {
$feed = 'add_to_domclick_feed' ;
$stat_feed = 'DOMCLICK_JW_FEED' ;
$del_query = ' use_in_advert = IF (
add_to_bn_feed = 0 AND
add_to_yandex_feed = 0 AND
add_to_cian_feed = 0 AND
add_to_avito_feed = 0 AND
add_to_emls_feed = 0 AND
add_to_zipal = 0 , 0 , 1 ) ' ;
$del_query_sph = ' if (
add_to_bn_feed = 0 AND
add_to_yandex_feed = 0 AND
add_to_cian_feed = 0 AND
add_to_avito_feed = 0 AND
add_to_emls_feed = 0 AND
add_to_zipal = 0 , 0 , 1 ) ' ;
$advert_stat = 'domclick' ;
break ;
}
case 'COMPLEX_CIAN_JW_FEED' : {
$feed = 'add_to_cian_feed' ;
$stat_feed = 'CIAN_JW_FEED' ;
$del_query = ' use_in_advert = IF (
add_to_bn_feed = 0 AND
add_to_yandex_feed = 0 AND
add_to_domclick_feed = 0 AND
add_to_avito_feed = 0 AND
add_to_emls_feed = 0 AND
add_to_zipal = 0 , 0 , 1 ) ' ;
$del_query_sph = ' if (
add_to_bn_feed = 0 AND
add_to_yandex_feed = 0 AND
add_to_domclick_feed = 0 AND
add_to_avito_feed = 0 AND
add_to_emls_feed = 0 AND
add_to_zipal = 0 , 0 , 1 ) ' ;
$advert_stat = 'cian' ;
break ;
}
case 'COMPLEX_AVITO_JW_FEED' : {
$feed = 'add_to_avito_feed' ;
$stat_feed = 'AVITO_JW_FEED' ;
$del_query = ' use_in_advert = IF (
add_to_bn_feed = 0 AND
add_to_yandex_feed = 0 AND
add_to_domclick_feed = 0 AND
add_to_emls_feed = 0 AND
add_to_cian_feed = 0 AND
add_to_zipal = 0 , 0 , 1 ) ' ;
$del_query_sph = ' if (
add_to_bn_feed = 0 AND
add_to_yandex_feed = 0 AND
add_to_domclick_feed = 0 AND
add_to_emls_feed = 0 AND
add_to_cian_feed = 0 AND
add_to_zipal = 0 , 0 , 1 ) ' ;
$advert_stat = 'avito' ;
break ;
}
case 'COMPLEX_FREE_JW_FEED' : {
$feed = 'add_to_yandex_feed' ;
$stat_feed = 'FREE_JW_FEED' ;
$del_query = ' use_in_advert = IF (
add_to_bn_feed = 0 AND
add_to_domclick_feed = 0 AND
add_to_avito_feed = 0 AND
add_to_emls_feed = 0 AND
add_to_cian_feed = 0 AND
add_to_zipal = 0 , 0 , 1 ) ' ;
$del_query_sph = ' if (
add_to_bn_feed = 0 AND
add_to_domclick_feed = 0 AND
add_to_avito_feed = 0 AND
add_to_emls_feed = 0 AND
add_to_cian_feed = 0 AND
add_to_zipal = 0 , 0 , 1 ) ' ;
$advert_stat = 'yandex' ;
break ;
}
}
$obj_ids = array ();
$sql_complex_object = " SELECT * FROM complex_objects WHERE complex_id = { $complex_id } " ;
$q_complex_object = $this -> db -> query ( $sql_complex_object );
while ( $complex_obj = $this -> db -> fetch_assoc ( $q_complex_object )) {
$obj_ids [] = $complex_obj [ 'object_id' ];
}
$fields [] = " { $feed } = { $yes_no } " ;
$this -> update_complex ( $complex_id , $fields , 'complex_advert' );
$objData = array ();
//Начитываем объекты
$sqlObjData = " SELECT id, nazv, id_add_user from objects WHERE id in ( " . implode ( ',' , $obj_ids ) . " ) " ;
$qObjData = $this -> db -> query ( $sqlObjData );
while ( $rObjData = $this -> db -> fetch_assoc ( $qObjData )) {
$objData [ $rObjData [ 'id' ]] = $rObjData ;
}
if ( $yes_no > 0 ) {
$sql = " UPDATE objects SET use_in_advert = 1, { $feed } = { $yes_no } , is_main = 0 WHERE id in ( " . implode ( ',' , $obj_ids ) . " ) " ;
$this -> db -> query ( $sql );
$sql_sph = " UPDATE objects SET use_in_advert = 1, { $feed } = { $yes_no } WHERE id in ( " . implode ( ',' , $obj_ids ) . " ) " ;
$this -> sphinx2 -> query ( $sql_sph , true );
foreach ( $obj_ids as $objId ) {
$sqlBaseStat = " INSERT INTO object_publish_statistic(object_id, user_owner_id, publish_user_id, created_at, publish_start_date, publish_end_date, days_count, destination, price)
VALUES ({ $objId }, '{$objData[$objId][' id_add_user ']}' , '$user_id' , NOW (), NOW (), DATE_ADD ( NOW (), INTERVAL $days DAY ), '$days' , '{$stat_feed}' , '0' ) " ;
//echo $sqlBaseStat;
$this -> db -> query ( $sqlBaseStat );
if ( ! empty ( $advert_stat )) {
AdvertStats :: cleanUpStats ( $advert_stat , $objId );
}
}
} else {
$sql = " UPDATE objects
SET { $del_query },
{ $feed } = '{$yes_no}' ,
is_main = 0
WHERE id in ( " . implode(',', $obj_ids ) . " ) " ;
$this -> db -> query ( $sql );
/* $sql_sph_tmp = " SELECT { $del_query_sph } FROM objects WHERE id in ( " . implode ( ',' , $obj_ids ) . " ) " ;
$q_sph_tmp = $this -> sphinx2 -> query ( $sql_sph_tmp );
$use_in_advert = $this -> sphinx2 -> result ( $q_sph_tmp ); */
$sql_sph = " UPDATE objects
SET
{ $feed } = $yes_no
WHERE id in ( " . implode(',', $obj_ids ) . " ) " ;
$this -> sphinx2 -> query ( $sql_sph , true );
//проставляем дату отмены в статистике
$sqlUpdateStat = " UPDATE object_publish_statistic SET unpublish_user_id = ' $user_id ', publish_end_date = NOW(), days_count = DATEDIFF(NOW(), publish_start_date) WHERE object_id in ( " . implode ( ',' , $obj_ids ) . " ) AND destination = ' { $stat_feed } ' AND (publish_end_date IS NULL OR publish_end_date > NOW()) " ;
$this -> db -> query ( $sqlUpdateStat );
if ( ! empty ( $advert_stat )) {
foreach ( $obj_ids as $objId ) {
AdvertStats :: cleanUpStats ( $advert_stat , $objId );
}
}
}
}
}
public function get_all_houses () {
$result = array ();
$this -> set_user ();
$this -> set_users_ids ();
// $imgR = $this->db->query("SELECT * from complex_house_images WHERE house_id = {$r['id']}");
$sql = "
SELECT
ch . id ,
ch . name ,
ch . development_end_quarter ,
ch . development_end_year ,
COUNT ( cr . id ) as total_rooms ,
MIN ( cr . total_amount ) as min_room_amount ,
complex_list . name as complex_name ,
complex_list . id as complex_id ,
complex_address . address as complex_address ,
chi . url as image_url
FROM complex_houses as ch
left JOIN complex_entrances ce ON ce . complex_house_id = ch . id
left JOIN complex_floors cf ON cf . complex_entrance_id = ce . id
LEFT OUTER JOIN complex_rooms cr ON cr . floor_id = cf . id
JOIN complex_list on complex_list . id = ch . complex_id
LEFT JOIN complex_address on complex_address . complex_id = complex_list . id
LEFT JOIN complex_house_images chi ON chi . house_id = ch . id
WHERE complex_list . agency_id = { $this -> user -> agencyId }
AND complex_list . arhive != 1
AND ch . is_archive != 1
AND ( ch . deleted_at IS NULL OR ch . deleted_at = '0000-00-00 00:00:00' )
GROUP BY ch . id order by ch . id desc " ;
$q = $this -> db -> query ( $sql );
while ( $r = $this -> db -> fetch_assoc ( $q )) {
$result [] = $r ;
}
return $result ;
}
/**
*
*/
public function get_houses ( $complex_id , $has_token = false , $filter = [])
{
$result = array ();
if ( $complex_id > 0 ) {
$name_complex = '' ;
$sql_complex = " SELECT name FROM complex_list WHERE id = { $complex_id } " ;
$q_complex = $this -> db -> query ( $sql_complex );
$r_complex = $this -> db -> fetch_assoc ( $q_complex );
if ( isset ( $r_complex [ 'name' ])) {
$name_complex = $r_complex [ 'name' ];
}
if ( $has_token ) {
if ( $this -> user -> agencyId == 20382 ) {
$filter_by_status = " " ;
} else {
$filter_by_status = " AND cs.status IN ('available', 'reservation') " ;
}
} else {
$filter_by_status = " " ;
}
$whereHouse = '' ;
if ( ! empty ( $filter -> is_partner_show )){
$whereHouse .= " AND ch.is_partner_show = 1 " ;
}
$sql = " SELECT ch.*, COUNT(cr.id) as total_rooms FROM complex_houses as ch
LEFT JOIN complex_entrances ce ON ce . complex_house_id = ch . id
LEFT JOIN complex_floors cf ON cf . complex_entrance_id = ce . id
LEFT JOIN complex_rooms cr ON cr . floor_id = cf . id
LEFT JOIN complex_status cs ON cr . complex_status_id = cs . id AND cs . is_archive = 0
WHERE ch . complex_id = { $complex_id } AND deleted_at IS NULL
{ $filter_by_status }
{ $whereHouse }
GROUP BY ch . id
ORDER BY ch . id DESC " ;
$q = $this -> db -> query ( $sql );
while ( $r = $this -> db -> fetch_assoc ( $q )) {
$r [ 'name_complex' ] = $name_complex ;
$r [ 'images' ] = array ();
$r [ 'floors' ] = array ();
$r [ 'rooms' ] = array ();
$imgR = $this -> db -> query ( " SELECT * from complex_house_images WHERE house_id = { $r [ 'id' ] } " );
$floorsQuery = $this -> db
-> query ( " SELECT complex_floors.* from complex_floors
LEFT JOIN complex_entrances ce ON complex_floors . complex_entrance_id = ce . id
WHERE ce . complex_house_id = { $r [ 'id' ]}; " );
$roomQuery = $this -> db -> query ( "
SELECT complex_rooms .* , cs . status
FROM complex_rooms
LEFT JOIN complex_floors AS cf ON cf . id = complex_rooms . floor_id
LEFT JOIN complex_entrances AS ce ON cf . complex_entrance_id = ce . id
LEFT JOIN complex_status cs ON complex_rooms . complex_status_id = cs . id AND cs . is_archive = 0
WHERE ce . complex_house_id = { $r [ 'id' ]}
{ $filter_by_status };
" );
$min_total_amount = null ;
while ( $floor = $this -> db -> fetch_assoc ( $floorsQuery )) {
$r [ 'floors' ][] = $floor ;
}
while ( $room = $this -> db -> fetch_assoc ( $roomQuery )) {
if ( in_array (( string ) $room [ 'id' ], $_SESSION [ 'to_send_complexes' ])) {
$room [ 'inPdf' ] = true ;
}
$r [ 'rooms' ][] = $room ;
// Вычисляем минимальную стоимость
if ( $room [ 'total_amount' ] !== null && $room [ 'total_amount' ] > 0 ) {
if ( $min_total_amount === null || $room [ 'total_amount' ] < $min_total_amount ) {
$min_total_amount = $room [ 'total_amount' ];
}
}
}
$r [ 'min_total_amount' ] = $min_total_amount ;
while ( $row = $this -> db -> fetch_assoc ( $imgR )) {
$r [ 'images' ][] = $row ;
}
$result [] = $r ;
}
}
return $result ;
}
/**
*
*/
public function get_house_one ( $house_id )
{
$types_building = [
'RESIDENTIAL' => 'Жилое' ,
'PARKING' => 'Паркинг' ,
'APARTMENT' => 'Апартаменты' ,
'OFFICE' => 'Офисы'
];
$placement_types = [
1 => 'Квартиры' ,
2 => 'Комнаты' ,
3 => 'Дома' ,
4 => 'Коммерция' ,
5 => 'Части домов' ,
7 => 'Участки'
];
$time_to_subway = [
1 => 'пешком' ,
2 => 'на транспорте'
];
$quarter_list = [
1 => 'I квартал' ,
2 => 'II квартал' ,
3 => 'III квартал' ,
4 => 'IV квартал' ,
];
$month_list = [
1 => 'Январь' ,
2 => 'Февраль' ,
3 => 'Март' ,
4 => 'Апрель' ,
5 => 'Май' ,
6 => 'Июнь' ,
7 => 'Июль' ,
8 => 'Август' ,
9 => 'Сентябрь' ,
10 => 'Октябрь' ,
11 => 'Ноябрь' ,
12 => 'Декабрь' ,
];
$status_corpus_list = [
1 => 'Построен, но не сдан' ,
2 => 'Cда н в эксплуатацию' ,
3 => 'Cтр о итс я' ,
4 => 'Построен и сдан' ,
];
$work_days = [
1 => 'Понедельник' ,
2 => 'Вторник' ,
3 => 'Среда' ,
4 => 'Четверг' ,
5 => 'Пятница' ,
6 => 'Суббота' ,
7 => 'Воскресенье' ,
];
$result = array ();
if ( $house_id > 0 ) {
$sql = " SELECT
complex_houses .* ,
COUNT ( DISTINCT c_rooms . id ) AS rooms_count ,
COUNT ( DISTINCT c_rooms_plans . id ) AS rooms_count_where_has_plans ,
COUNT ( DISTINCT c_floors . id ) as floors_count ,
COUNT ( DISTINCT c_floor_plans . floor_plan_id ) as floors_plans_count_where_has_floor ,
COUNT ( DISTINCT facades . id ) as facades_count ,
COUNT ( DISTINCT figures . floor_id ) as figures_where_has_floor_count
FROM
complex_houses
LEFT JOIN
complex_entrances c_entrances ON c_entrances . complex_house_id = complex_houses . id
LEFT JOIN
complex_floors c_floors ON c_floors . complex_entrance_id = c_entrances . id
LEFT JOIN
complex_house_facades facades ON facades . house_id = complex_houses . id AND facades . is_published != 0
LEFT JOIN
complex_facade_figures figures ON figures . facade_id = facades . id
LEFT JOIN
complex_floors_plans c_floor_plans ON c_floor_plans . floor_id = c_floors . id
LEFT JOIN
complex_rooms c_rooms ON c_rooms . floor_id = c_floors . id
LEFT JOIN
complex_rooms_plans c_rooms_plans ON c_rooms_plans . room_id = c_rooms . id
WHERE
complex_houses . id = { $house_id } AND complex_houses . deleted_at IS NULL " ;
$q = $this -> db -> query ( $sql );
$r = $this -> db -> fetch_assoc ( $q );
if ( ! $r ) {
return [ 'status' => false , 'message' => 'house not found' ];
}
$r [ 'type_building_text' ] = '' ;
if ( isset ( $types_building [ $r [ 'type_building' ]])) $r [ 'type_building_text' ] = $types_building [ $r [ 'type_building' ]];
$r [ 'placement_type_text' ] = '' ;
if ( isset ( $placement_types [ $r [ 'placement_type' ]])) $r [ 'placement_type_text' ] = $placement_types [ $r [ 'placement_type' ]];
$r [ 'status_corpus_text' ] = '' ;
if ( isset ( $status_corpus_list [ $r [ 'status_corpus' ]])) $r [ 'status_corpus_text' ] = $status_corpus_list [ $r [ 'status_corpus' ]];
$r [ 'deadline' ] = '' ;
if ( isset ( $quarter_list [ $r [ 'deadline_quarter' ]])) $r [ 'deadline' ] .= $quarter_list [ $r [ 'deadline_quarter' ]];
$r [ 'deadline' ] .= ' ' . $r [ 'deadline_year' ];
$r [ 'development' ] = '' ;
if ( isset ( $quarter_list [ $r [ 'development_start_quarter' ]])) {
$r [ 'development' ] .= $quarter_list [ $r [ 'development_start_quarter' ]] . ' ' . $r [ 'development_start_year' ];
}
if ( isset ( $quarter_list [ $r [ 'development_end_quarter' ]])) {
$r [ 'development' ] .= ' - ' . $quarter_list [ $r [ 'development_end_quarter' ]] . ' ' . $r [ 'development_end_year' ];
}
$result [ 'house' ] = $r ;
$result [ 'house' ][ 'images' ] = array ();
$imgR = $this -> db -> query ( " SELECT * from complex_house_images WHERE house_id = $house_id " );
while ( $row = $this -> db -> fetch_assoc ( $imgR )) {
$result [ 'house' ][ 'images' ][] = $row ;
}
$utpR = $this -> db -> query ( " SELECT * FROM complex_house_UTP WHERE house_id = { $house_id } " );
$result [ 'house' ][ 'utps' ] = [];
while ( $row = $this -> db -> fetch_assoc ( $utpR )) {
$result [ 'house' ][ 'utps' ][] = $row ;
}
$decR = $this -> db -> query ( " SELECT chd.*, dt.name as decoration_name FROM complex_house_decoration chd, decoration_types dt WHERE dt.id = chd.decoration_id AND house_id = { $house_id } " );
$result [ 'house' ][ 'decorations' ] = [];
while ( $row = $this -> db -> fetch_assoc ( $decR )) {
$result [ 'house' ][ 'decorations' ][] = $row ;
}
if ( $r [ 'complex_id' ] > 0 ) {
$complex = $this -> get_complex_one ( $r [ 'complex_id' ], false , false );
$result [ 'complex' ] = $complex ;
if ( isset ( $complex [ 'metro' ]) && isset ( $complex [ 'metro' ][ 'metro' ])) {
$result [ 'house' ][ 'metro' ] = $complex [ 'metro' ][ 'metro' ];
} else {
$result [ 'house' ][ 'metro' ] = [];
}
}
$installmentsResult = $this -> db -> query ( "
SELECT
i . id ,
i . name ,
i . type ,
i . description ,
i . initial_payment ,
i . payment_period ,
i . interest_rate ,
i . comment ,
chi . end_date
FROM
complex_house_installments chi
LEFT JOIN
installments i ON i . id = chi . installment_id
WHERE
chi . house_id = $house_id
" );
$result [ 'house' ][ 'installments' ] = [];
while ( $row = $this -> db -> fetch_assoc ( $installmentsResult )) {
$result [ 'house' ][ 'installments' ][] = $row ;
}
}
return $result ;
}
public function get_house_plans ( $house_id , $has_token = false )
{
$result = array ();
if ( $house_id > 0 ) {
$sql = " SELECT * FROM complex_house_plans WHERE house_id = { $house_id } " ;
$q = $this -> db -> query ( $sql );
while ( $plan = $this -> db -> fetch_assoc ( $q )) {
$images = $this -> get_plans_images ( $plan [ 'id' ]);
$rooms = $this -> get_plan_rooms ( $plan [ 'id' ], $has_token );
$plan [ 'images' ] = $images ;
$plan [ 'rooms' ] = $rooms ;
$result [] = $plan ;
}
}
return $result ;
}
public function get_entrances_floor_plans ( $house_id , $has_token = false )
{
$result = array ();
$sql = " SELECT DISTINCT entrances.*
FROM complex_entrances as entrances
JOIN complex_floors floors ON floors . complex_entrance_id = entrances . id
JOIN complex_floors_plans floor_plan_link ON floor_plan_link . floor_id = floors . id
JOIN complex_house_floor_plans floor_plans ON floor_plans . id = floor_plan_link . floor_plan_id
WHERE entrances . complex_house_id = { $house_id }
" ;
// JOIN complex_floor_plan_figures figures ON figures.floor_plan_id = floor_plans.id
// figures.room_plan_id IS NOT NULL AND
$res = $this -> db -> query ( $sql );
while ( $entrance = $this -> db -> fetch_assoc ( $res )) {
$sql_floors = " SELECT DISTINCT complex_floors.* from complex_floors
JOIN complex_floors_plans floor_plan_link ON floor_plan_link . floor_id = complex_floors . id
WHERE complex_entrance_id = { $entrance [ 'id' ]}
order by complex_floors . position
" ;
$entrance [ 'floors' ] = [];
$r_floors = $this -> db -> query ( $sql_floors );
while ( $floor = $this -> db -> fetch_assoc ( $r_floors )) {
$sql_plan_with_not_use_all = " SELECT plan.* FROM complex_house_floor_plans as plan
JOIN complex_floors_plans floor_plan_link ON floor_plan_link . floor_plan_id = plan . id
WHERE floor_plan_link . floor_id = { $floor [ 'id' ]} AND plan . is_use_all_entrances != 1
" ;
$sql_plan = " SELECT plan.* FROM complex_house_floor_plans as plan
JOIN complex_floors_plans floor_plan_link ON floor_plan_link . floor_plan_id = plan . id
WHERE floor_plan_link . floor_id = { $floor [ 'id' ]}
" ;
$floor [ 'plan' ] = [];
$r_plans = $this -> db -> query ( $sql_plan_with_not_use_all );
$plan = $this -> db -> fetch_assoc ( $r_plans );
if ( ! $plan ) {
$plan = $this -> db -> fetch_assoc ( $this -> db -> query ( $sql_plan ));
}
$plan [ 'entrances' ] = json_decode ( $plan [ 'entrances' ]);
$plan [ 'floor_positions' ] = json_decode ( $plan [ 'floor_positions' ]);
$plan [ 'is_use_all_entrances' ] = ( bool ) $plan [ 'is_use_all_entrances' ];
$plan [ 'has_light_angle' ] = ( bool ) $plan [ 'has_light_angle' ];
$plan [ 'figures' ] = array ();
$q = $this -> db -> query ( " SELECT DISTINCT figures.* FROM complex_floor_plan_figures as figures
JOIN complex_floors on complex_floors . id = { $floor [ 'id' ]}
JOIN complex_rooms ON complex_rooms . floor_id = complex_floors . id
JOIN complex_rooms_plans on complex_rooms_plans . plan_id = figures . room_plan_id AND complex_rooms_plans . room_id = complex_rooms . id
WHERE figures . floor_plan_id = { $plan [ 'id' ]} AND figures . room_plan_id IS NOT NULL " );
$installment_plans = [];
$installment_sql = " SELECT i.*,
chi . end_date as house_installment_end_date
FROM installments i
INNER JOIN complex_house_installments chi ON chi . installment_id = i . id
WHERE chi . house_id = { $house_id }
AND i . is_archive = 0
AND ( chi . end_date IS NULL OR chi . end_date >= CURDATE ()) " ;
$installment_q = $this -> db -> query ( $installment_sql );
while ( $plan_installment = $this -> db -> fetch_assoc ( $installment_q )) {
$installment_plans [] = [
'id' => $plan_installment [ 'id' ],
'name' => $plan_installment [ 'name' ],
'description' => $plan_installment [ 'description' ],
'type' => $plan_installment [ 'type' ],
'initial_payment' => $plan_installment [ 'initial_payment' ],
'payment_period' => json_decode ( $plan_installment [ 'payment_period' ], true ),
'allow_change_on_close' => $plan_installment [ 'allow_change_on_close' ],
'interest_rate' => $plan_installment [ 'interest_rate' ],
'comment' => $plan_installment [ 'comment' ],
'house_installment_end_date' => $plan_installment [ 'house_installment_end_date' ]
];
}
while ( $figure = $this -> db -> fetch_assoc ( $q )) {
// $r_room = $this->db->query("SELECT DISTINCT rooms.* FROM complex_rooms as rooms
// JOIN complex_rooms_plans as room_plan_link ON room_plan_link.room_id = rooms.id AND room_plan_link.plan_id = {$figure['room_plan_id']}
// WHERE rooms.floor_id = {$floor['id']}
// ");
$r_room = $this -> db -> query ( " SELECT DISTINCT
complex_rooms .* ,
c_house_p_i . url as plan_url ,
cs . name as status_name ,
cs . status as status_type ,
cs . color as status_color ,
ch . name as house_name ,
ch . parking as house_parking ,
ch . security as house_security ,
ch . fenced_area as house_fenced_area ,
ch . sports_ground as house_sports_ground ,
ch . play_ground as house_play_ground ,
ch . school as house_school ,
ch . kinder_garten as house_kinder_garten ,
ch . id as house_id ,
c_house_p . has_light_angle ,
c_house_p . light_angle FROM complex_rooms
LEFT JOIN complex_rooms_plans c_room_p ON c_room_p . room_id = complex_rooms . id AND c_room_p . plan_id = { $figure [ 'room_plan_id' ]}
2026-07-15 09:58:57 +02:00
LEFT JOIN complex_house_plans_images c_house_p_i ON c_room_p . plan_id = c_house_p_i . plan_id
2026-05-22 20:21:54 +02:00
LEFT JOIN complex_status cs ON complex_rooms . complex_status_id = cs . id and cs . is_archive = 0
JOIN complex_houses ch on ch . id = { $house_id }
LEFT JOIN complex_house_plans c_house_p ON c_room_p . plan_id = c_house_p . id
WHERE complex_rooms . id = c_room_p . room_id AND complex_rooms . floor_id = { $floor [ 'id' ]}
ORDER BY complex_rooms . position
" );
$room = $this -> db -> fetch_assoc ( $r_room );
$reservations = $this -> get_room_reservations ( $room [ 'id' ]);
unset ( $reservations [ 'can_change_queue' ]);
$complex_status_info = [
'status_name' => $room [ 'status_name' ],
'status_type' => $room [ 'status_type' ],
'status_color' => $room [ 'status_color' ]
];
if ( ! $has_token ) {
unset ( $room [ 'status_name' ]);
unset ( $room [ 'status_type' ]);
unset ( $room [ 'status_color' ]);
}
if ( $room [ 'status_type' ] != 'reservation' && is_array ( $reservations ) && count ( $reservations ))
{
$complex_status_info = [
'status_name' => $reservations [ 0 ][ 'status_name' ],
'status_type' => $reservations [ 0 ][ 'status_type' ],
'status_color' => $reservations [ 0 ][ 'status_color' ],
];
}
$room [ 'complex_status_info' ] = $complex_status_info ;
if ( in_array (( string ) $room [ 'id' ], $_SESSION [ 'to_send_complexes' ])) {
$room [ 'inPdf' ] = true ;
}
$room [ 'installment_plans' ] = $installment_plans ;
$figure [ 'room' ] = $room ? $room : null ;
$figure [ 'points' ] = json_decode ( $figure [ 'points' ]);
$plan [ 'figures' ][] = $figure ;
}
$floor [ 'plan' ] = $plan ? $plan : null ;
// $row_floor['plan'] = $this->get_floor_plan($row_floor['id']);
$entrance [ 'floors' ][] = $floor ;
}
$result [] = $entrance ;
}
return $result ;
}
public function get_house_floors_plans ( $house_id )
{
$result = array ();
if ( $house_id > 0 ) {
$sql = " SELECT * FROM complex_house_floor_plans WHERE house_id = { $house_id } " ;
$q = $this -> db -> query ( $sql );
while ( $plan = $this -> db -> fetch_assoc ( $q )) {
$floors = $this -> get_plan_floors ( $plan [ 'id' ]);
$plan [ 'floors' ] = $floors ;
$plan [ 'entrances' ] = json_decode ( $plan [ 'entrances' ]);
$plan [ 'floor_positions' ] = json_decode ( $plan [ 'floor_positions' ]);
$result [] = $plan ;
}
}
return $result ;
}
public function get_floor_plan ( $floor_plan_id )
{
if ( $floor_plan_id > 0 ) {
$sql = " SELECT * FROM complex_house_floor_plans WHERE id = { $floor_plan_id } " ;
$q = $this -> db -> query ( $sql );
$plan = $this -> db -> fetch_assoc ( $q );
$plan [ 'entrances' ] = json_decode ( $plan [ 'entrances' ]);
$plan [ 'floor_positions' ] = json_decode ( $plan [ 'floor_positions' ]);
$plan [ 'is_use_all_entrances' ] = ( bool ) $plan [ 'is_use_all_entrances' ];
$plan [ 'has_light_angle' ] = ( bool ) $plan [ 'has_light_angle' ];
$plan [ 'figures' ] = array ();
$q = $this -> db -> query ( " SELECT * FROM complex_floor_plan_figures WHERE floor_plan_id = { $plan [ 'id' ] } " );
while ( $row = $this -> db -> fetch_assoc ( $q )) {
$row [ 'points' ] = json_decode ( $row [ 'points' ]);
$plan [ 'figures' ][] = $row ;
}
return $plan ;
}
return [ 'status' => false ];
}
public function save_document ( $blank_id , $req_id , $room , $user_id ){
$room_array = json_decode ( json_encode ( $room ), true );
$room_id = $room_array [ 'id' ] ;
$q = $this -> db -> query ( " SELECT client_id, object_id FROM requisitions WHERE id = " . intval ( $req_id ));
$client = $this -> db -> fetch_assoc ( $q );
$client_id = $client [ 'client_id' ];
$document = Docs :: fillInnerDocument ( $blank_id , $client_id , null , null , false , $room_array );
$document_id = $document [ " doc_id " ];
$sql_insert = "
INSERT INTO user_client_events ( req_id , type , document_id , user_id )
VALUES ( $req_id , 'file' , $document_id , $user_id )
" ;
$this -> db -> query ( $sql_insert );
}
public function updateRoomsPlanLink ( $plan_id , $room_ids = [])
{
// $plan_id, $room_ids
if ( $plan_id ) {
$sqlDelete = " DELETE FROM complex_rooms_plans WHERE plan_id = $plan_id " ;
$q = $this -> db -> query ( $sqlDelete );
}
if ( ! empty ( $room_ids )) {
$insertValue = array ();
foreach ( $room_ids as $room_id ) {
$insertValue [] = " ( $plan_id , $room_id ) " ;
}
$insertValueStr = implode ( ', ' , $insertValue );
$sqlAddRooms = " INSERT INTO complex_rooms_plans (plan_id, room_id) VALUES { $insertValueStr } " ;
$q = $this -> db -> query ( $sqlAddRooms );
}
return $this -> get_plan_rooms ( $plan_id );
}
public function change_rooms_price_by_square ( $value , $room_ids , $type , $operation_type ) {
foreach ( $room_ids as $id ) {
if ( ! is_numeric ( $id )) continue ;
$q = $this -> db -> query ( " SELECT id, $operation_type , area FROM complex_rooms WHERE id = { $id } " );
$room = $this -> db -> fetch_assoc ( $q );
if ( ! $room || $room [ 'area' ] == 0 ) continue ;
$unitPrice = $room [ $operation_type ] / $room [ 'area' ];
switch ( $type ) {
case 'change_by_value' :
$unitPrice = $value ;
break ;
case 'up_by_percent' :
$unitPrice += $unitPrice * ( $value / 100 );
break ;
case 'down_by_percent' :
$unitPrice -= $unitPrice * ( $value / 100 );
break ;
case 'up_by_value' :
$unitPrice += $value ;
break ;
case 'down_by_value' :
$unitPrice -= $value ;
break ;
default :
return [ 'status' => false ];
}
$newTotal = $unitPrice * $room [ 'area' ];
$sql = " UPDATE complex_rooms SET $operation_type = { $newTotal } WHERE id = { $id } " ;
$this -> db -> query ( $sql );
}
return [ 'status' => true ];
}
public function change_rooms_price ( $value , $room_ids , $type , $operation_type ) {
if ( $type === 'change_by_value' ) {
foreach ( $room_ids as $id ) {
if ( is_numeric ( $id )) {
$sqlAddRooms = " UPDATE complex_rooms SET $operation_type = { $value } WHERE id = { $id } " ;
$this -> db -> query ( $sqlAddRooms );
}
}
return [ 'status' => true ];
}
if ( $type === 'up_by_percent' ) {
foreach ( $room_ids as $id ) {
if ( is_numeric ( $id )) {
$q = $this -> db -> query ( " SELECT id, $operation_type FROM complex_rooms WHERE id = { $id } " );
$room = $this -> db -> fetch_assoc ( $q );
$newPrice = $room [ $operation_type ] + ( $room [ $operation_type ] * ( $value / 100 ));
$sqlAddRooms = " UPDATE complex_rooms SET $operation_type = { $newPrice } WHERE id = { $id } " ;
$this -> db -> query ( $sqlAddRooms );
}
}
return [ 'status' => true ];
}
if ( $type === 'down_by_percent' ) {
foreach ( $room_ids as $id ) {
if ( is_numeric ( $id )) {
$q = $this -> db -> query ( " SELECT id, $operation_type FROM complex_rooms WHERE id = { $id } " );
$room = $this -> db -> fetch_assoc ( $q );
$newPrice = $room [ $operation_type ] - ( $room [ $operation_type ] * ( $value / 100 ));
$sqlAddRooms = " UPDATE complex_rooms SET $operation_type = { $newPrice } WHERE id = { $id } " ;
$this -> db -> query ( $sqlAddRooms );
}
}
return [ 'status' => true ];
}
if ( $type === 'down_by_value' ) {
foreach ( $room_ids as $id ) {
if ( is_numeric ( $id )) {
$q = $this -> db -> query ( " SELECT id, $operation_type FROM complex_rooms WHERE id = { $id } " );
$room = $this -> db -> fetch_assoc ( $q );
$newPrice = $room [ $operation_type ] - $value ;
$sqlAddRooms = " UPDATE complex_rooms SET $operation_type = { $newPrice } WHERE id = { $id } " ;
$this -> db -> query ( $sqlAddRooms );
}
}
return [ 'status' => true ];
}
if ( $type === 'up_by_value' ) {
foreach ( $room_ids as $id ) {
if ( is_numeric ( $id )) {
$q = $this -> db -> query ( " SELECT id, $operation_type FROM complex_rooms WHERE id = { $id } " );
$room = $this -> db -> fetch_assoc ( $q );
$newPrice = $room [ $operation_type ] + $value ;
$sqlAddRooms = " UPDATE complex_rooms SET $operation_type = { $newPrice } WHERE id = { $id } " ;
$this -> db -> query ( $sqlAddRooms );
}
}
return [ 'status' => true ];
}
return [ 'status' => false ];
}
public function send_rooms_to_advert ( $house_id , $room_ids , $type ) {
if ( $type === 'domclick' ) {
$roomsInAdvert = [];
//ищем все помещения, которые уже размещены
$rooms_sql = " SELECT complex_rooms.id
FROM complex_rooms
LEFT JOIN complex_room_advert cra ON cra . complex_room_id = complex_rooms . id
LEFT JOIN complex_floors cf ON cf . id = complex_rooms . floor_id
LEFT JOIN complex_entrances ce ON ce . id = cf . complex_entrance_id
LEFT JOIN complex_houses ch ON ch . id = ce . complex_house_id
WHERE ce . complex_house_id = { $house_id } and cra . add_to_domclick_feed = 1
GROUP BY complex_rooms . id
ORDER BY complex_rooms . position " ;
$rooms_q = $this -> db -> query ( $rooms_sql );
while ( $room = $this -> db -> fetch_assoc ( $rooms_q )) {
$roomsInAdvert [] = $room [ 'id' ];
}
//размещаем выбранные помещения в рекламу
foreach ( $room_ids as $id ) {
$sql_adv = " SELECT id FROM complex_room_advert WHERE complex_room_id= { $id } " ;
$q_adv = $this -> db -> query ( $sql_adv );
if ( $this -> db -> num_rows ( $q_adv ) == 0 ) {
$sqlAddRooms = " INSERT INTO complex_room_advert (complex_room_id, add_to_domclick_feed) VALUES ( { $id } , 1) " ;
$this -> db -> query ( $sqlAddRooms );
} else {
$sqlAddRooms = " UPDATE complex_room_advert SET add_to_domclick_feed = 1 WHERE complex_room_id = { $id } " ;
$this -> db -> query ( $sqlAddRooms );
}
//удаляем из массива уже размещенных
$key = array_search ( $id , $roomsInAdvert );
if ( $key !== false ) {
unset ( $roomsInAdvert [ $key ]);
}
}
//снимаем с рекламы то, что было в БД, но снято
foreach ( $roomsInAdvert as $id ) {
$sqlAddRooms = " UPDATE complex_room_advert SET add_to_domclick_feed = 0 WHERE complex_room_id = { $id } " ;
$this -> db -> query ( $sqlAddRooms );
}
}
if ( $type === 'avito' ) {
$roomsInAdvert = [];
//ищем все помещения, которые уже размещены
$rooms_sql = " SELECT complex_rooms.id
FROM complex_rooms
LEFT JOIN complex_room_advert cra ON cra . complex_room_id = complex_rooms . id
LEFT JOIN complex_floors cf ON cf . id = complex_rooms . floor_id
LEFT JOIN complex_entrances ce ON ce . id = cf . complex_entrance_id
LEFT JOIN complex_houses ch ON ch . id = ce . complex_house_id
WHERE ce . complex_house_id = { $house_id } and cra . add_to_avito_feed = 1
GROUP BY complex_rooms . id
ORDER BY complex_rooms . position " ;
$rooms_q = $this -> db -> query ( $rooms_sql );
while ( $room = $this -> db -> fetch_assoc ( $rooms_q )) {
$roomsInAdvert [] = $room [ 'id' ];
}
//размещаем выбранные помещения в рекламу
foreach ( $room_ids as $id ) {
$sql_adv = " SELECT id FROM complex_room_advert WHERE complex_room_id= { $id } " ;
$q_adv = $this -> db -> query ( $sql_adv );
if ( $this -> db -> num_rows ( $q_adv ) == 0 ) {
$sqlAddRooms = " INSERT INTO complex_room_advert (complex_room_id, add_to_avito_feed) VALUES ( { $id } , 1) " ;
$this -> db -> query ( $sqlAddRooms );
} else {
$sqlAddRooms = " UPDATE complex_room_advert SET add_to_avito_feed = 1 WHERE complex_room_id = { $id } " ;
$this -> db -> query ( $sqlAddRooms );
}
//удаляем из массива уже размещенных
$key = array_search ( $id , $roomsInAdvert );
if ( $key !== false ) {
unset ( $roomsInAdvert [ $key ]);
}
}
//снимаем с рекламы то, что было в БД, но снято
foreach ( $roomsInAdvert as $id ) {
$sqlAddRooms = " UPDATE complex_room_advert SET add_to_avito_feed = 0 WHERE complex_room_id = { $id } " ;
$this -> db -> query ( $sqlAddRooms );
}
}
if ( $type === 'cian' ) {
$roomsInAdvert = [];
//ищем все помещения, которые уже размещены
$rooms_sql = " SELECT complex_rooms.id
FROM complex_rooms
LEFT JOIN complex_room_advert cra ON cra . complex_room_id = complex_rooms . id
LEFT JOIN complex_floors cf ON cf . id = complex_rooms . floor_id
LEFT JOIN complex_entrances ce ON ce . id = cf . complex_entrance_id
LEFT JOIN complex_houses ch ON ch . id = ce . complex_house_id
WHERE ce . complex_house_id = { $house_id } and cra . add_to_cian_feed = 1
GROUP BY complex_rooms . id
ORDER BY complex_rooms . position " ;
$rooms_q = $this -> db -> query ( $rooms_sql );
while ( $room = $this -> db -> fetch_assoc ( $rooms_q )) {
$roomsInAdvert [] = $room [ 'id' ];
}
//размещаем выбранные помещения в рекламу
foreach ( $room_ids as $id ) {
$sql_adv = " SELECT id FROM complex_room_advert WHERE complex_room_id= { $id } " ;
$q_adv = $this -> db -> query ( $sql_adv );
if ( $this -> db -> num_rows ( $q_adv ) == 0 ) {
$sqlAddRooms = " INSERT INTO complex_room_advert (complex_room_id, add_to_cian_feed) VALUES ( { $id } , 1) " ;
$this -> db -> query ( $sqlAddRooms );
} else {
$sqlAddRooms = " UPDATE complex_room_advert SET add_to_cian_feed = 1 WHERE complex_room_id = { $id } " ;
$this -> db -> query ( $sqlAddRooms );
}
//удаляем из массива уже размещенных
$key = array_search ( $id , $roomsInAdvert );
if ( $key !== false ) {
unset ( $roomsInAdvert [ $key ]);
}
}
//снимаем с рекламы то, что было в БД, но снято
foreach ( $roomsInAdvert as $id ) {
$sqlAddRooms = " UPDATE complex_room_advert SET add_to_cian_feed = 0 WHERE complex_room_id = { $id } " ;
$this -> db -> query ( $sqlAddRooms );
}
}
if ( $type === 'ya' ) {
$roomsInAdvert = [];
//ищем все помещения, которые уже размещены
$rooms_sql = " SELECT complex_rooms.id
FROM complex_rooms
LEFT JOIN complex_room_advert cra ON cra . complex_room_id = complex_rooms . id
LEFT JOIN complex_floors cf ON cf . id = complex_rooms . floor_id
LEFT JOIN complex_entrances ce ON ce . id = cf . complex_entrance_id
LEFT JOIN complex_houses ch ON ch . id = ce . complex_house_id
WHERE ce . complex_house_id = { $house_id } and cra . add_to_yandex_feed = 1
GROUP BY complex_rooms . id
ORDER BY complex_rooms . position " ;
$rooms_q = $this -> db -> query ( $rooms_sql );
while ( $room = $this -> db -> fetch_assoc ( $rooms_q )) {
$roomsInAdvert [] = $room [ 'id' ];
}
//размещаем выбранные помещения в рекламу
foreach ( $room_ids as $id ) {
$sql_adv = " SELECT id FROM complex_room_advert WHERE complex_room_id= { $id } " ;
$q_adv = $this -> db -> query ( $sql_adv );
if ( $this -> db -> num_rows ( $q_adv ) == 0 ) {
$sqlAddRooms = " INSERT INTO complex_room_advert (complex_room_id, add_to_yandex_feed) VALUES ( { $id } , 1) " ;
$this -> db -> query ( $sqlAddRooms );
} else {
$sqlAddRooms = " UPDATE complex_room_advert SET add_to_yandex_feed = 1 WHERE complex_room_id = { $id } " ;
$this -> db -> query ( $sqlAddRooms );
}
//удаляем из массива уже размещенных
$key = array_search ( $id , $roomsInAdvert );
if ( $key !== false ) {
unset ( $roomsInAdvert [ $key ]);
}
}
//снимаем с рекламы то, что было в БД, но снято
foreach ( $roomsInAdvert as $id ) {
$sqlAddRooms = " UPDATE complex_room_advert SET add_to_yandex_feed = 0 WHERE complex_room_id = { $id } " ;
$this -> db -> query ( $sqlAddRooms );
}
}
if ( $type === 'domrf' ) {
$roomsInAdvert = [];
//ищем все помещения, которые уже размещены
$rooms_sql = " SELECT complex_rooms.id
FROM complex_rooms
LEFT JOIN complex_room_advert cra ON cra . complex_room_id = complex_rooms . id
LEFT JOIN complex_floors cf ON cf . id = complex_rooms . floor_id
LEFT JOIN complex_entrances ce ON ce . id = cf . complex_entrance_id
LEFT JOIN complex_houses ch ON ch . id = ce . complex_house_id
WHERE ce . complex_house_id = { $house_id } and cra . add_to_domrf_feed = 1
GROUP BY complex_rooms . id
ORDER BY complex_rooms . position " ;
$rooms_q = $this -> db -> query ( $rooms_sql );
while ( $room = $this -> db -> fetch_assoc ( $rooms_q )) {
$roomsInAdvert [] = $room [ 'id' ];
}
//размещаем выбранные помещения в рекламу
foreach ( $room_ids as $id ) {
$sql_adv = " SELECT id FROM complex_room_advert WHERE complex_room_id= { $id } " ;
$q_adv = $this -> db -> query ( $sql_adv );
if ( $this -> db -> num_rows ( $q_adv ) == 0 ) {
$sqlAddRooms = " INSERT INTO complex_room_advert (complex_room_id, add_to_domrf_feed) VALUES ( { $id } , 1) " ;
$this -> db -> query ( $sqlAddRooms );
} else {
$sqlAddRooms = " UPDATE complex_room_advert SET add_to_domrf_feed = 1 WHERE complex_room_id = { $id } " ;
$this -> db -> query ( $sqlAddRooms );
}
//удаляем из массива уже размещенных
$key = array_search ( $id , $roomsInAdvert );
if ( $key !== false ) {
unset ( $roomsInAdvert [ $key ]);
}
}
//снимаем с рекламы то, что было в БД, но снято
foreach ( $roomsInAdvert as $id ) {
$sqlAddRooms = " UPDATE complex_room_advert SET add_to_domrf_feed = 0 WHERE complex_room_id = { $id } " ;
$this -> db -> query ( $sqlAddRooms );
}
}
if ( $type === 'site' ) {
$roomsInAdvert = [];
//ищем все помещения, которые уже размещены
$rooms_sql = " SELECT complex_rooms.id
FROM complex_rooms
LEFT JOIN complex_room_advert cra ON cra . complex_room_id = complex_rooms . id
LEFT JOIN complex_floors cf ON cf . id = complex_rooms . floor_id
LEFT JOIN complex_entrances ce ON ce . id = cf . complex_entrance_id
LEFT JOIN complex_houses ch ON ch . id = ce . complex_house_id
WHERE ce . complex_house_id = { $house_id } and cra . add_to_site_feed = 1
GROUP BY complex_rooms . id
ORDER BY complex_rooms . position " ;
$rooms_q = $this -> db -> query ( $rooms_sql );
while ( $room = $this -> db -> fetch_assoc ( $rooms_q )) {
$roomsInAdvert [] = $room [ 'id' ];
}
//размещаем выбранные помещения в рекламу
foreach ( $room_ids as $id ) {
$sql_adv = " SELECT id FROM complex_room_advert WHERE complex_room_id= { $id } " ;
$q_adv = $this -> db -> query ( $sql_adv );
if ( $this -> db -> num_rows ( $q_adv ) == 0 ) {
$sqlAddRooms = " INSERT INTO complex_room_advert (complex_room_id, add_to_site_feed) VALUES ( { $id } , 1) " ;
$this -> db -> query ( $sqlAddRooms );
} else {
$sqlAddRooms = " UPDATE complex_room_advert SET add_to_site_feed = 1 WHERE complex_room_id = { $id } " ;
$this -> db -> query ( $sqlAddRooms );
}
//удаляем из массива уже размещенных
$key = array_search ( $id , $roomsInAdvert );
if ( $key !== false ) {
unset ( $roomsInAdvert [ $key ]);
}
}
//снимаем с рекламы то, что было в БД, но снято
foreach ( $roomsInAdvert as $id ) {
$sqlAddRooms = " UPDATE complex_room_advert SET add_to_site_feed = 0 WHERE complex_room_id = { $id } " ;
$this -> db -> query ( $sqlAddRooms );
}
}
}
public function get_plan_floors ( $floor_plan_id )
{
$result = array ();
if ( $floor_plan_id > 0 ) {
$sql = " SELECT floor.* FROM complex_floors as floor
JOIN complex_floors_plans floors_plans on floors_plans . floor_id = floor . id
WHERE floors_plans . floor_plan_id = { $floor_plan_id }
" ;
$q = $this -> db -> query ( $sql );
while ( $floor = $this -> db -> fetch_assoc ( $q )) {
$result [] = $floor ;
}
}
return $result ;
}
public function get_house_facades ( $house_id , $includes = [])
{
$result = array ();
$usePublished = in_array ( 'not_published' , $includes );
if ( $house_id > 0 ) {
if ( $usePublished ) {
$sql = " SELECT * FROM complex_house_facades WHERE house_id = { $house_id } " ;
} else {
$sql = " SELECT * FROM complex_house_facades WHERE house_id = { $house_id } AND is_published != 0 " ;
}
$q = $this -> db -> query ( $sql );
while ( $facade = $this -> db -> fetch_assoc ( $q )) {
$facade [ 'figures' ] = $this -> getFacadeFigures ( $house_id , $facade [ 'id' ], $includes );
$facade [ 'is_published' ] = ( bool ) $facade [ 'is_published' ];
$result [] = $facade ;
}
}
return $result ;
}
public function getFacadeFigures ( $house_id , $facade_id , $includes = [])
{
$result = array ();
$useRooms = in_array ( 'rooms' , $includes );
$useFloor = in_array ( 'floor' , $includes );
$useEntrance = in_array ( 'entrance' , $includes );
if ( $facade_id > 0 ) {
$sql = " SELECT * FROM complex_facade_figures WHERE facade_id = { $facade_id } " ;
$q = $this -> db -> query ( $sql );
// Installment plans: fetch once by house_id
$installment_plans = [];
$installment_sql = " SELECT i.*, chi.end_date as house_installment_end_date
FROM installments i
INNER JOIN complex_house_installments chi ON chi . installment_id = i . id
WHERE chi . house_id = { $house_id }
AND i . is_archive = 0
AND ( chi . end_date IS NULL OR chi . end_date >= CURDATE ()) " ;
$installment_q = $this -> db -> query ( $installment_sql );
while ( $plan = $this -> db -> fetch_assoc ( $installment_q )) {
$installment_plans [] = [
'id' => $plan [ 'id' ],
'name' => $plan [ 'name' ],
'description' => $plan [ 'description' ],
'type' => $plan [ 'type' ],
'initial_payment' => $plan [ 'initial_payment' ],
'payment_period' => json_decode ( $plan [ 'payment_period' ], true ),
'allow_change_on_close' => $plan [ 'allow_change_on_close' ],
'interest_rate' => $plan [ 'interest_rate' ],
'comment' => $plan [ 'comment' ],
'house_installment_end_date' => $plan [ 'house_installment_end_date' ]
];
}
while ( $figure = $this -> db -> fetch_assoc ( $q )) {
$figure [ 'points' ] = json_decode ( $figure [ 'points' ]);
if ( $useRooms ) {
$figure [ 'rooms' ] = [];
if ( $figure [ 'floor_id' ] && $figure [ 'entrance_id' ]) {
$sqlRooms = " SELECT
complex_rooms . id ,
complex_rooms . number ,
complex_rooms . area ,
complex_rooms . kitchen_area ,
complex_rooms . total_amount ,
complex_rooms . installment_price ,
complex_rooms . rooms_count ,
complex_rooms . layout_feature ,
complex_rooms . decoration_id ,
complex_rooms . windows_placement_id ,
complex_rooms . ceiling_height ,
complex_rooms . payment_types ,
MIN ( complex_rooms . position ) AS position ,
MIN ( complex_floors . position ) AS floor ,
complex_entrances . name AS entrance_name ,
MIN ( c_house_p_i . url ) AS plan_url ,
MIN ( cs . name ) AS status_name ,
MIN ( cs . status ) AS status_type ,
MIN ( cs . color ) AS status_color ,
MIN ( ch . name ) AS house_name ,
MIN ( ch . parking ) AS house_parking ,
MIN ( ch . security ) AS house_security ,
MIN ( ch . fenced_area ) AS house_fenced_area ,
MIN ( ch . sports_ground ) AS house_sports_ground ,
MIN ( ch . play_ground ) AS house_play_ground ,
MIN ( ch . school ) AS house_school ,
MIN ( ch . kinder_garten ) AS house_kinder_garten ,
MIN ( ch . id ) AS house_id ,
MIN ( c_house_p . has_light_angle ) AS has_light_angle ,
MIN ( c_house_p . light_angle ) AS light_angle
FROM
complex_rooms
JOIN complex_floors ON complex_floors . id = complex_rooms . floor_id
JOIN complex_entrances ON complex_entrances . id = complex_floors . complex_entrance_id
LEFT JOIN complex_rooms_plans c_room_p ON c_room_p . room_id = complex_rooms . id
2026-07-15 09:58:57 +02:00
LEFT JOIN complex_house_plans_images c_house_p_i ON c_room_p . plan_id = c_house_p_i . plan_id
2026-05-22 20:21:54 +02:00
LEFT JOIN complex_status cs ON complex_rooms . complex_status_id = cs . id AND cs . is_archive = 0
JOIN complex_houses ch ON ch . id = { $house_id }
LEFT JOIN complex_house_plans c_house_p ON c_room_p . plan_id = c_house_p . id
WHERE
complex_floors . id = { $figure [ 'floor_id' ]}
AND complex_entrances . id = { $figure [ 'entrance_id' ]}
AND cs . status = 'available'
GROUP BY
complex_rooms . id ,
complex_entrances . name
ORDER BY
MIN ( complex_rooms . position ) " ;
$res = $this -> db -> query ( $sqlRooms );
while ( $room = $this -> db -> fetch_assoc ( $res )) {
if ( $room [ 'status_type' ] == 'reservation' ) {
$requisition_sql = $this -> db -> query ( " SELECT id FROM requisitions where complex_room_id = { $room [ 'id' ] } ORDER BY created_at DESC " );
if ( $row = $this -> db -> fetch_assoc ( $requisition_sql )) {
$room [ 'requisition_id' ] = $row [ 'id' ];
}
}
if ( in_array (( string ) $room [ 'id' ], $_SESSION [ 'to_send_complexes' ])) {
$room [ 'inPdf' ] = true ;
}
$reservations = $this -> get_room_reservations ( $room [ 'id' ]);
unset ( $reservations [ 'can_change_queue' ]);
$complex_status_info = [
'status_name' => $room [ 'status_name' ],
'status_type' => $room [ 'status_type' ],
'status_color' => $room [ 'status_color' ]
];
if ( $room [ 'status_type' ] != 'reservation' && is_array ( $reservations ) && count ( $reservations ))
{
$complex_status_info = [
'status_name' => $reservations [ 0 ][ 'status_name' ],
'status_type' => $reservations [ 0 ][ 'status_type' ],
'status_color' => $reservations [ 0 ][ 'status_color' ],
];
}
$room [ 'complex_status_info' ] = $complex_status_info ;
// Installment plans without base_price
$room [ 'installment_plans' ] = $installment_plans ;
// Payment types decode
if ( ! empty ( $room [ 'payment_types' ])) {
$decodedPaymentTypes = json_decode ( $room [ 'payment_types' ], true );
$room [ 'payment_types' ] = is_array ( $decodedPaymentTypes ) ? $decodedPaymentTypes : [];
} else {
$room [ 'payment_types' ] = [];
}
$figure [ 'rooms' ][] = $room ;
}
}
}
if ( $useFloor ) {
$figure [ 'floor' ] = null ;
if ( $figure [ 'floor_id' ]) {
$sqlFloor = $this -> db -> query ( " SELECT DISTINCT complex_floors.*, floor_plans.image as plan_url FROM complex_floors
LEFT JOIN complex_floors_plans floor_plan_link ON floor_plan_link . floor_id = complex_floors . id
LEFT JOIN complex_house_floor_plans floor_plans ON floor_plans . id = floor_plan_link . floor_plan_id
WHERE complex_floors . id = { $figure [ 'floor_id' ]} and complex_floors . complex_entrance_id = { $figure [ 'entrance_id' ]} ORDER BY position ASC
" );
$figure [ 'floor' ] = $this -> db -> fetch_assoc ( $sqlFloor );
}
unset ( $figure [ 'floor_id' ]);
}
if ( $useEntrance ) {
$figure [ 'entrance' ] = null ;
if ( $figure [ 'entrance_id' ]) {
$sqlEntrance = $this -> db -> query ( " SELECT * FROM complex_entrances WHERE id = { $figure [ 'entrance_id' ] } " );
$figure [ 'entrance' ] = $this -> db -> fetch_assoc ( $sqlEntrance );
}
unset ( $figure [ 'entrance_id' ]);
}
$result [] = $figure ;
}
}
return $result ;
}
public function addFacadeToHouse ( $house_id , $photo , $position , $hover_color , $opacity )
{
$sql = " INSERT INTO complex_house_facades SET house_id = { $house_id } , position = { $position } , hover_color = ' { $hover_color } ', opacity = ' { $opacity } ' " ;
$r = $this -> db -> query ( $sql , true );
$facade_id = $this -> db -> insert_id ();
$this -> addPhotoToFacade ( $photo , $facade_id );
$facade_sql = " SELECT * FROM complex_house_facades WHERE id = { $facade_id } " ;
$facade_r = $this -> db -> query ( $facade_sql , true );
$facade = $this -> db -> fetch_assoc ( $facade_r );
$facade [ 'is_published' ] = ( bool ) $facade [ 'is_published' ];
$facade [ 'figures' ] = [];
return $facade ;
}
public function addPhotoToFacade ( $photo , $facade_id )
{
$newPhotos = $this -> uploadPhotosToEntity ([ $photo ], " facades " , $facade_id );
$q = $this -> db -> query ( " DELETE FROM complex_facade_figures WHERE facade_id = { $facade_id } " ); // TODO
$result = '' ;
if ( count ( $newPhotos )) {
$image = $newPhotos [ 0 ];
$sql_in_image = " UPDATE complex_house_facades SET `image` = ' { $image [ 'url' ] } ', `name` = ' { $image [ 'name' ] } ' WHERE `id` = { $facade_id } " ;
$r = $this -> db -> query ( $sql_in_image , true );
$result = $image ;
}
return $result ;
}
public function updateHouseFacade ( $facade_id , $fields )
{
$this -> set_user ();
$strArray = [];
foreach ( $fields as $key => $value ) {
if ( $key == 'id' || ( empty ( $value ) && $value !== 0 && $value !== false )) {
continue ;
}
if ( is_string ( $value )) {
$strArray [] = " $key =' $value ' " ;
} else if ( is_bool ( $value )) {
$value = ( int ) $value ;
$strArray [] = " $key = $value " ;
} else {
$strArray [] = " $key = $value " ;
}
}
$str = implode ( ', ' , $strArray );
$sql = " UPDATE complex_house_facades SET $str WHERE id = { $facade_id } " ;
$this -> db -> query ( $sql );
$facade = $this -> db -> fetch_assoc ( $this -> db -> query ( " SELECT * from complex_house_facades WHERE id = { $facade_id } " ));
$facade [ 'is_published' ] = ( bool ) $facade [ 'is_published' ];
return $facade ;
}
public function updateFacadeFigure ( $figure_id , $fields )
{
$this -> set_user ();
$strArray = [];
foreach ( $fields as $key => $value ) {
if ( $key == 'id' || ( empty ( $value ) && $value !== 0 && $value !== false )) {
continue ;
}
if ( is_string ( $value )) {
$strArray [] = " $key =' $value ' " ;
} else if ( is_bool ( $value )) {
$value = ( int ) $value ;
$strArray [] = " $key = $value " ;
} else {
$strArray [] = " $key = $value " ;
}
}
$str = implode ( ', ' , $strArray );
$sql = " UPDATE complex_facade_figures SET $str WHERE id = { $figure_id } " ;
$this -> db -> query ( $sql );
$figure = $this -> db -> fetch_assoc ( $this -> db -> query ( " SELECT * from complex_facade_figures WHERE id = { $figure_id } " ));
$figure [ 'points' ] = json_decode ( $figure [ 'points' ]);
return $figure ;
}
public function addFacadeFigure ( $facade_id , $points )
{
$points = json_encode ( $points );
$sql = " INSERT INTO complex_facade_figures SET points = ' { $points } ', facade_id= { $facade_id } " ;
$q = $this -> db -> query ( $sql );
$id = $this -> db -> insert_id ();
$q = $this -> db -> query ( " SELECT * FROM complex_facade_figures WHERE id = $id " );
$figure = $this -> db -> fetch_assoc ( $q );
$figure [ 'points' ] = json_decode ( $figure [ 'points' ]);
return $figure ;
}
public function get_plan_rooms ( $plan_id , $has_token = false )
{
$result = array ();
if ( $plan_id > 0 ) {
// Get house_id based on plan_id
$house_id_sql = " SELECT ch.id as house_id
FROM complex_house_plans chp
JOIN complex_houses ch ON ch . id = chp . house_id
WHERE chp . id = { $plan_id }
LIMIT 1 " ;
$house_id_result = $this -> db -> query ( $house_id_sql );
$house_row = $this -> db -> fetch_assoc ( $house_id_result );
$house_id = ( int )( $house_row [ 'house_id' ] ? $house_row [ 'house_id' ] : 0 );
// Fetch installment plans for the house
$installment_plans = [];
if ( $house_id > 0 ) {
$installment_sql = " SELECT i.*, chi.end_date as house_installment_end_date
FROM installments i
INNER JOIN complex_house_installments chi ON chi . installment_id = i . id
WHERE chi . house_id = { $house_id }
AND i . is_archive = 0
AND ( chi . end_date IS NULL OR chi . end_date >= CURDATE ()) " ;
$installment_q = $this -> db -> query ( $installment_sql );
while ( $plan = $this -> db -> fetch_assoc ( $installment_q )) {
$installment_plans [] = [
'id' => $plan [ 'id' ],
'name' => $plan [ 'name' ],
'description' => $plan [ 'description' ],
'type' => $plan [ 'type' ],
'initial_payment' => $plan [ 'initial_payment' ],
'payment_period' => json_decode ( $plan [ 'payment_period' ], true ),
'allow_change_on_close' => $plan [ 'allow_change_on_close' ],
'interest_rate' => $plan [ 'interest_rate' ],
'comment' => $plan [ 'comment' ],
'house_installment_end_date' => $plan [ 'house_installment_end_date' ],
];
}
}
if ( $has_token ) {
if ( $this -> user -> agencyId == 20382 ) {
$filter_by_status = " " ;
} else {
$filter_by_status = " AND cs.status IN ('available', 'reservation') " ;
}
} else {
$filter_by_status = " " ;
}
$sql = " SELECT
room . id ,
room . number ,
room . area ,
room . kitchen_area ,
room . total_amount ,
room . installment_price ,
room . rooms_count ,
room . layout_feature ,
room . decoration_id ,
room . windows_placement_id ,
room . payment_types ,
room . type ,
MIN ( room . position ) AS position ,
MIN ( cs . name ) AS status_name ,
MIN ( cs . status ) AS status_type ,
MIN ( cs . color ) AS status_color ,
MIN ( c_house_p_i . url ) AS plan_url ,
MIN ( floors . position ) AS floor ,
entrances . name AS entrance_name ,
MIN ( ch . name ) AS house_name ,
MIN ( ch . parking ) AS house_parking ,
MIN ( ch . security ) AS house_security ,
MIN ( ch . fenced_area ) AS house_fenced_area ,
MIN ( ch . sports_ground ) AS sports_ground ,
MIN ( ch . play_ground ) AS play_ground ,
MIN ( ch . school ) AS school ,
MIN ( ch . kinder_garten ) AS kinder_garten ,
MIN ( ch . id ) AS house_id ,
MIN ( c_house_p . has_light_angle ) AS has_light_angle ,
MIN ( c_house_p . light_angle ) AS light_angle
FROM complex_rooms AS room
JOIN complex_rooms_plans rooms_plans ON rooms_plans . room_id = room . id
2026-07-15 09:58:57 +02:00
LEFT JOIN complex_house_plans_images c_house_p_i ON rooms_plans . plan_id = c_house_p_i . plan_id
2026-05-22 20:21:54 +02:00
LEFT JOIN complex_status cs ON room . complex_status_id = cs . id AND cs . is_archive = 0
JOIN complex_floors floors ON floors . id = room . floor_id
JOIN complex_entrances entrances ON entrances . id = floors . complex_entrance_id
JOIN complex_houses ch ON ch . id = entrances . complex_house_id
LEFT JOIN complex_house_plans c_house_p ON rooms_plans . plan_id = c_house_p . id
WHERE rooms_plans . plan_id = { $plan_id } { $filter_by_status }
GROUP BY room . id , entrances . name
ORDER BY MIN ( room . position ) " ;
$q = $this -> db -> query ( $sql );
while ( $room = $this -> db -> fetch_assoc ( $q )) {
$reservations = $this -> get_room_reservations ( $room [ 'id' ]);
unset ( $reservations [ 'can_change_queue' ]);
$complex_status_info = [
'status_name' => $room [ 'status_name' ],
'status_type' => $room [ 'status_type' ],
'status_color' => $room [ 'status_color' ]
];
unset ( $room [ 'status_name' ]);
unset ( $room [ 'status_type' ]);
unset ( $room [ 'status_color' ]);
if ( $room [ 'status_type' ] != 'reservation' && is_array ( $reservations ) && count ( $reservations ))
{
$complex_status_info = [
'status_name' => $reservations [ 0 ][ 'status_name' ],
'status_type' => $reservations [ 0 ][ 'status_type' ],
'status_color' => $reservations [ 0 ][ 'status_color' ],
];
}
$room [ 'complex_status_info' ] = $complex_status_info ;
// Add installment_plans
$room [ 'installment_plans' ] = $installment_plans ;
// Decode payment_types safely
if ( ! empty ( $room [ 'payment_types' ])) {
$decodedPaymentTypes = json_decode ( $room [ 'payment_types' ], true );
$room [ 'payment_types' ] = is_array ( $decodedPaymentTypes ) ? $decodedPaymentTypes : [];
} else {
$room [ 'payment_types' ] = [];
}
if ( in_array (( string ) $room [ 'id' ], $_SESSION [ 'to_send_complexes' ])) {
$room [ 'inPdf' ] = true ;
}
$result [] = $room ;
}
}
return $result ;
}
public function get_windows_placements ()
{
$result = array ();
$sql = " SELECT * FROM complex_rooms_windows_placements " ;
$q = $this -> db -> query ( $sql );
while ( $window = $this -> db -> fetch_assoc ( $q )) {
$result [] = $window ;
}
return $result ;
}
public function get_plans_images ( $plan_id )
{
$result = array ();
if ( $plan_id > 0 ) {
$sql = " SELECT * FROM complex_house_plans_images WHERE plan_id = { $plan_id } ORDER BY `position` " ;
$q = $this -> db -> query ( $sql );
while ( $res = $this -> db -> fetch_assoc ( $q )) {
$result [] = $res ;
}
}
return $result ;
}
public function complex_delete ( $complex_id )
{
$this -> deleteComplexFiles ( $complex_id );
$this -> db -> query ( " UPDATE complex_list SET deleted=1 WHERE id = { $complex_id } " );
return array ( 'result' => 'done' , 'complex_id' => $complex_id );;
}
public function delete_house ( $house_id )
{
$house_id = ( int ) $house_id ;
$sql = " UPDATE complex_houses SET deleted_at = NOW() WHERE id = { $house_id } " ;
$q = $this -> db -> query ( $sql );
return [
'status' => $q ,
'message' => $q ? 'Дом перемещен в корзину' : 'Ошибка при удалении дома' ,
'house_id' => $house_id
];
}
public function deleteComplexFiles ( $complex_id )
{
$this -> db -> query ( 'SET SESSION group_concat_max_len = 9999999;' );
$sql = $this -> db -> query ( " SELECT
complex_list . id AS complex_id ,
GROUP_CONCAT ( complex_house_floor_plans . image SEPARATOR ',' ) AS floor_plan_images ,
GROUP_CONCAT ( complex_house_plans_images . url SEPARATOR ',' ) AS room_plan_images ,
GROUP_CONCAT ( complex_house_images . url SEPARATOR ',' ) AS house_images ,
GROUP_CONCAT ( complex_house_facades . image SEPARATOR ',' ) AS house_facade_images ,
GROUP_CONCAT ( complex_images . image SEPARATOR ',' ) AS complex_images ,
GROUP_CONCAT ( complex_house_UTP . photo SEPARATOR ',' ) AS house_utp_images ,
GROUP_CONCAT ( complex_house_decoration . photo SEPARATOR ',' ) AS house_dec_images ,
GROUP_CONCAT ( complex_house_decoration . photo2 SEPARATOR ',' ) AS house_dec_images2 ,
GROUP_CONCAT ( complex_house_decoration . photo3 SEPARATOR ',' ) AS house_dec_images3 ,
GROUP_CONCAT ( complex_house_decoration . photo4 SEPARATOR ',' ) AS house_dec_images4 ,
GROUP_CONCAT ( complex_house_decoration . photo5 SEPARATOR ',' ) AS house_dec_images5 ,
GROUP_CONCAT ( complex_actions . image SEPARATOR ',' ) AS complex_actions_images
FROM complex_list
LEFT JOIN complex_houses ON complex_houses . complex_id = complex_list . id
LEFT JOIN complex_entrances ON complex_entrances . complex_house_id = complex_houses . id
LEFT JOIN complex_floors ON complex_floors . complex_entrance_id = complex_entrances . id
LEFT JOIN complex_floors_plans ON complex_floors_plans . floor_id = complex_floors . id
LEFT JOIN complex_house_floor_plans ON complex_house_floor_plans . id = complex_floors_plans . floor_plan_id
LEFT JOIN complex_rooms ON complex_rooms . floor_id = complex_floors . id
LEFT JOIN complex_rooms_plans ON complex_rooms_plans . room_id = complex_rooms . id
LEFT JOIN complex_house_plans_images ON complex_house_plans_images . plan_id = complex_rooms_plans . plan_id
LEFT JOIN complex_house_images ON complex_house_images . house_id = complex_houses . id
LEFT JOIN complex_house_facades ON complex_house_facades . house_id = complex_houses . id
LEFT JOIN complex_images ON complex_images . complex_id = complex_list . id
LEFT JOIN complex_house_UTP ON complex_house_UTP . house_id = complex_houses . id
LEFT JOIN complex_house_decoration ON complex_house_decoration . house_id = complex_houses . id
LEFT JOIN complex_actions ON complex_actions . complex_id = complex_list . id
WHERE complex_list . id = { $complex_id }
GROUP BY complex_list . id ; " );
$urls = [];
while ( $row = $this -> db -> fetch_assoc ( $sql )) {
$mergedArray = array_merge (
explode ( ',' , $row [ 'floor_plan_images' ]),
explode ( ',' , $row [ 'room_plan_images' ]),
explode ( ',' , $row [ 'house_images' ]),
explode ( ',' , $row [ 'house_facade_images' ]),
explode ( ',' , $row [ 'complex_images' ]),
explode ( ',' , $row [ 'house_utp_images' ]),
explode ( ',' , $row [ 'house_dec_images' ]),
explode ( ',' , $row [ 'house_dec_images2' ]),
explode ( ',' , $row [ 'house_dec_images3' ]),
explode ( ',' , $row [ 'house_dec_images4' ]),
explode ( ',' , $row [ 'house_dec_images5' ]),
explode ( ',' , $row [ 'complex_actions_images' ])
);
$mergedArray = array_filter ( $mergedArray );
$urls = array_merge (
$mergedArray ,
$urls
);
};
$this -> deleteFiles ( $urls );
}
public function deleteHouseFiles ( $house_id )
{
$this -> db -> query ( 'SET SESSION group_concat_max_len = 9999999;' );
$sql = $this -> db -> query ( " SELECT
complex_houses . id AS complex_house_id ,
GROUP_CONCAT ( complex_house_floor_plans . image SEPARATOR ',' ) AS floor_plan_images ,
GROUP_CONCAT ( complex_house_plans_images . url SEPARATOR ',' ) AS room_plan_images ,
GROUP_CONCAT ( complex_house_images . url SEPARATOR ',' ) AS house_images ,
GROUP_CONCAT ( complex_house_facades . image SEPARATOR ',' ) AS house_facade_images ,
GROUP_CONCAT ( complex_house_UTP . photo SEPARATOR ',' ) AS house_utp_images ,
GROUP_CONCAT ( complex_house_decoration . photo SEPARATOR ',' ) AS house_dec_images ,
GROUP_CONCAT ( complex_house_decoration . photo2 SEPARATOR ',' ) AS house_dec_images2 ,
GROUP_CONCAT ( complex_house_decoration . photo3 SEPARATOR ',' ) AS house_dec_images3 ,
GROUP_CONCAT ( complex_house_decoration . photo4 SEPARATOR ',' ) AS house_dec_images4 ,
GROUP_CONCAT ( complex_house_decoration . photo5 SEPARATOR ',' ) AS house_dec_images5
FROM complex_houses
LEFT JOIN complex_entrances ON complex_entrances . complex_house_id = complex_houses . id
LEFT JOIN complex_floors ON complex_floors . complex_entrance_id = complex_entrances . id
LEFT JOIN complex_floors_plans ON complex_floors_plans . floor_id = complex_floors . id
LEFT JOIN complex_house_floor_plans ON complex_house_floor_plans . id = complex_floors_plans . floor_plan_id
LEFT JOIN complex_rooms ON complex_rooms . floor_id = complex_floors . id
LEFT JOIN complex_rooms_plans ON complex_rooms_plans . room_id = complex_rooms . id
LEFT JOIN complex_house_plans_images ON complex_house_plans_images . plan_id = complex_rooms_plans . plan_id
LEFT JOIN complex_house_images ON complex_house_images . house_id = complex_houses . id
LEFT JOIN complex_house_facades ON complex_house_facades . house_id = complex_houses . id
LEFT JOIN complex_house_UTP ON complex_house_UTP . house_id = complex_houses . id
LEFT JOIN complex_house_decoration ON complex_house_decoration . house_id = complex_houses . id
WHERE complex_houses . id = { $house_id }
GROUP BY
complex_entrances . id ; " );
$urls = [];
while ( $row = $this -> db -> fetch_assoc ( $sql )) {
$mergedArray = array_merge (
explode ( ',' , $row [ 'floor_plan_images' ]),
explode ( ',' , $row [ 'room_plan_images' ]),
explode ( ',' , $row [ 'house_images' ]),
explode ( ',' , $row [ 'house_facade_images' ]),
explode ( ',' , $row [ 'house_utp_images' ]),
explode ( ',' , $row [ 'house_dec_images2' ]),
explode ( ',' , $row [ 'house_dec_images3' ]),
explode ( ',' , $row [ 'house_dec_images4' ]),
explode ( ',' , $row [ 'house_dec_images5' ])
);
$mergedArray = array_filter ( $mergedArray );
$urls = array_merge (
$mergedArray ,
$urls
);
};
$this -> deleteFiles ( $urls );
}
public function deleteEntranceFiles ( $entrance_id )
{
$this -> db -> query ( 'SET SESSION group_concat_max_len = 9999999;' );
$sql = $this -> db -> query ( " SELECT
complex_entrances . id AS entrance_id ,
GROUP_CONCAT ( complex_house_floor_plans . image SEPARATOR ',' ) AS floor_plan_images ,
GROUP_CONCAT ( complex_house_plans_images . url SEPARATOR ',' ) AS room_plan_images
FROM complex_entrances
LEFT JOIN complex_floors ON complex_floors . complex_entrance_id = complex_entrances . id
LEFT JOIN complex_floors_plans ON complex_floors_plans . floor_id = complex_floors . id
LEFT JOIN complex_house_floor_plans ON complex_house_floor_plans . id = complex_floors_plans . floor_plan_id
LEFT JOIN complex_rooms ON complex_rooms . floor_id = complex_floors . id
LEFT JOIN complex_rooms_plans ON complex_rooms_plans . room_id = complex_rooms . id
LEFT JOIN complex_house_plans_images ON complex_house_plans_images . plan_id = complex_rooms_plans . plan_id
WHERE complex_entrances . id = { $entrance_id }
GROUP BY
complex_entrances . id ; " );
$urls = [];
while ( $row = $this -> db -> fetch_assoc ( $sql )) {
$mergedArray = array_merge (
explode ( ',' , $row [ 'floor_plan_images' ]),
explode ( ',' , $row [ 'room_plan_images' ])
);
$mergedArray = array_filter ( $mergedArray );
$urls = array_merge (
$mergedArray ,
$urls
);
};
$this -> deleteFiles ( $urls );
}
public function deleteFloorFiles ( $floor_id )
{
$this -> db -> query ( 'SET SESSION group_concat_max_len = 9999999;' );
$sql = $this -> db -> query (
" SELECT
complex_floors . id AS floor_id ,
GROUP_CONCAT ( complex_house_floor_plans . image SEPARATOR ',' ) AS floor_plan_images ,
GROUP_CONCAT ( complex_house_plans_images . url SEPARATOR ',' ) AS room_plan_images
FROM complex_floors
LEFT JOIN complex_floors_plans ON complex_floors_plans . floor_id = complex_floors . id
LEFT JOIN complex_house_floor_plans ON complex_house_floor_plans . id = complex_floors_plans . floor_plan_id
LEFT JOIN complex_rooms ON complex_rooms . floor_id = complex_floors . id
LEFT JOIN complex_rooms_plans ON complex_rooms_plans . room_id = complex_rooms . id
LEFT JOIN complex_house_plans_images ON complex_house_plans_images . plan_id = complex_rooms_plans . plan_id
WHERE complex_floors . id = { $floor_id }
GROUP BY complex_floors . id ; "
);
$urls = [];
while ( $row = $this -> db -> fetch_assoc ( $sql )) {
$mergedArray = array_merge (
explode ( ',' , $row [ 'floor_plan_images' ]),
explode ( ',' , $row [ 'room_plan_images' ])
);
$mergedArray = array_filter ( $mergedArray );
$urls = array_merge (
$mergedArray ,
$urls
);
};
$this -> deleteFiles ( $urls );
}
public function delete_house_entrance ( $entrance_id )
{
$this -> set_user ();
$this -> deleteEntranceFiles ( $entrance_id );
$sql = " DELETE FROM complex_entrances WHERE id= { $entrance_id } " ;
$q = $this -> db -> query ( $sql );
return [ 'status' => $q ];
}
// TODO FIX DELETE ENTRIES WHILE DELETING THEIR PARENTS
public function delete_floor ( $floor_id )
{
$this -> set_user ();
$this -> deleteFloorFiles ( $floor_id );
$sql = " DELETE FROM complex_floors WHERE id= { $floor_id } " ;
$q = $this -> db -> query ( $sql );
// $sql = "DELETE FROM complex_rooms WHERE floor_id={$floor_id}";
// $q_ = $this->db->query($sql);
return [ 'status' => $q ];
}
public function delete_room ( $room_id )
{
$this -> set_user ();
$sql = " DELETE FROM complex_room_notes WHERE room_id= { $room_id } " ;
$this -> db -> query ( $sql );
$sql = " DELETE FROM complex_rooms_plans WHERE room_id= { $room_id } " ;
$this -> db -> query ( $sql );
$sql = " DELETE FROM complex_rooms WHERE id= { $room_id } " ;
$q = $this -> db -> query ( $sql );
return [ 'status' => $q ];
}
public function deleteFiles ( array $urls )
{
if ( empty ( $urls )) {
return false ;
}
$urls = array_map ( function ( $url ) {
return " (' $url ') " ;
}, $urls );
$urls = implode ( ',' , $urls );
$sql = " INSERT INTO job_delete_files (`url`) VALUES { $urls } " ;
$this -> db -> query ( $sql );
return true ;
// $Selectel = SelectelApi::getTokenAndUrl();
// $api = new SelectelApi();
// $token = $Selectel[0];
// $storageUrl = $Selectel[1];
// foreach ($urls as $url) {
// $parsed_url = parse_url($url);
// if (isset($parsed_url['path'])) {
// $api->deleteFile($storageUrl, $token, $parsed_url['path']);
// }
// }
}
public function deleteComplexPhoto ( $photo_id )
{
$r = $this -> db -> query ( " SELECT `image` FROM complex_images WHERE id = { $photo_id } " );
$row = $this -> db -> fetch_assoc ( $r );
$this -> deleteFiles ([ $row [ 'image' ]]);
$this -> db -> query ( " DELETE FROM complex_images WHERE id = { $photo_id } " , true );
return [ 'status' => true ];
}
public function deleteHousePhoto ( $photo_id )
{
$r = $this -> db -> query ( " SELECT `url` FROM complex_house_images WHERE id = { $photo_id } " );
$row = $this -> db -> fetch_assoc ( $r );
$this -> deleteFiles ([ $row [ 'url' ]]);
$this -> db -> query ( " DELETE FROM complex_house_images WHERE id = { $photo_id } " , true );
return [ 'status' => true ];
}
public function deleteHouseFacede ( $facade_id )
{
$r = $this -> db -> query ( " SELECT `image` FROM complex_house_facades WHERE id = { $facade_id } " );
$row = $this -> db -> fetch_assoc ( $r );
$this -> deleteFiles ([ $row [ 'image' ]]);
$q = $this -> db -> query ( " DELETE FROM complex_facade_figures WHERE facade_id = { $facade_id } " ); // TODO
$q = $this -> db -> query ( " DELETE FROM complex_house_facades WHERE `id` = { $facade_id } " );
return [ 'status' => true ];
}
public function deleteFacedeFigure ( $figure_id )
{
$q = $this -> db -> query ( " DELETE FROM complex_facade_figures WHERE id = { $figure_id } " ); // TODO
return [ 'status' => true , 'sql' => $q ];
}
public function deletePhotoFloorPlan ( $floor_plan_id )
{
$sql = " SELECT `image` FROM complex_house_floor_plans WHERE id = { $floor_plan_id } " ;
$r = $this -> db -> query ( $sql );
$row = $this -> db -> fetch_assoc ( $r );
$this -> deleteFiles ([ $row [ 'image' ]]);
}
public function delete_floor_plan_figure ( $figure_id )
{
$q = $this -> db -> query ( " DELETE FROM complex_floor_plan_figures WHERE id = { $figure_id } " ); // TODO
return [ 'status' => true ];
}
public function delete_floor_plan ( $floor_plan_id )
{
$q = $this -> db -> query ( " DELETE FROM complex_house_floor_plans WHERE id = { $floor_plan_id } " ); // TODO
$q = $this -> db -> query ( " DELETE FROM complex_floor_plan_figures WHERE floor_plan_id = { $floor_plan_id } " ); // TODO
$q = $this -> db -> query ( " DELETE FROM complex_floors_plans WHERE floor_plan_id = { $floor_plan_id } " ); // TODO
return [ 'status' => true ];
}
public function deleteHousePlans ( $plan_ids )
{
$plan_ids_str = implode ( ', ' , $plan_ids );
$filesToDelete = array ();
// die("SELECT `url` FROM complex_house_plans_images where plan_id in ({$plan_ids_str})");
$r = $this -> db -> query ( " SELECT `url` FROM complex_house_plans_images where plan_id in ( { $plan_ids_str } ) " );
while ( $res = $this -> db -> fetch_assoc ( $r )) {
$filesToDelete [] = $res [ 'url' ];
}
$this -> deleteFiles ( $filesToDelete );
$plans_sql = " DELETE FROM complex_house_plans where id in ( { $plan_ids_str } ) " ;
$images_sql = " DELETE FROM complex_house_plans_images where plan_id in ( { $plan_ids_str } ) " ;
$room_plans_sql = " DELETE FROM complex_rooms_plans where plan_id in ( { $plan_ids_str } ) " ;
$figures_sql = " UPDATE complex_floor_plan_figures SET room_plan_id = NULL WHERE room_plan_id in ( $plan_ids_str ) " ;
$this -> db -> query ( $figures_sql );
$this -> db -> query ( $plans_sql );
$this -> db -> query ( $images_sql );
$this -> db -> query ( $room_plans_sql );
return $plan_ids ;
}
public function deletePhotoFromRoomPlan ( $photo_id )
{
$res = $this -> db -> query ( " SELECT `url` FROM complex_house_plans_images where id = { $photo_id } " );
$photo = $this -> db -> fetch_assoc ( $res );
$sql = " DELETE FROM complex_house_plans_images where id = { $photo_id } " ;
$r = $this -> db -> query ( $sql );
$this -> deleteFiles ([ $photo [ 'url' ]]);
return [ 'success' => true ];
}
protected function parseCsv ( $input )
{
$possibleSeparators = [ ',' , ';' , " \t " , '|' ];
$separatorCounts = [];
$for_first_line = fopen ( 'php://memory' , 'rw' );
fwrite ( $for_first_line , $input );
fseek ( $for_first_line , 0 );
$firstLine = fgets ( $for_first_line );
fclose ( $for_first_line );
$temp = fopen ( 'php://memory' , 'rw' );
fwrite ( $temp , $input );
fseek ( $temp , 0 );
$res = array ();
foreach ( $possibleSeparators as $separator ) {
$columns = str_getcsv ( $firstLine , $separator );
$separatorCounts [ $separator ] = count ( $columns );
}
$mostLikelySeparator = array_search ( max ( $separatorCounts ), $separatorCounts );
while (( $data = fgetcsv ( $temp , null , $mostLikelySeparator )) !== false ) {
$res [] = $data ;
}
fclose ( $temp );
return $res ;
}
protected function endsWith ( $haystack , $needle ) {
$length = strlen ( $needle );
return $length > 0 ? substr ( $haystack , - $length ) === $needle : true ;
}
public function createRequisition ( $room_id = null , $requisition , $partner_id , $employee_id ){
$this -> set_user ();
$this -> set_users_ids ();
$phone = $requisition -> phone ;
$fio_client = $requisition -> fio ;
$opis = $requisition -> description ;
$partners = new Partners ( $this -> user -> agencyId );
$partner = $partners -> getPartner ( $partner_id );
$user_id = $user_id_client = $this -> user -> id ;
$confirm = 1 ;
$confirm_client = 1 ;
$who_work = ( int ) $partner [ 'who_work_req' ];
$who_work_client = ( int ) $partner [ 'who_work_client' ];
$funnel_id = ( int ) $partner [ 'funnel_id_req' ];
$funnel_id_client = ( int ) $partner [ 'funnel_id_client' ];
if ( $who_work == 0 ) {
$confirm = 0 ;
} else {
$user_id = $who_work ;
}
if ( $who_work_client == 0 ){
$confirm_client = 0 ;
} else {
$user_id_client = $who_work_client ;
}
$sql = " SELECT `id`, `stage`, `deleted`, `fio` FROM `clients` WHERE cancel=0 AND (phone = ' $phone ' OR id in (SELECT client_id FROM clients_phone2 WHERE phone = ' $phone ')) and (id_agent in ( " . implode ( ',' , $this -> userIds ) . " ) or who_work in ( " . implode ( ',' , $this -> userIds ) . " )) " ;
$client = $this -> db -> fetch_assoc ( $this -> db -> query ( $sql ));
if ( ! empty ( $client ) && $client ){
$client_id = ( int ) $client [ 'id' ];
//$fio_client = $client['fio'];
} else {
$sql = " INSERT INTO clients SET phone=' { $phone } ', fio=' { $fio_client } ', opis=' { $opis } ', employee_id=' { $employee_id } ', id_agent= { $user_id_client } , who_work= { $who_work_client } , date_add=NOW(), confirm= { $confirm_client } , funnel_id= { $funnel_id_client } , stage=1, integration=10 " ;
$this -> db -> query ( $sql );
$client_id = $this -> db -> insert_id ();
if ( $funnel_id_client > 0 ){
$Clients = new Clients ();
$Clients -> get_class_etap ( $client_id , $funnel_id_client );
}
}
$type_id = 1 ;
$name = $fio_client ;
$sql = " SELECT name FROM requisitions_type WHERE id = { $type_id } " ;
$q = $this -> db -> query ( $sql );
$r = $this -> db -> fetch_assoc ( $q );
$name = $r [ 'name' ] . ' для ' . $fio_client ;
if ( $client_id > 0 ){
$sql = " INSERT INTO requisitions SET
client_id = { $client_id },
name = '{$name}' ,
description = '{$opis}' ,
user_id = { $user_id },
who_work = { $who_work },
type_id = { $type_id },
confirm = { $confirm },
funnel_id = { $funnel_id },
stage = 1 ,
employee_id = { $employee_id }
" ;
if ( $room_id !== 0 ) {
$sql .= " , complex_room_id = { $room_id } " ;
}
$this -> db -> query ( $sql );
$req_id = $this -> db -> insert_id ();
if ( $funnel_id > 0 ){
$Requisitions = new Requisitions ();
$Requisitions -> get_class_etap ( $req_id , $funnel_id );
}
}
}
public function get_filter_fields ( $house_id = null , $complex_id = null )
{
$where = " " ;
if ( ! empty ( $house_id )) {
$house_id = ( int ) $house_id ;
$where = " complex_houses.`id` = { $house_id } " ;
} elseif ( ! empty ( $complex_id )) {
$complex_id = ( int ) $complex_id ;
$where = " complex_houses.`complex_id` = { $complex_id } " ;
} else {
return [
'total' => ( object )[ 'min' => null , 'max' => null ],
'area' => ( object )[ 'min' => null , 'max' => null ],
'kitchen_area' => ( object )[ 'min' => null , 'max' => null ],
'room_types' => [],
'decoration_types' => [],
'window_placements' => [],
'payment_types' => [],
];
}
$sql = " SELECT
JSON_OBJECT (
'min' , MIN ( c_rooms . total_amount ),
'max' , MAX ( c_rooms . total_amount )
) AS total ,
JSON_OBJECT (
'min' , MIN ( c_rooms . area ),
'max' , MAX ( c_rooms . area )
) AS area ,
JSON_OBJECT (
'min' , MIN ( c_rooms . kitchen_area ),
'max' , MAX ( c_rooms . kitchen_area )
) AS kitchen_area ,
GROUP_CONCAT ( DISTINCT c_rooms . type SEPARATOR ',' ) AS room_types ,
GROUP_CONCAT ( DISTINCT c_r_w_p . id SEPARATOR ',' ) AS window_placements ,
GROUP_CONCAT ( DISTINCT d_types . id SEPARATOR ',' ) AS decoration_types ,
GROUP_CONCAT ( DISTINCT apt . code SEPARATOR ',' ) AS payment_types
FROM
complex_houses
LEFT JOIN
complex_entrances AS c_entrances ON c_entrances . complex_house_id = complex_houses . id
LEFT JOIN
complex_floors AS c_floors ON c_floors . complex_entrance_id = c_entrances . id
LEFT JOIN
complex_house_facades AS facades ON facades . house_id = complex_houses . id AND facades . is_published != 0
LEFT JOIN
complex_facade_figures AS figures ON figures . facade_id = facades . id
LEFT JOIN
complex_floors_plans AS c_floor_plans ON c_floor_plans . floor_id = c_floors . id
LEFT JOIN
complex_rooms AS c_rooms ON c_rooms . floor_id = c_floors . id
LEFT JOIN
complex_rooms_plans AS c_rooms_plans ON c_rooms_plans . room_id = c_rooms . id
LEFT JOIN
complex_status AS cs ON cs . id = c_rooms . complex_status_id
LEFT JOIN
complex_rooms_windows_placements AS c_r_w_p ON c_r_w_p . id = c_rooms . windows_placement_id
LEFT JOIN
decoration_types AS d_types ON d_types . id = c_rooms . decoration_id
LEFT JOIN
apartment_payment_types AS apt ON JSON_CONTAINS ( c_rooms . payment_types , JSON_QUOTE ( apt . code ))
WHERE
{ $where }
AND ( cs . status = 'available' OR cs . status = 'reservation' )
AND c_rooms . id IS NOT NULL " ;
$q = $this -> db -> query ( $sql );
$fields = $this -> db -> fetch_assoc ( $q );
// Convert JSON strings to PHP objects
$fields [ 'total' ] = json_decode ( $fields [ 'total' ]);
$fields [ 'area' ] = json_decode ( $fields [ 'area' ]);
$fields [ 'kitchen_area' ] = json_decode ( $fields [ 'kitchen_area' ]);
// Process other fields safely
$fields [ 'room_types' ] = ! empty ( $fields [ 'room_types' ]) ? explode ( ',' , $fields [ 'room_types' ]) : [];
$fields [ 'decoration_types' ] = ! empty ( $fields [ 'decoration_types' ]) ? array_map ( 'intval' , explode ( ',' , $fields [ 'decoration_types' ])) : [];
$fields [ 'window_placements' ] = ! empty ( $fields [ 'window_placements' ]) ? array_map ( 'intval' , explode ( ',' , $fields [ 'window_placements' ])) : [];
$fields [ 'payment_types' ] = ! empty ( $fields [ 'payment_types' ]) ? array_filter ( explode ( ',' , $fields [ 'payment_types' ])) : [];
return $fields ;
}
public function get_frame_access ( $token ) {
$sql = " SELECT * FROM complexes_frame cf WHERE cf.token = ' $token ' AND cf.end_date >= NOW() " ;
$query = $this -> db -> query ( $sql );
$result = $this -> db -> fetch_assoc ( $query );
if ( $result ) {
return [
'access' => true ,
'agency_id' => $result [ 'agency_id' ],
];
} else {
return [ 'access' => 'denied' ];
}
}
public function get_frame_colors ( $token ) {
$sql = " SELECT cf.frame_color, cf.color_reserved, cf.color_free FROM complexes_frame cf WHERE cf.token = ' $token ' " ;
$query = $this -> db -> query ( $sql );
$colors = $this -> db -> fetch_assoc ( $query );
return $colors ;
}
public function create_frame_requisition ( $data ) {
$token = $data [ 'token' ];
$full_name = $data [ 'full_name' ];
$phone_number = $data [ 'phone_number' ];
$sql = " SELECT cf.agency_id, cf.client_funnel_id, cf.req_funnel_id FROM complexes_frame cf WHERE cf.token = ' $token ' " ;
$query = $this -> db -> query ( $sql );
$funnels = $this -> db -> fetch_assoc ( $query );
$agency_id = $funnels [ 'agency_id' ];
$client_funnel_id = $funnels [ 'client_funnel_id' ];
$requisition_funnel_id = $funnels [ 'req_funnel_id' ];
$confirm = 1 ;
$complex_name = $data [ 'complex_name' ];
$house_name = $data [ 'house_name' ];
$entrance_name = $data [ 'entrance_name' ];
$room_id = $data [ 'room_number' ];
$description = " Заявка с каталога комплексов по объекту в { $complex_name } , { $house_name } , { $entrance_name } , № кв { $room_id } " ;
// Добавляем клиента
$client_sql = " INSERT INTO clients (`fio`, `phone`, `opis`, `id_agent`, `date_add`, `who_work`, `confirm`, `funnel_id`)
VALUES ( '$full_name' , '$phone_number' , '$description' , '$agency_id' , NOW (), '$agency_id' , '$confirm' , '$client_funnel_id' ) " ;
$this -> db -> query ( $client_sql );
$new_client_id = $this -> db -> insert_id ();
// Добавляем заявку
$requisition_sql = " INSERT INTO requisitions (`name`, `user_id`, `client_id`, `who_work`, `type_id`, `description`, `stage`, `funnel_id`)
VALUES ( 'Подбор объекта для $full_name' , '$agency_id' , '$new_client_id' , '$agency_id' , 1 , '$description' , 1 , '$requisition_funnel_id' ) " ;
$this -> db -> query ( $requisition_sql );
}
public function getComplexNamesForIframe ( $use_empty_rooms = false , $page = 1 )
{
$limit = 10 ;
$offset = ( $page - 1 ) * $limit ;
$result = array ();
$this -> set_user ();
$this -> set_users_ids ();
// Формируем SQL-запрос
if ( $use_empty_rooms ) {
$sql = " SELECT id, `name`
FROM complex_list
WHERE agency_id = { $this -> user -> agencyId }
AND complex_list . arhive = 0
AND complex_list . deleted = 0 " ;
} else {
$sql = " SELECT complex_list.id, complex_list.name
FROM complex_list
LEFT JOIN complex_houses ON complex_houses . complex_id = complex_list . id
LEFT JOIN complex_entrances complex_entrances ON complex_entrances . complex_house_id = complex_houses . id
LEFT JOIN complex_floors complex_floors ON complex_floors . complex_entrance_id = complex_entrances . id
LEFT JOIN complex_rooms complex_rooms ON complex_rooms . floor_id = complex_floors . id
WHERE complex_list . agency_id = { $this -> user -> agencyId }
AND complex_list . arhive = 0
AND complex_list . deleted = 0
AND complex_houses . id IS NOT NULL
AND complex_rooms . id IS NOT NULL
GROUP BY complex_list . id
HAVING COUNT ( complex_houses . id ) > 0 AND COUNT ( complex_rooms . id ) > 0 " ;
}
// Для подсчёта общего количества записей
$count_sql = " SELECT COUNT(*) as count FROM ( $sql ) AS subquery " ;
// Добавляем LIMIT и OFFSET для основного запроса
$sql .= " ORDER BY id DESC LIMIT { $limit } OFFSET { $offset } " ;
// Выполняем основной запрос
$query = $this -> db -> query ( $sql );
while ( $row = $this -> db -> fetch_assoc ( $query )) {
$result [] = $row ;
}
// Выполняем запрос на подсчёт общего числа записей
$count_query = $this -> db -> query ( $count_sql );
$count_row = $this -> db -> fetch_assoc ( $count_query );
$total = ( int ) $count_row [ 'count' ];
$allPages = ceil ( $total / $limit );
return [
'list' => $result ,
'total' => $total ,
'allPages' => $allPages
];
}
public function searchForIframe ( $filter , $use_empty_rooms = false )
{
$whereComplex = '' ;
$whereRoom = '' ;
$whereAddress = '' ;
$whereHouse = '' ;
$whereFloor = '' ;
$priceFilterKey = ' complex_rooms.total_amount ' ;
$havingComplex = " " ;
if ( ! $use_empty_rooms ) {
$havingComplex .= " HAVING COUNT(complex_houses.id) > 0 AND COUNT(complex_rooms.id) > 0 " ;
$whereComplex .= " AND complex_houses.id IS NOT NULL AND complex_rooms.id IS NOT NULL " ;
// $whereHouse .= " AND COUNT(complex_rooms.id) > 0 ";
}
if ( $filter ) {
if ( ! empty ( $filter -> selectedDecorations )) {
$whereRoom .= " AND complex_rooms.decoration_id in ( " . implode ( ',' , $filter -> selectedDecorations ) . " ) " ;
}
if ( ! empty ( $filter -> selectedTypes )) {
$whereRoom .= " AND complex_rooms.type in (' " . implode ( '\',\'' , $filter -> selectedTypes ) . " ') " ;
}
if ( ! empty ( $filter -> rooms )) {
$isMoreThenFive = in_array ( '5-more' , $filter -> rooms );
$isSelectedStudio = in_array ( 'studio' , $filter -> rooms );
$filteredArray = array_filter ( $filter -> rooms , function ( $element ) {
return ! in_array ( $element , [ " 5-more " , " studio " ]);
});
if ( $isSelectedStudio ) {
$whereRoom .= " AND complex_rooms.layout_feature = 'studio' " ;
}
if ( count ( $filteredArray )) {
if ( $isMoreThenFive ) {
$whereRoom .= " AND (complex_rooms.rooms_count >= 5 OR complex_rooms.rooms_count IN ( " . implode ( ',' , $filteredArray ) . " )) " ;
} else {
$whereRoom .= " AND complex_rooms.rooms_count IN ( " . implode ( ',' , $filteredArray ) . " ) " ;
}
} else if ( $isMoreThenFive ) {
$whereRoom .= " AND complex_rooms.rooms_count >= 5 " ;
}
}
if ( ! empty ( $filter -> rayons )) {
$whereComplex .= " AND ( " ;
foreach ( $filter -> rayons as $index => $rayon ) {
$whereComplex .= " complex_address.rayon LIKE '% { $rayon } %' " ;
if ( isset ( $filter -> rayons [ $index + 1 ])) {
$whereComplex .= " OR " ;
}
}
$whereComplex .= " ) " ;
// var_dump($whereAddress);die;
}
if ( ! empty ( $filter -> selectedMetros )) {
$whereComplex .= " AND complex_metro.metro_id in ( " . implode ( ',' , $filter -> selectedMetros ) . " ) " ;
}
if ( ! empty ( $filter -> complexes )) {
$whereComplex .= " AND complex_list.id in ( " . implode ( ',' , $filter -> complexes ) . " ) " ;
}
if ( ! empty ( $filter -> address )) {
$whereComplex .= " AND complex_address.address like '% { $filter -> address } %' " ;
}
if ( ! empty ( $filter -> squareKitchen_min )) {
$whereRoom .= " AND complex_rooms.kitchen_area >= { $filter -> squareKitchen_min } " ;
}
if ( ! empty ( $filter -> squareKitchen_max )) {
$whereRoom .= " AND complex_rooms.kitchen_area <= { $filter -> squareKitchen_max } " ;
}
if ( ! empty ( $filter -> area_from )) {
$whereRoom .= " AND complex_rooms.area >= { $filter -> area_from } " ;
}
if ( ! empty ( $filter -> area_to )) {
$whereRoom .= " AND complex_rooms.area <= { $filter -> area_to } " ;
}
if ( filter_var ( $filter -> useSquarePrice , FILTER_VALIDATE_BOOLEAN )) {
$priceFilterKey = " complex_rooms.total_amount / complex_rooms.area " ;
}
if ( ! empty ( $filter -> price_from )) {
$whereRoom .= " AND { $priceFilterKey } >= { $filter -> price_from } " ;
}
if ( ! empty ( $filter -> price_to )) {
$whereRoom .= " AND { $priceFilterKey } <= { $filter -> price_to } " ;
}
if ( ! empty ( $filter -> floor_from )) {
$whereFloor .= " AND complex_floors.position >= { $filter -> floor_from } " ;
}
if ( ! empty ( $filter -> floor_to )) {
$whereFloor .= " AND complex_floors.position <= { $filter -> floor_to } " ;
}
if ( ! empty ( $filter -> selectedComplexTypes )) {
$whereComplex .= " AND complex_list.type in (' " . implode ( '\',\'' , $filter -> selectedComplexTypes ) . " ') " ;
}
if ( ! empty ( $filter -> period )) {
if ( $filter -> period == 'completed' ) {
$currentMonth = date ( 'n' );
$currentYear = date ( 'Y' );
$currentQuarter = ceil ( $currentMonth / 3 );
$whereHouse .= " AND complex_houses.deadline_quarter <= $currentQuarter AND complex_houses.deadline_year <= $currentYear " ;
} else {
list ( $year , $quarter ) = explode ( 'Q' , $filter -> period );
$whereHouse .= " AND complex_houses.deadline_quarter = $quarter AND complex_houses.deadline_year = $year " ;
}
}
if ( ! empty ( $filter -> is_partner_show )){
$whereHouse .= " AND complex_houses.is_partner_show = 1 " ;
}
// if (!empty($filter->is_archive)) {
// $whereComplex .= " AND complex_list.arhive = 1 ";
// } else {
// $whereComplex .= " AND complex_list.arhive = 0 ";
// }
// Фильтрация по способам оплаты
if ( ! empty ( $filter -> selectedPaymentTypes )) {
$conditions = [];
foreach ( $filter -> selectedPaymentTypes as $pt ) {
$conditions [] = " complex_rooms.payment_types LIKE '% \" { $pt } \" %' " ;
}
if ( ! empty ( $conditions )) {
$whereRoom .= " AND ( " . implode ( ' OR ' , $conditions ) . " ) " ;
}
// Installment-specific filtering
if ( in_array ( 'INSTALLMENT' , $filter -> selectedPaymentTypes )) {
$whereRoom .= " AND EXISTS (
SELECT 1
FROM complex_house_installments chi
JOIN complex_entrances ce ON ce . complex_house_id = chi . house_id
JOIN complex_floors cf ON cf . complex_entrance_id = ce . id
JOIN installments i ON i . id = chi . installment_id
WHERE cf . id = complex_rooms . floor_id
AND i . is_archive = 0 "
. ( ! empty ( $filter -> selectedInstallments )
? " AND chi.installment_id IN ( " . implode ( ',' , $filter -> selectedInstallments ) . " ) "
: " " )
. (( isset ( $filter -> initialPayment ) && is_numeric ( $filter -> initialPayment ))
? " AND complex_rooms.installment_price IS NOT NULL AND complex_rooms.installment_price > 0 AND ((i.initial_payment / 100.0) * complex_rooms.installment_price) <= " . ( float ) $filter -> initialPayment
: " " )
. (( isset ( $filter -> paymentTerm ) && is_numeric ( $filter -> paymentTerm ))
? " AND (DATEDIFF(chi.end_date, CURDATE()) / 30.44) >= " . ( float ) $filter -> paymentTerm
: " " )
. (( isset ( $filter -> installmentPrice -> min ) && is_numeric ( $filter -> installmentPrice -> min ))
? " AND complex_rooms.installment_price >= " . ( float ) $filter -> installmentPrice -> min
: " " )
. (( isset ( $filter -> installmentPrice -> max ) && is_numeric ( $filter -> installmentPrice -> max ))
? " AND complex_rooms.installment_price <= " . ( float ) $filter -> installmentPrice -> max
: " " )
. " ) " ;
}
}
}
$whereComplex .= " AND complex_list.arhive = 0 " ;
$this -> limit = 10 ;
$limitSqlComolex = " limit { $this -> limit } " ;
$this -> set_user ();
$this -> set_users_ids ();
if ( $this -> page > 0 ) {
$limitSqlComolex = ' limit ' . ( $this -> page - 1 ) * $this -> limit . ', ' . $this -> limit ;
}
if ( $this -> user -> agencyId == 20382 ) {
$filter_by_status = " " ;
} else {
$filter_by_status = " AND cs.status IN ('available', 'reservation') " ;
}
// var_dump($limitSqlComolex);die;
$result = array ();
$sql_total = " SELECT count(DISTINCT complex_list.id) as total, count( DISTINCT complex_houses.id) as houses_total, COUNT(DISTINCT complex_rooms.id) as total_rooms FROM complex_list
LEFT JOIN complex_houses ON complex_houses . complex_id = complex_list . id AND ( complex_houses . deleted_at IS NULL OR complex_houses . deleted_at = '0000-00-00 00:00:00' ) { $whereHouse }
LEFT JOIN complex_metro ON complex_metro . complex_id = complex_list . id
LEFT JOIN complex_address ON complex_address . complex_id = complex_list . id
LEFT JOIN complex_entrances complex_entrances ON complex_entrances . complex_house_id = complex_houses . id
LEFT JOIN complex_floors complex_floors ON complex_floors . complex_entrance_id = complex_entrances . id { $whereFloor }
LEFT JOIN complex_rooms complex_rooms ON complex_rooms . floor_id = complex_floors . id { $whereRoom }
LEFT JOIN complex_status cs ON complex_rooms . complex_status_id = cs . id AND cs . is_archive = 0
WHERE complex_list . agency_id = { $this -> user -> agencyId }
AND complex_list . deleted = 0
{ $filter_by_status }
{ $whereComplex }
{ $havingComplex }
ORDER BY complex_list . id DESC
" ;
$q_total = $this -> db -> query ( $sql_total );
$result [ 'total' ] = ( int ) $this -> db -> fetch_assoc ( $q_total )[ 'total' ];
$sql = " SELECT complex_list.*, count( DISTINCT complex_houses.id) as houses_total, COUNT(DISTINCT complex_rooms.id) as total_rooms, MIN(complex_rooms.total_amount) AS min_total_amount FROM complex_list
LEFT JOIN complex_houses ON complex_houses . complex_id = complex_list . id AND ( complex_houses . deleted_at IS NULL OR complex_houses . deleted_at = '0000-00-00 00:00:00' ) { $whereHouse }
LEFT JOIN complex_metro ON complex_metro . complex_id = complex_list . id
LEFT JOIN complex_address ON complex_address . complex_id = complex_list . id
LEFT JOIN complex_entrances complex_entrances ON complex_entrances . complex_house_id = complex_houses . id
LEFT JOIN complex_floors complex_floors ON complex_floors . complex_entrance_id = complex_entrances . id { $whereFloor }
LEFT JOIN complex_rooms complex_rooms ON complex_rooms . floor_id = complex_floors . id { $whereRoom }
LEFT JOIN complex_status cs ON complex_rooms . complex_status_id = cs . id AND cs . is_archive = 0
WHERE complex_list . agency_id = { $this -> user -> agencyId }
AND complex_list . deleted = 0
{ $filter_by_status }
{ $whereComplex }
GROUP BY complex_list . id
{ $havingComplex }
ORDER BY complex_list . id DESC { $limitSqlComolex }
" ;
$q = $this -> db -> query ( $sql );
// , MIN(complex_rooms.total_amount) AS min_total_amount
// echo '<pre>';
// print_r($q->queryString);
// echo '</pre>';
// die();
// var_dump($q);die;
// $result['total'] = $this->db->num_rows($q);
// var_dump('test');die;
$result [ 'allPages' ] = ceil ( $result [ 'total' ] / $this -> limit );
$result [ 'agency_name' ] = $this -> user -> agencyName ;
$result [ 'agency_logo' ] = $this -> user -> photo ;
$result [ 'agency_phone' ] = $this -> user -> agencyPhone ;
// var_dump($result['agency_phone']);die;
// var_dump($this->user);die;
// var_dump($result);die;
while ( $r = $this -> db -> fetch_assoc ( $q )) {
$result [ 'list' ][ 'complex_' . $r [ 'id' ]] = $this -> get_complex_one ( $r [ 'id' ], true , false );
$result [ 'list' ][ 'complex_' . $r [ 'id' ]][ 'houses_total' ] = $r [ 'houses_total' ];
$result [ 'list' ][ 'complex_' . $r [ 'id' ]][ 'total_rooms' ] = $r [ 'total_rooms' ];
$result [ 'list' ][ 'complex_' . $r [ 'id' ]][ 'min_total_amount' ] = $r [ 'min_total_amount' ];
// var_dump($r);die;
}
$result [ 'debug' ][ 'sql' ] = $q ;
// var_dump($result);die;
return $result ;
}
private function generateUniqueColor ( $house_id )
{
$colors = [
'#F44336' , // red
'#E91E63' , // pink
'#9C27B0' , // purple
'#673AB7' ,
'#3F51B5' ,
'#2196F3' ,
'#03A9F4' ,
'#00BCD4' ,
'#009688' ,
'#4CAF50' ,
'#8BC34A' ,
'#CDDC39' ,
'#FFC107' ,
'#FF9800' ,
'#FF5722'
];
// get used colors
$sql = " SELECT color FROM complex_house_media_set WHERE complex_house_id = { $house_id } " ;
$q = $this -> db -> query ( $sql );
$used = [];
while ( $row = $this -> db -> fetch_assoc ( $q )) {
$used [] = $row [ 'color' ];
}
// find unused
foreach ( $colors as $color ) {
if ( ! in_array ( $color , $used )) {
return $color ;
}
}
// fallback → random color
return sprintf ( '#%06X' , mt_rand ( 0 , 0xFFFFFF ));
}
public function findUser ( $sessionId )
{
$userSql = " SELECT id, agency, users_admin, role_developer FROM users where id= { $sessionId } " ;
$query = $this -> db -> query ( $userSql );
return $this -> db -> fetch_assoc ( $query );
}
public function getMediaThumbnails ( array $mediaIds )
{
if ( empty ( $mediaIds )) {
return [];
}
// Sanitize IDs (ensure integers)
$mediaIds = array_map ( 'intval' , $mediaIds );
$idsList = implode ( ',' , $mediaIds );
$sql = " SELECT id, thumbnail_path
FROM complex_house_media
WHERE id IN ( $idsList ) " ;
$query = $this -> db -> query ( $sql );
$results = [];
while ( $row = $this -> db -> fetch_assoc ( $query )) {
$results [] = [
'id' => $row [ 'id' ],
'thumbnail' => ! empty ( $row [ 'thumbnail_path' ])
? 'https://data.joywork.ru' . $row [ 'thumbnail_path' ]
: null
];
}
return $results ;
}
public function findHouseComplexAgency ( $homeId )
{
$sql = "
SELECT cl . agency_id
FROM complex_houses ch
JOIN complex_list cl ON cl . id = ch . complex_id
WHERE ch . id = { $homeId }
" ;
$query = $this -> db -> query ( $sql );
$result = $this -> db -> fetch_assoc ( $query );
return isset ( $result [ 'agency_id' ]) && $result [ 'agency_id' ] ? $result [ 'agency_id' ] : null ;
}
}