Base Directory:
/home/ecedu/public_html/new/service
View File: loadMoreNews.php
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
header('Content-Type: application/json');
require_once __DIR__ . '/../Models/NewsModel.php';
$repo = new NewsModel();
// التحقق من المدخلات
$lang = in_array($_GET['lang'] ?? 'ar', ['ar', 'ku', 'en']) ? $_GET['lang'] : 'ar';
$search = trim((string)($_GET['search'] ?? ''));
$typeId = (int)($_GET['typeId'] ?? 0);
$offset = max(0, (int)($_GET['offset'] ?? 0));
$limit = 10;
// التحقق من وجود معايير بحث صالحة
if ($typeId <= 0 && $search === '') {
http_response_code(400);
echo json_encode(['error' => 'يجب توفير إما typeId أو search'], JSON_UNESCAPED_UNICODE);
exit;
}
$total = 0;
$newsList = [];
$table = '';
try {
if ($typeId > 0) {
$table = $repo->getTableName($typeId);
$total = $repo->getCountByType($typeId);
$newsList = $repo->getListNewsByType($typeId, $limit, $offset);
} else {
$total = $repo->getCountByText($search, $lang);
$newsList = $repo->getListNewsByText($search, $lang, $limit, $offset);
}
} catch (Throwable $e) {
http_response_code(500);
echo json_encode(['error' => $e->getMessage()], JSON_UNESCAPED_UNICODE);
exit;
}
/**
* ترجمة الحقل حسب اللغة المطلوبة
*/
function localize(array $row, string $lang, string $base): string
{
$suffix = $lang === 'ku' ? '1' : ($lang === 'en' ? '2' : '');
$key = $base . $suffix;
return $row[$key] ?? $row[$base] ?? '';
}
/**
* تقصير النص مع الحفاظ على الكلمات كاملة
*/
function snippet(string $text, int $max): string
{
$clean = strip_tags($text);
if (mb_strlen($clean) <= $max) {
return $clean;
}
$cut = mb_strrpos($clean = mb_substr($clean, 0, $max), ' ');
return mb_substr($clean, 0, $cut ?: $max) . ' …';
}
/**
* بناء صف البيانات للعرض
*/
function buildNewsRow(array $n, string $lang, string $table, int $type): array
{
// تنظيف اسم الجدول لاستخدامه في مسار الصورة
$cleanTable = preg_replace('/[^a-zA-Z0-9_]/', '', $table);
return [
'id' => (int)($n['news_id'] ?? 0),
'type' => $type,
'type_id' => (int)($n['type_id'] ?? 0),
'title' => localize($n, $lang, 'news_title'),
'description' => snippet(localize($n, $lang, 'news_description'), 300),
'image' => "service/images/news/{$cleanTable}/img_{$n['news_id']}." . ($n['img_ext'] ?? 'jpg'),
'author' => $n['author'] ?? '',
'date' => date('Y-m-d', strtotime($n['news_date'] ?? 'now')),
'date_raw' => $n['news_date'] ?? date('Y-m-d H:i:s'),
];
}
// بناء البيانات للواجهة
$rows = [];
foreach ($newsList as $newsItem) {
$rows[] = buildNewsRow($newsItem, $lang, $table,$typeId);
}
echo json_encode(
['total' => $total, 'rows' => $rows],
JSON_UNESCAPED_UNICODE | JSON_NUMERIC_CHECK
);
exit;