Priority File Manager

📁 public_html
Base Directory:
/home/ecedu/public_html/cce/Views/layouts
NameTypeSizeActions
📁 .. Folder -
📄 aboutus-layout.php File 1676
Edit Download
📄 article-layout.php File 21975
Edit Download
📄 back-top.php File 706
Edit Download
📄 body-layout.php File 1313
Edit Download
📄 contactus-layout.php File 4025
Edit Download
📄 department-layout.php File 3736
Edit Download
📄 footer-layout.php File 5862
Edit Download
📄 header-layout.php File 451
Edit Download
📄 header-second.php File 827
Edit Download
📄 index-layout.php File 4027
Edit Download
📄 list-languages.php File 5393
Edit Download
📄 list-news-layout.php File 6488
Edit Download
📄 list-pdf-layout.php File 4459
Edit Download
📄 main-func.php File 59102
Edit Download
📄 main-layout.php File 8313
Edit Download
📄 main-menu.php File 3613
Edit Download
📄 mobile-menu.php File 5453
Edit Download
📄 mobile-side.php File 14998
Edit Download
📄 pdf-layout.php File 3
Edit Download
📄 right_sidebar.php File 3970
Edit Download
📄 search-layout.php File 5408
Edit Download
📄 top-menu.php File 1175
Edit Download
📄 top_slider.php File 2320
Edit Download

View File: main-func.php

<?php
header('Content-Type: text/html; charset=utf-8'); 
require_once __DIR__ . '/../../Models/Functions.php';
$functions = new Functions();  
// -------------------------------------
// 1) ضبط اللغة والاتجاه والقيم الأولية
// -------------------------------------
$lang = $_GET['lang'] ?? 'ar';
$theme = ($lang == 'ar' || $lang == 'ku') ? 'theme-rtl' : 'theme';
$dir   = ($lang == 'ar' || $lang == 'ku') ? 'rtl' : 'ltr';

$langNames = [
    'ar' => 'عربي',
    'ku' => 'کوردی',
    'en' => 'English',
];
 

$tables = getTables();

$currentLangName = isset($langNames[$lang]) ? $langNames[$lang] : 'English'; 

// -------------------------------------
// 2) توليد أسماء الجداول تلقائياً
// -------------------------------------

// ———– طريقة 1: إذا كنت تعرف عدد الجداول الثابت مسبقاً
// -------------------------------------
// 2) تعريف باقي المتغيرات والمصفوفات
// ------------------------------------- 
// نص من نحن - افتراضياً فارغ، قد يعبأ من قاعدة البيانات.

// تهيئة المتغيرات الافتراضية
$type_id = 0;

$_aboutus = '';
$aboutus  = '';
$aboutus1 = '';
$aboutus2 = '';

$_contactus = '';
$contactus  = '';
$contactus1 = '';
$contactus2 = '';

$address = '';

$social = array_fill(1, 4, '');  // للمواقع الاجتماعية
$logo   = [];                   // للشعارات
$ads_url1 = '';
$ads_img1 = '';

$details_title         = '';
$details1_title        = '';
$details2_title        = '';
$details_description   = '';
$details1_description  = '';
$details2_description  = '';

$news_path = "service/images/news/";

// 1) محتوى "من نحن"
if (!empty($editorialData) && is_array($editorialData)) {
    $aboutus  = $editorialData['text_description']   ?? '';
    $aboutus1 = $editorialData['text_description1']  ?? '';
    $aboutus2 = $editorialData['text_description2']  ?? '';

    switch ($lang) {
        case 'ku':
            $_aboutus = $aboutus1 !== '' ? $aboutus1 : $aboutus;
            break;
        case 'en':
            $_aboutus = $aboutus2 !== '' ? $aboutus2 : $aboutus;
            break;
        default:
            $_aboutus = $aboutus;
    }
}

// 2) محتوى "اتصل بنا"
if (!empty($contactusData) && is_array($contactusData)) {
    $contactus  = $contactusData['text_description']   ?? '';
    $contactus1 = $contactusData['text_description1']  ?? '';
    $contactus2 = $contactusData['text_description2']  ?? '';

    switch ($lang) {
        case 'ku':
            $_contactus = $contactus1 !== '' ? $contactus1 : $contactus;
            break;
        case 'en':
            $_contactus = $contactus2 !== '' ? $contactus2 : $contactus;
            break;
        default:
            $_contactus = $contactus;
    }
}

// 3) بيانات التواصل الاجتماعي
if (!empty($socialData) && is_array($socialData)) {
    foreach ($socialData as $idx => $item) {
        $key = $idx + 1;
        if ($key >= 1 && $key <= 4) {
            $social[$key] = $item['text_description'] ?? '';
        }
    }
}
$social1 = $social[1];
$social2 = $social[2];
$social3 = $social[3];
$social4 = $social[4];

// 4) الشعارات
if (!empty($imageData) && is_array($imageData)) {
    foreach ($imageData as $img) {
        $tid = $img['type_id'] ?? null;
        $id  = $img['img_id']   ?? '';
        $ext = $img['img_ext']  ?? '';
        if ($tid && $id && $ext) {
            $logo[$tid] = "service/images/header/img_{$id}.{$ext}";
        }
    }
}
$logo1 = $logo[1] ?? '';
$logo2 = $logo[2] ?? '';
$logo3 = $logo[3] ?? '';
$logo4 = $logo[4] ?? '';

// 5) إعلانات
if (!empty($adsData) && is_array($adsData)) {
    foreach ($adsData as $ad) {
        if (($ad['type_id'] ?? null) == 1) {
            $ads_url1 = !empty($ad['img_url']) ? $ad['img_url'] : '#';
            $id  = $ad['img_id']  ?? '';
            $ext = $ad['img_ext'] ?? '';
            $ads_img1 = "service/images/ads/img_{$id}.{$ext}";
        }
    }
}
$site_title=$L['site_title'];

// معلومات عامة عن الموقع
$siteInfo = [
    'logo'      => $logo1,
    'address'   => 'العراق – بغداد – الوزيرية – قرب المعهد القضائي',
    'address1'  => 'عێراق – بەغداد – الوزیریە – نزیک ئەنجومەنی دادوەری',
    'address2'  => 'Iraq – Baghdad – Al-Waziriyah – Near the Judicial Institute', 
    'phone'     => '',//'+(123) 456-7890',
    'email'     => 'ec@ec.edu.iq',
];

 $address= $siteInfo['address'];
if($lang=="ku") $address= $siteInfo['address1'];
if($lang=="en") $address= $siteInfo['address2'];

// روابط الصفحات الثابتة في شريط الحقوق
$footerPages = [
    ['aboutus.php',      $L['about_us']],
    ['contactus.php',    $L['contact_us']],
    ['term-of-use.html',   $L['term_of_use'] ],
    ['privacy-policy.html',$L['privacy']   ],
];

 $socialPlatforms = [
    11 => [
        'url'  => !empty($social1) ? $social1 : 'https://facebook.com',
        'icon' => 'facebook',
        'name' => !empty($L['facebook']) ? $L['facebook'] : 'Facebook'
    ],
    12 => [
        'url'  => !empty($social2) ? $social2 : 'https://x.com/',
        'icon' => 'telegram',
        'name' => !empty($L['telegram']) ? $L['telegram'] : 'telegram'
    ],
    13 => [
        'url'  => !empty($social3) ? $social3 : 'https://youtube.com',
        'icon' => 'youtube',
        'name' => !empty($L['youtube']) ? $L['youtube'] : 'YouTube'
    ],
    14 => [
        'url'  => !empty($social4) ? $social4 : 'https://instagram.com',
        'icon' => 'instagram',
        'name' => !empty($L['instagram']) ? $L['instagram'] : 'Instagram'
    ],
];

// نفترض وجود كائن $functions مسبقاً
$today   = $functions->getDate($lang); 

// -------------------------------------
// القائمة الجديدة 
// -------------------------------------
 $showHeaderType=2;

$menu =$M;

/**
 * دالة للمساعدة في إرجاع العنوان المناسب حسب اللغة
 */
function getItemTitle(array $items, string $lang): string {
    // إذا كان العنوان مصفوفة لغات
    if (is_array($items ?? null)) {
        return $items[$lang] ?? ''; 
    }
    // دعم قديم في حال كان العنوان نصا مفردا
    return $items ?? '';
}
 
function renderMenu(array $items, string $lang = "ar", bool $isMobile = false, int $level = 0, bool $st = false): string
{
    $html = '';
    $m    = '';
    $currentId = $_GET['i'] ?? 1;

    foreach ($items as $item) {
        $title = getItemTitle($item['title'], $lang);
        $id    = $item['id']?? -1;
        $icon  = $item['icon'] ?? '';
        $hasChildren = !empty($item['children']);
        $link =$id == -1 ?'':( ($id == 0) ? 'index.php?lang=' . $lang  : 'list-news.php?i=' . $id . '&lang=' . $lang);
        $iconHtml = $icon ? "<i class='bi $icon me-2'></i>" : '';
        $isActive = ($id == $currentId) ? ' active-text' : '';
        $edit = ($id > 1) ? edit_news($id) : '';
        
        /* ---------------------------------------------------
         *  فرع الموبايل  (أكورديون)
         * --------------------------------------------------*/
        if ($isMobile) {
            if ($hasChildren) {
                $html .= "
                <div class='accordion-item $m'>
                    <h2 class='accordion-header' id='heading-$id'>
                        <button class='accordion-button accordion-button-arrow collapsed'
                                type='button'
                                data-bs-toggle='collapse'
                                data-bs-target='#collapse-$id'
                                aria-expanded='false'
                                aria-controls='collapse-$id'>
                            $iconHtml $title
                        </button>
                    </h2>
                    <div id='collapse-$id' class='accordion-collapse collapse' aria-labelledby='heading-$id'>
                        <div class='accordion-body'>
                            " . renderMenu($item['children'], $lang, true, $level + 1, true) . "
                        </div>
                    </div>
                </div>";
            } else {
                if (!$st) {
                    $html .= "
                    <a href='$link' style='margin: 0 -14px'>
                        <div class='accordion-item mb-1'>
                            <h2 class='accordion-header'>
                                <button class='accordion-button accordion-button-arrow-1 collapsed' type='button'>
                                    $iconHtml $title
                                </button>
                            </h2>
                        </div>
                    </a>";
                } else {
                    $html .= "
                    <a href='$link' style='padding: 8px 4px'>
                        <div class='accordion-item'>
                            <button class='accordion-button accordion-button-arrow-1 collapsed' type='button'>
                                $iconHtml $title
                            </button>
                        </div>
                    </a>";
                }
            }

        /* ---------------------------------------------------
         *  فرع الدسكتوب  (Dropdown)
         * --------------------------------------------------*/
        } else {
            // ↓↓ التعديل الرئيسى على المسافات ↓↓
            $dropdownClass = $hasChildren ? 'dropdown' : '';
            $aBaseClass    = $hasChildren ? 'nav-link dropdown-toggle' : 'nav-link';
            $aClass        = $aBaseClass . ' py-1 px-2';      // Padding أصغر
            $aAttrs        = $hasChildren
                                ? "href='#' role='button' data-bs-toggle='dropdown' aria-expanded='false'"
                                : "href='$link'";
            
            $edit = (!$hasChildren && $id > 1) ? edit_details($id) : '';

            $html .= "
            <li class='nav-item $dropdownClass  li-nowrap'  >  
                <a class='$aClass  text-capitalize d-inline-flex ' $aAttrs>$iconHtml$title</a> $edit  " ;

            if ($hasChildren) {
                // أزلنا الحشو الافتراضى للقائمة
                $html .= "
                <ul class='dropdown-menu p-0'>
                    " . renderMenu($item['children'], $lang, false, $level + 1) . "
                </ul>";
            }
            $html .= "</li> ";
        }
    }

    return $html;
}
  
// Define readMenu function
function readMenu(array $items, int $id, string $lang): string {
    foreach ($items as $item) {
        $id1 = $item['id'] ?? -1;
        if ($id == $id1) {
            return getItemTitle($item['title'], $lang);
        }
        if (!empty($item['children'])) {
            $result = readMenu($item['children'], $id, $lang);
            if (!empty($result)) {
                return $result;
            }
        }
    }
    return '';
}

// دالة السلايدر الرئيسي (يسار كبير)
function renderMainSlider(array $newsList, string $lang, int $type = 2): string {
    ob_start(); ?>
    <div class="col-md-6 pb-05 pt-05 pe-md-05">
        <div class="position-relative overflow-hidden">
            <div class="nav-slider-hover nav-dots-top-right light-dots" data-flickity='{
                "cellAlign":"right",
                "rightToLeft":true,
                "wrapAround":true,
                "adaptiveHeight":true,
                "prevNextButtons": false,
                "pageDots":true,
                "imagesLoaded":true,
                "autoPlay": 3000
            }'>
                <?php foreach ($newsList as $news):
                    $title = getLocalizedTitle($news, $lang);
                    $imagePath = getImagePath($news, $type);
                    $author = getAuthor($news);
                    $dateStr = formatNewsDate($news, 'd M Y');
                ?>
                <article class="col-12">
                    <div class="card card-full text-light overflow zoom">
                        <div class="image-wrapper position-relative w-100 overflow-hidden" style="aspect-ratio: 16 / 10;">
                            <a href="article.php?id=<?= $news['news_id'] ?>&type=<?= $type ?>&lang=<?= $lang ?>">
                                <img class="img-fluid lazy w-100 h-100 object-fit-cover"
                                     src="assets/img/lazy-empty.png"
                                     data-src="<?= htmlspecialchars($imagePath) ?>"
                                     alt="<?= htmlspecialchars($title) ?>">
                            </a>
                            <div class="position-absolute p-3 b-0 w-100 bg-lg-shadow">
                                <a href="article.php?id=<?= $news['news_id'] ?>&type=<?= $type ?>&lang=<?= $lang ?>">
                                    <h2 class="h1-sm h2-md display-4-lg font-weight-500 text-white"><?= htmlspecialchars($title) ?></h2>
                                </a>
                                <div class="news-meta">
                                    <span class="news-author">
                                        بواسطة <a class="text-white font-weight-bold" href="#" onclick="event.preventDefault();"><?= htmlspecialchars($author) ?></a>
                                    </span>
                                    <time class="news-date" datetime="<?= htmlspecialchars($news['news_date']) ?>">
                                        <?= $dateStr ?>
                                    </time>
                                </div>
                            </div>
                        </div>
                    </div>
                </article>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
    <?php return ob_get_clean();
}

// دالة السلايدر الجانبي - ديسكتوب (مجموعات في خلايا كل خليتين)
function renderSideSliderDesktop(array $newsList, string $lang, int $type = 2, int $requiredCount = 8): string {
    ob_start();
    $currentCount = count($newsList);
    if ($currentCount < $requiredCount && $currentCount > 0) {
        $repeatedNews = [];
        for ($i = 0; $i < $requiredCount; $i++) {
            $repeatedNews[] = $newsList[$i % $currentCount];
        }
    } else {
        $repeatedNews = array_slice($newsList, 0, $requiredCount);
    }
    $padLeft = '4px';
    ?>
    <div class="col-md-6 pt-05 ps-md-05 d-none d-md-flex flex-column h-100">
        <div class="carousel box-slider h-100" data-flickity='{
            "cellAlign": "left",
            "contain": true,
            "wrapAround": true,
            "autoPlay": 3000,
            "pageDots": false,
            "prevNextButtons": false,
            "rightToLeft": true,
            "imagesLoaded": true
        }' style="direction: rtl;">
            <?php for ($i = 0; $i < count($repeatedNews); $i += 2): ?>
            <div class="carousel-cell" style="width: 50%; padding-bottom: 1px; box-sizing: border-box;">
                <div class="d-flex flex-column gap-2" style="height: 100%;">
                    <?php for ($j = 0; $j < 2; $j++):
                        if (!isset($repeatedNews[$i + $j])) continue;
                        $news = $repeatedNews[$i + $j];
                        $title = getLocalizedTitle($news, $lang);
                        $imagePath = getImagePath($news, $type);
                    ?>
                    <div class="card card-full text-white overflow zoom mb-0" style="border-radius: 1px; padding-left: <?= $padLeft ?>;">
                        <div class="image-wrapper image-box" style="position: relative; overflow: hidden; border-radius: 1px;">
                            <a href="article.php?id=<?= $news['news_id'] ?>&type=<?= $type ?>&lang=<?= $lang ?>" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;">
                                <img class="img-fluid lazy"
                                     src="assets/img/lazy-empty.png"
                                     data-src="<?= htmlspecialchars($imagePath) ?>"
                                     alt="<?= htmlspecialchars($title) ?>"
                                     style="width: 100%; height: 100%; object-fit: cover; border-radius: 1px;">
                            </a>
                            <div class="position-absolute px-3 pb-3 pt-2 b-0 w-100 bg-shadow" style="bottom: 0;">
                                <a href="article.php?id=<?= $news['news_id'] ?>" class="p-1 badge bg-primary text-white"><?= $L["details"] ?? 'التفاصيل' ?></a>
                                <a href="article.php?id=<?= $news['news_id'] ?>&type=<?= $type ?>&lang=<?= $lang ?>">
                                    <h2 class="h6 h4-sm h6-md h5-lg text-white my-1"><?= htmlspecialchars($title) ?></h2>
                                </a>
                            </div>
                        </div>
                    </div>
                    <?php endfor; ?>
                </div>
            </div>
            <?php endfor; ?>
        </div>
    </div>
    <?php return ob_get_clean();
}

// دالة السلايدر الجانبي - موبايل (2 صور فقط)
function renderSideSliderMobile(array $newsList, string $lang, int $type = 2, int $maxItems = 4): string {
    ob_start();
    $itemsToShow = array_slice($newsList, 0, $maxItems);
    $padLeft = '4px';
    ?>
    <div class="col-md-6 pt-05 ps-md-05 d-flex flex-column h-100 d-block d-md-none">
        <div class="carousel box-slider h-100" data-flickity='{
            "cellAlign": "left",
            "contain": true,
            "wrapAround": true,
            "autoPlay": 3000,
            "pageDots": false,
            "prevNextButtons": false,
            "rightToLeft": true,
            "imagesLoaded": true
        }' style="direction: rtl;">
            <?php foreach ($itemsToShow as $news):
                $title = getLocalizedTitle($news, $lang);
                $imagePath = getImagePath($news, $type);
            ?>
            <div class="carousel-cell" style="width: 50%; padding-bottom: 1px; box-sizing: border-box;">
                <div class="card card-full text-white overflow zoom mb-0" style="border-radius: 1px; padding-left: <?= $padLeft ?>;">
                    <div class="image-wrapper image-box" style="position: relative; overflow: hidden; border-radius: 1px;">
                        <a href="article.php?id=<?= $news['news_id'] ?>&type=<?= $type ?>&lang=<?= $lang ?>" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;">
                            <img class="img-fluid lazy"
                                 src="assets/img/lazy-empty.png"
                                 data-src="<?= htmlspecialchars($imagePath) ?>"
                                 alt="<?= htmlspecialchars($title) ?>"
                                 style="width: 100%; height: 100%; object-fit: cover; border-radius: 1px;">
                        </a>
                        <div class="position-absolute px-3 pb-3 pt-2 b-0 w-100 bg-shadow" style="bottom: 0;">
                            <a href="article.php?id=<?= $news['news_id'] ?>" class="p-1 badge bg-primary text-white"><?= $L["details"] ?? 'التفاصيل' ?></a>
                            <a href="article.php?id=<?= $news['news_id'] ?>&type=<?= $type ?>&lang=<?= $lang ?>">
                                <h2 class="h6 h4-sm h6-md h5-lg text-white my-1"><?= htmlspecialchars($title) ?></h2>
                            </a>
                        </div>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php return ob_get_clean();
}
  

function renderSmallPost($news, $tableId, $lang, $functions, $isDetails = false) { 
    $title       = getLocalizedTitle($news, $lang);
    $description = getShortHtmlDescription($news, $lang, $functions, 140);
    $imagePath   = getImagePath($news, $tableId);
    $dateStr     = formatNewsDate($news);
    $type        = $tableId;

    ob_start(); ?>
    <article class="card card-full hover-a mb-4">
        <div class="row g-2 align-items-center">
            <div class="col-4 col-md-4">
                <div class="ratio ratio-4x3 rounded overflow-hidden">
                    <a href="article.php?id=<?= $news['news_id'] ?>&type=<?= $type ?>&lang=<?= $lang ?>">
                        <img class="img-fluid object-fit-cover lazy w-100 h-100"
                             src="assets/img/lazy-empty.png"
                             data-src="<?= htmlspecialchars($imagePath) ?>"
                             alt="<?= htmlspecialchars($title) ?>">
                    </a>
                    <?= playIcon($news,$lang,$type); ?>
                </div>
            </div>
            <div class="col-8 col-md-8">
                <div class="card-body py-0 px-1">
                    <h3 class="card-title h6 h5-sm h6-md mb-1">
                        <a href="article.php?id=<?= $news['news_id'] ?>&type=<?= $type ?>&lang=<?= $lang ?>">
                            <?= htmlspecialchars($title) ?>
                        </a>
                    </h3>
                    <div class="small text-muted mb-1">
                        <time datetime="<?= htmlspecialchars($news['news_date']) ?>">
                            <?= $dateStr ?>
                        </time>
                    </div>
                    <?php if ($isDetails): ?>
                        <p class="card-text small mb-0"><?= $description ?></p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </article>
    <?php return ob_get_clean();
}
 
function renderBigPost($news, $tableId, $lang, $functions, $isDetails = true) {
    $title       = getLocalizedTitle($news, $lang);
    $description = getShortHtmlDescription($news, $lang, $functions, 300); 
    $imagePath   = getImagePath($news, $tableId);
    $dateStr     = formatNewsDate($news);
    $author      = getAuthor($news);
    $type        = $tableId;

    ob_start(); ?>
    <article class="card card-full hover-a mb-4">
      <div class="image-wrapper position-relative w-100 overflow-hidden" style="aspect-ratio: 16 / 9;">
        <a href="article.php?id=<?= $news['news_id'] ?>&type=<?= $type ?>&lang=<?= $lang ?>">
          <img class="img-fluid lazy w-100 h-100 object-fit-cover"
               src="assets/img/lazy-empty.png" 
               data-src="<?= htmlspecialchars($imagePath) ?>" 
               alt="<?= htmlspecialchars($title) ?>">
        </a>
      </div>
      <div class="card-body">
        <h2 class="card-title h1-sm h3-lg">
          <a href="article.php?id=<?= $news['news_id'] ?>&type=<?= $type ?>&lang=<?= $lang ?>">
            <?= htmlspecialchars($title) ?>
          </a>
        </h2>
        <div class="card-text mb-2 text-muted small">
          <span class="d-none d-sm-inline me-1">
            <a class="font-weight-bold" href="#" onclick="event.preventDefault();">
              <?= htmlspecialchars($author) ?>
            </a>
          </span>
          <time datetime="<?= htmlspecialchars($news['news_date']) ?>">
            <?= $dateStr ?>
          </time>
        </div>
        <p class="card-text"><?= $description ?></p>
      </div>
    </article>
    <?php return ob_get_clean();
}
 
function renderPersonPost($news, $tableId, $lang, $functions, $isDetails = true) { 
    $title       = getLocalizedTitle($news, $lang);
    $description = getShortHtmlDescription($news, $lang, $functions, 200);
    $imagePath   = getImagePath($news, $tableId);
    $dateStr     = formatNewsDate($news);
    $author      = getAuthor($news);
    $type        = $tableId;

    ob_start(); ?>
    <article class="card card-full hover-a mb-4">
      <div class="row">
        <div class="col-3 col-md-4 pe-2 pe-md-0">
          <div class="image-wrapper position-relative w-100 overflow-hidden"
               style="aspect-ratio: 3 / 4; max-height: 180px;">
            <a href="article.php?id=<?= $news['news_id'] ?>&type=<?= $type ?>&lang=<?= $lang ?>">
              <img class="img-fluid lazy w-100 h-100 object-fit-cover"
                   src="assets/img/lazy-empty.png"
                   data-src="<?= htmlspecialchars($imagePath) ?>" 
                   alt="<?= htmlspecialchars($title) ?>">
            </a>
          </div>
        </div>
        <div class="col-9 col-md-8">
          <div class="card-body pt-0">
            <h3 class="card-title h6 h5-sm h6-lg mb-1">
              <a href="article.php?id=<?= $news['news_id'] ?>&type=<?= $type ?>&lang=<?= $lang ?>">
                <?= htmlspecialchars($title) ?>
              </a>
            </h3>
            <div class="card-text small text-muted mb-1">
              <span class="d-none d-sm-inline me-1">
                <a class="font-weight-bold" href="#" onclick="event.preventDefault();">
                  <?= htmlspecialchars($author) ?>
                </a>
              </span>
              <time datetime="<?= htmlspecialchars($news['news_date']) ?>">
                <?= $dateStr ?>
              </time>
            </div>
            <p class="card-text mb-0"><?= $description ?></p>
          </div>
        </div> 
      </div>
    </article>
    <?php return ob_get_clean();
}

function renderMainSidePost(array $newsList, string $lang, int $type , $functions,  int $limit = 200): string {
    if (empty($newsList)) {
        return '<p> </p>';
    }

    $news        = $newsList[0];
    $title       = htmlspecialchars(getLocalizedTitle($news, $lang));
    $description = getShortHtmlDescription($news, $lang, $functions, $limit);
    $imagePath   = htmlspecialchars(getImagePath($news, $type));
    $author      = htmlspecialchars(getAuthor($news));
    $dateStr     = formatNewsDate($news, 'd F Y');
    $newsId      = (int)$news['news_id'];
    return '
    <div class="col-lg-6">
      <article class="card card-full hover-a mb-4">
        <div class="ratio ratio-16x9 image-wrapper rounded overflow-hidden">
          <a href="article.php?id=' . $newsId . '&type=' . $type . '&lang=' . $lang . '">
            <img class="img-fluid lazy object-fit-cover w-100 h-100" 
                 src="assets/img/lazy-empty.png" 
                 data-src="' . $imagePath . '" 
                 alt="' . $title . '">
          </a>'
          . playIcon($news,$lang,$type) .
        '</div>
        <div class="card-body">
          <h2 class="card-title h1-sm h3-lg">
            <a href="article.php?id=' . $newsId . '&type=' . $type . '&lang=' . $lang . '">' . $title . '</a>
          </h2>
          <div class="card-text mb-2 text-muted small">
            <span class="d-none d-sm-inline me-1">
              <a class="font-weight-bold" href="#" onclick="event.preventDefault();">' . $author . '</a>
            </span>
            <time datetime="' . htmlspecialchars($news['news_date']) . '">' . $dateStr . '</time>
          </div>
          <p class="card-text">' . $description . '</p>
        </div>
      </article>
    </div>';
}

function renderSidePostsBlock(array $newsList, string $lang, int $type, $l, int $limit = 4): string {
    if (empty($newsList) || count($newsList) <= 1) return '';

    $output = '<div class="col-lg-6">';
    $side_posts = array_slice($newsList, 1);
    $count = 0;

    foreach ($side_posts as $news) {
        if ($count++ >= $limit) break;

        $title     = htmlspecialchars(getLocalizedTitle($news, $lang));
        $imagePath = htmlspecialchars(getImagePath($news, $type));
        $dateStr   = formatNewsDate($news);
        $newsId    = (int)$news['news_id'];

        $output .= '
        <article class="card card-full hover-a mb-4">
          <div class="row g-2 align-items-center">
            <div class="col-4 col-md-4">
              <div class="ratio ratio-4x3 rounded overflow-hidden">
                <a href="article.php?id=' . $newsId . '&type=' . $type . '&lang=' . $lang . '">
                  <img class="img-fluid object-fit-cover lazy w-100 h-100"
                       src="assets/img/lazy-empty.png"
                       data-src="' . $imagePath . '"
                       alt="وصف الصورة">
                </a>'
                . playIcon($news,$lang,$type) .
              '</div>
            </div>
            <div class="col-8 col-md-8">
              <div class="card-body py-0 px-1">
                <h3 class="card-title h6 h5-sm h6-lg mb-1">
                  <a href="article.php?id=' . $newsId . '&type=' . $type . '&lang=' . $lang . '">' . $title . '</a>
                </h3>
                <div class="card-text small text-muted">
                  <time datetime="' . htmlspecialchars($news['news_date']) . '">' . $dateStr . '</time>
                </div>
              </div>
            </div>
          </div>
        </article>';
    }

    $output .= readMore($newsList, $type, $lang ,$l);
    $output .= '</div>';

    return $output;
}

function renderNewsBlockSection(array $newsList, string $lang, int $type, string $sectionTitle, $functions, $l): string {
    ob_start();
    ?>
    <div class="col-lg-6">
      <div class="block-title-6">
        <h4 class="h5 border-primary">
          <a href="list-news.php?i=<?= $type ?>&lang=<?= $lang ?>">
            <span class="bg-primary text-white"><?= htmlspecialchars($sectionTitle) ?></span>
          </a>
          <?= edit_news($type); ?>
        </h4>
      </div>
      <div class="big-post">
        <?php 
          if (!empty($newsList)) :
            foreach ($newsList as $news): ?>
          <?php
            $title       = htmlspecialchars(getLocalizedTitle($news, $lang));
            $description = getShortHtmlDescription($news, $lang, $functions, 300);
            $imagePath   = htmlspecialchars(getImagePath($news, $type));
            $dateStr     = formatNewsDate($news);
            $newsId      = (int)$news['news_id'];
          ?>
          <article class="card card-full hover-a mb-4">
            <div class="image-wrapper position-relative w-100 overflow-hidden" style="aspect-ratio: 16/9;">
              <a href="article.php?id=<?= $newsId ?>&type=<?= $type ?>&lang=<?= $lang ?>">
                <img class="img-fluid lazy w-100 h-100 object-fit-cover"
                     src="assets/img/lazy-empty.png"
                     data-src="<?= $imagePath ?>"
                     alt="<?= $title ?>">
              </a>
              <?= playIcon($news,$lang,$type); ?>
            </div>
            <div class="card-body">
              <h3 class="card-title h2 h3-sm h2-md">
                <a href="article.php?id=<?= $newsId ?>&type=<?= $type ?>&lang=<?= $lang ?>"><?= $title ?></a>
              </h3>
              <div class="card-text mb-2 text-muted small">
                <time datetime="<?= htmlspecialchars($news['news_date']) ?>"><?= $dateStr ?></time>
              </div>
              <p class="card-text"><?= $description ?></p>
            </div>
          </article>
        <?php endforeach;
          endif;
        ?>
        <?= readMore($newsList, $type,  $lang ,$l) ?>
      </div>
    </div>
    <?php
    return ob_get_clean();
}

function renderSplitNewsBlock(array $newsList, string $lang, int $type, $functions, $l ): string {
    if (empty($newsList)) return '';

    ob_start(); ?>
    <div class="border-bottom-last-0 first-pt-0">
      <?php foreach ($newsList as $news): ?>
        <?php
          $title       = htmlspecialchars(getLocalizedTitle($news, $lang));
          $description = getShortHtmlDescription($news, $lang, $functions, 200);
          $imagePath   = htmlspecialchars(getImagePath($news, $type));
          $author      = htmlspecialchars(getAuthor($news));
          $dateStr     = formatNewsDate($news);
          $newsId      = (int)$news['news_id'];
        ?>
        <article class="card card-full hover-a py-4">
          <div class="row">
            <div class="col-sm-6 col-md-12 col-lg-6">
              <div class="image-wrapper position-relative w-100 overflow-hidden" style="aspect-ratio: 16/9;">
                <a href="article.php?id=<?= $newsId ?>&type=<?= $type ?>&lang=<?= $lang ?>">
                  <img class="img-fluid lazy w-100 h-100 object-fit-cover"
                       src="assets/img/lazy-empty.png"
                       data-src="<?= $imagePath ?>"
                       alt="<?= $title ?>">
                </a>
                <?= playIcon($news,$lang,$type); ?>
              </div>
            </div>
            <div class="col-sm-6 col-md-12 col-lg-6">
              <div class="card-body pt-3 pt-sm-0 pt-md-3 pt-lg-0">
                <h3 class="card-title h2 h3-sm h2-md">
                  <a href="article.php?id=<?= $newsId ?>&type=<?= $type ?>&lang=<?= $lang ?>"><?= $title ?></a>
                </h3>
                <div class="card-text mb-2 text-muted small">
                  <span class="d-none d-sm-inline me-1">
                    <a class="font-weight-bold" href="article.php?id=<?= $newsId ?>&type=<?= $type ?>&lang=<?= $lang ?>">
                      <?= $author ?>
                    </a>
                  </span>
                  <time datetime="<?= htmlspecialchars($news['news_date']) ?>"><?= $dateStr ?></time>
                </div>
                <p class="card-text"><?= $description ?></p>
              </div>
            </div>
          </div>
        </article>
      <?php endforeach; ?>
      <?= readMore($newsList, $type, $lang , $l) ?>
    </div>
    <?php
    return ob_get_clean();
}

function renderCompactNewsList(array $newsList, string $lang, int $type, $functions, $l): string {
    if (empty($newsList)) return '';

    ob_start(); ?>
    <div class="border-bottom-last-0 first-pt-0">
      <?php foreach ($newsList as $news): ?>
        <?php
          $title       = getLocalizedTitle($news, $lang);
          $limit       = 180;
          $description = getShortHtmlDescription($news, $lang, $functions, $limit);
          $imagePath   = getImagePath($news, $type);
          $author      = getAuthor($news);
          $dateStr     = formatNewsDate($news);
          $newsId      = (int)$news['news_id'];
        ?>
        <article class="card card-full hover-a mb-4">
          <div class="row">
            <!-- صورة الخبر -->
            <div class="col-sm-6 col-md-12 col-lg-6">
              <div class="ratio ratio-16x9 image-wrapper rounded overflow-hidden">
                <a href="article.php?id=<?= $newsId ?>&type=<?= $type ?>&lang=<?= $lang ?>">
                  <img class="img-fluid lazy object-fit-cover w-100 h-100"
                       src="assets/img/lazy-empty.png"
                       data-src="<?= htmlspecialchars($imagePath) ?>"
                       alt="<?= htmlspecialchars($title) ?>">
                </a>
                <?= playIcon($news, $lang, $type); ?>
              </div>
            </div>

            <!-- نص الخبر -->
            <div class="col-sm-6 col-md-12 col-lg-6">
              <div class="card-body pt-3 pt-sm-0 pt-md-3 pt-lg-0">
                <h3 class="card-title h2 h3-sm h2-md">
                  <a href="article.php?id=<?= $newsId ?>&type=<?= $type ?>&lang=<?= $lang ?>">
                    <?= htmlspecialchars($title) ?>
                  </a>
                </h3>
                <div class="card-text mb-2 text-muted small">
                  <span class="d-none d-sm-inline me-1">
                    <a class="font-weight-bold" href="#" onclick="event.preventDefault();">
                      <?= htmlspecialchars($author) ?>
                    </a>
                  </span>
                  <time datetime="<?= htmlspecialchars($news['news_date']) ?>">
                    <?= $dateStr ?>
                  </time>
                </div>
                <p class="card-text"><?= $description ?></p>
              </div>
            </div>
          </div>
        </article>
      <?php endforeach; ?>
      <?= readMore($newsList, $type, $lang , $l) ?>
    </div>
    <?php
    return ob_get_clean();
}

function _renderCompactNewsList(array $newsList, string $lang, int $type, $functions, $l): string {
    if (empty($newsList)) return '';

    ob_start(); ?>
    <div class="border-bottom-last-0 first-pt-0">
      <?php foreach ($newsList as $news): ?>
        <?php
          $title       = htmlspecialchars(getLocalizedTitle($news, $lang));
          $description = getShortHtmlDescription($news, $lang, $functions, 120);
          $imagePath   = htmlspecialchars(getImagePath($news, $type));
          $dateStr     = formatNewsDate($news);
          $newsId      = (int)$news['news_id'];
        ?>
        <article class="card card-full hover-a mb-4">
          <div class="row">
            <div class="col-3 col-md-2 pe-2 pe-md-0">
              <div class="image-wrapper position-relative w-100 overflow-hidden"
                   style="aspect-ratio: 3 / 4; max-height: 160px;">
                <a href="article.php?id=<?= $newsId ?>&type=<?= $type ?>&lang=<?= $lang ?>">
                  <img class="img-fluid lazy w-100 h-100 object-fit-cover"
                       src="assets/img/lazy-empty.png"
                       data-src="<?= $imagePath ?>"
                       alt="<?= $title ?>">
                </a>
                <?= playIcon($news,$lang,$type); ?>
              </div>
            </div>
            <div class="col-9 col-md-10">
              <h3 class="card-title h6 h5-sm h6-lg mb-1">
                <a href="article.php?id=<?= $newsId ?>&type=<?= $type ?>&lang=<?= $lang ?>"><?= $title ?></a>
              </h3>
              <p class="card-text mb-1"><?= $description ?></p>
              <div class="card-text small text-muted">
                <time datetime="<?= htmlspecialchars($news['news_date']) ?>"><?= $dateStr ?></time>
              </div>
            </div>
          </div>
        </article>
      <?php endforeach; ?>
      <?= readMore($newsList, $type, $lang , $l) ?>
    </div>
    <?php
    return ob_get_clean();
}


function renderSimpleNewsList(array $newsList, int $tableId, string $lang, array $tables, array $L, $functions = null): string {
    if (empty($newsList)) {
        return '<p class="text-muted">' . htmlspecialchars($L['no_last_news'] ?? 'No news available') . '</p>';
    }

    $table = $tables[$tableId];
    $img_path = "service/images/news/$table/";

    ob_start();
    ?>
    <div class="posts-list">
        <?php foreach ($newsList as $news): 
            $newsId     = (int) $news['news_id'];
            $title      = getLocalizedTitle($news, $lang); 
            $imagePath  = $img_path . "img_" . $newsId . '.' . $news['img_ext'];
            $dateStr    = formatDate($news['news_date']);
        ?>
            <article class="card card-full hover-a mb-4">
                <div class="row g-2 align-items-center">
                    <div class="col-3 col-md-4">
                        <div class="image-wrapper position-relative w-100 overflow-hidden rounded" style="aspect-ratio: 115 / 80;">
                            <a href="article.php?id=<?= $newsId ?>&type=<?= $tableId ?>&lang=<?= $lang ?>">
                                <img class="img-fluid lazy w-100 h-100 object-fit-cover"
                                     src="assets/img/lazy-empty.png"
                                     data-src="<?= htmlspecialchars($imagePath) ?>"
                                     alt="<?= htmlspecialchars($title) ?>">
                            </a>
                            <?= playIcon($news,$lang,$type); ?>
                        </div>
                    </div>
                    <div class="col-9 col-md-8">
                        <div class="card-body py-0 px-2">
                            <h3 class="card-title h6 mb-1">
                                <a href="article.php?id=<?= $newsId ?>&type=<?= $tableId ?>&lang=<?= $lang ?>">
                                    <?= htmlspecialchars($title) ?>
                                </a>
                            </h3>
                            <div class="card-text small text-muted">
                                <time datetime="<?= htmlspecialchars($news['news_date']) ?>">
                                    <?= $dateStr ?>
                                </time>
                            </div>
                        </div>
                    </div>
                </div>
            </article>
        <?php endforeach; ?>
    </div>
    <?php
    return ob_get_clean();
}

function renderInstagramPhotos(array $newsList, int $tableId, string $lang, array $tables, array $L, int $maxCount = 12): string {
    if (empty($newsList)) {
        return '<p class="text-muted">' . htmlspecialchars($L['no_last_news'] ?? 'No news available') . '</p>';
    }

    $table = $tables[$tableId];
    $img_path = "service/images/news/$table/";

    ob_start(); ?>
    <div class="col-12 instagram-photos mb-1">
        <div class="row g-1">
            <?php 
            $count = 0;
            foreach ($newsList as $news):
                if ($count++ >= $maxCount) break;
                $newsId = (int)$news['news_id'];
                $title = getLocalizedTitle($news, $lang);
                $imagePath = $img_path . "img_" . $newsId . '.' . $news['img_ext'];
            ?>
                <div class="col-6 col-sm-4 px-1">
                    <a href="article.php?id=<?= $newsId ?>&type=<?= $tableId ?>&lang=<?= $lang ?>" 
                       class="card card-full mb-2 rounded-0 overflow-hidden zoom hover-a"
                       data-bs-toggle="tooltip"
                       data-bs-placement="bottom"
                       title="<?= htmlspecialchars($title) ?>">
                        <div class="image-wrapper position-relative w-100 overflow-hidden rounded" style="aspect-ratio: 540 / 454;">
                            <img 
                                src="assets/img/lazy-empty.png"
                                data-src="<?= htmlspecialchars($imagePath) ?>"
                                class="img-fluid lazy w-100 h-100 object-fit-cover"
                                alt="<?= htmlspecialchars($title) ?>"
                                loading="lazy"
                                />
                        </div>
                    </a>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php
    return ob_get_clean();
}


function findById(array $items, int $id): ?array
{
    foreach ($items as $item) {
        if ($item['id'] === $id) {
            return $item;                     // وُجِد
        }
        if (!empty($item['children'])) {
            $found = findById($item['children'], $id);
            if ($found !== null) {
                return $found;                // وُجِد في مستوى أعمق
            }
        }
    }
    return null;                              // لم يُعثر عليه
}
 
function readMore(array $items, int $i,  $lang, array $L ): string { 
    if (count($items) >= 5) {  
        return '<span style="margin-top:-25px;margin-right:20px;float:left">
            &emsp;<i>
                <a href="list-news.php?i=' . $i . '&lang='. $lang .'">' . htmlspecialchars($L['read_more']) . '</a>
            </i>
        </span>'; 
    }
    return '';
}

function playIcon($news,  $lang,  $type){
    $id=$news['news_id'];
    $url=$news['news_link'];
    if($url)
    return '<div class="post-type-icon" style="width: 36px;height: 36px; 
        border-radius: 50%; 
        background-color: rgba(0, 123, 255, 0.5); 
        display: flex; 
        justify-content: center; 
        align-items: center;">
        <a href="article.php?id='.$id.'&type=' . $type . '&lang=' . $lang . '" style="display: block; width: 100%; height: 100%;">
            <svg xmlns="http://www.w3.org/2000/svg" fill="white" viewBox="0 0 16 16" style="width: 100%; height: 100%;">
                <path d="M11.596 8.697l-6.363 3.692c-.54.313-1.233-.066-1.233-.697V4.308c0-.63.692-1.01 1.233-.696l6.363 3.692a.802.802 0 0 1 0 1.393z"/>
            </svg>
        </a>
    </div>
    ';
    else   
       return '';
}



/**
 * إرجاع كود SVG لشبكات التواصل مع إمكانية مضاعفة الحجم.
 *
 * @param string $name اسم الشبكة: facebook | telegram | youtube | instagram
 * @param float  $scale عامل التكبير (1 = الحجم الأصلي؛ 2 = ضعف الحجم؛ …)
 * @return string  كود SVG جاهز للإدراج
 */
function getSocialIconSvg(string $name, float $scale = 1): string
{
    $base = 1 * $scale . 'rem';
    $icons = [
        'facebook'  => '<svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" class="bi bi-facebook" viewBox="0 0 16 16">
            <path d="M16 8.049c0-4.446-3.582-8.05-8-8.05C3.58 0-.002 3.603-.002 8.05c0 4.017 2.926 7.347 6.75 7.951v-5.625h-2.03V8.05H6.75V6.275
            c0-2.017 1.195-3.131 3.022-3.131.876 0 1.791.157 1.791.157v1.98h-1.009c-.993 0-1.303.621-1.303 1.258v1.51h2.218l-.354 2.326H9.25V16
            c3.824-.604 6.75-3.934 6.75-7.951z"></path>
        </svg>',
         'telegram'   => '<svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" class="bi bi-telegram" viewBox="0 0 16 16">
           <path d="M16 3.038a2 2 0 0 0-2.828-1.89L1.457 6.52c-.885.39-.83 1.618.08 1.93l3.563 1.237 1.3 4.02c.3.923 1.5 1.097 2.06.293l2.55-3.655 3.585-1.318a2 2 0 0 0 1.405-1.989z"/>
         </svg>', 
        'youtube'   => '<svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" class="bi bi-youtube" viewBox="0 0 16 16">
            <path d="M8.051 1.999h.089c.822.003 4.987.033 6.11.335a2.01 2.01 0 0 1 1.415 1.42c.101.38.172.883.22 1.402l.01.104.022.26.008.104
            c.065.914.073 1.77.074 1.957v.075c-.001.194-.01 1.108-.082 2.06l-.008.105-.009.104c-.05.572-.124 1.14-.235 1.558a2.007
            2.007 0 0 1-1.415 1.42c-1.16.312-5.569.334-6.18.335h-.142c-.309
            0-1.587-.006-2.927-.052l-.17-.006-.087-.004-.171-.007-.171-.007
            c-1.11-.049-2.167-.128-2.654-.26a2.007 2.007 0 0 1-1.415-1.419
            c-.111-.417-.185-.986-.235-1.558L.09 9.82l-.008-.104A31.4 31.4 0 0 1 0 7.68v-.122C.002 7.343.01 6.6.064 5.78
            l.007-.103.003-.052.008-.104.022-.26.01-.104c.048-.519.119-1.023.22-1.402
            a2.007 2.007 0 0 1 1.415-1.42c.487-.13 1.544-.21 2.654-.26
            l.17-.007.172-.006.086-.003.171-.007A99.788
            99.788 0 0 1 7.858 2h.193zM6.4 5.209v4.818l4.157-2.408L6.4 5.209z"></path>
        </svg>',
        'instagram' => '<svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 512 512">
            <path d="M349.33,69.33a93.62,93.62,0,0,1,93.34,93.34V349.33a93.62,93.62,0,0,1-93.34,93.34H162.67
            a93.62,93.62,0,0,1-93.34-93.34V162.67a93.62,93.62,0,0,1,93.34-93.34H349.33m0-37.33H162.67C90.8,32,32,90.8,32,162.67V349.33
            C32,421.2,90.8,480,162.67,480H349.33C421.2,480,480,421.2,480,349.33V162.67C480,90.8,421.2,32,349.33,32Z"></path>
            <path d="M377.33,162.67a28,28,0,1,1,28-28A27.94,27.94,0,0,1,377.33,162.67Z"></path>
            <path d="M256,181.33A74.67,74.67,0,1,1,181.33,256,74.75,74.75,0,0,1,256,181.33M256,144A112,112,0,1,0,368,256
            A112,112,0,0,0,256,144Z"></path>
        </svg>'
    ];

    if (isset($icons[$name])) {
        return preg_replace('/<svg\b/', '<svg style="width:' . $base . ';height:' . $base . ';"', $icons[$name], 1);
    }
    return '';
}


/**
 * تعيد العنوان المناسب حسب اللغة.
 */
function getLocalizedTitle(array $news, string $lang): string
{
    switch ($lang) {
        case 'en':
            return $news['news_title2'] ?: $news['news_title'];
        case 'ku':
            return $news['news_title1'] ?: $news['news_title'];
        default:
            return $news['news_title'];
    }
}

/**
 * تعيد الوصف المناسب حسب اللغة.
 */
function getLocalizedDescription(array $news, string $lang): string
{
    switch ($lang) {
        case 'en':
            return $news['news_description2'] ?: $news['news_description'];
        case 'ku':
            return $news['news_description1'] ?: $news['news_description'];
        default:
            return $news['news_description'];
    }
}

/**
 * اختصار النص بالاعتماد على دالة subText أو أي تقطيع آخر.
 */
function getFullDescription(array $news, string $lang, $functions): string
{
    $description = getLocalizedDescription($news, $lang);
    $length = strlen($description);
    return $functions->subText($description, 0, $length);
}

function getShortDescription(array $news, string $lang, $functions, int $maxLength = 500): string
{
    $description = getLocalizedDescription($news, $lang);
    return $functions->subText($description, 0, $maxLength);
}

function getFullHtmlDescription(array $news, string $lang, $functions): string
{
    $description = getLocalizedDescription($news, $lang);
    $length = strlen($description);
    return $functions->subHtmlText($description, 0, $length);
}

function getShortHtmlDescription(array $news, string $lang, $functions, int $maxLength = 500): string
{
    $description = getLocalizedDescription($news, $lang);
    return $functions->subHtmlText($description, 0, $maxLength);
}

/**
 * تعيد المسار الكامل للصورة بناءً على id الخبر وامتداد الصورة.
 */
function getImagePath(array $news, int $tableId): string
{   
    $tables = getTables();
    $tableName = isset($tables[$tableId]) ? $tables[$tableId] : 'dbs_news1';
    return "service/images/news/{$tableName}/img_{$news['news_id']}.{$news['img_ext']}"; 
}

function getTables(): array
{   
  $maxTables = 48;   
  $tables = [];

   for ($i = 1; $i <= $maxTables; $i++) {
    $tables[$i] = 'dbs_news' . $i;
  }
  return $tables;
}


/**
 * تنسيق تاريخ الخبر.
 */
function formatNewsDate(array $news, string $format = 'd F Y'): string
{
   // return date($format, strtotime($news['news_date']));
    $lang = $_GET['lang'] ?? 'ar';
    return localizedDate($news['news_date'],$lang);
}

/**
 * إعادة اسم المؤلف (حاليًا فارغ؛ قابل للتعديل لاحقًا).
 */
function getAuthor(array $news): string
{
    // يمكن تعديل الدالة لإرجاع اسم المؤلف الحقيقي مستقبلاً
    return '';
}

/**
 * دالة اختصار نص:
 */
function subText(string $txt, int $len = 120): string
{
    return mb_strlen($txt, 'UTF-8') > $len
        ? mb_substr($txt, 0, $len, 'UTF-8') . '…'
        : $txt;
}

/**
 * دالة لتنسيق التاريخ.
 */
function formatDate(string $date): string
{
    $lang = $_GET['lang'] ?? 'ar';
    return localizedDate($date,$lang);
}
/**
 * أرجع التاريخ بالصيغة المحلية (ar-IQ, ku-IQ, en).
 *
 * @param string      $dateStr  نصّ التاريخ المقبول من DateTime (مثلاً 2025-05-31)
 * @param string|null $lang     كود اللغة: 'ar' أو 'ku' أو 'en'؛
 *                              إذا تُرك null يُستخدم لغة الموقع الافتراضية.
 * @return string               مثال: "السبت، 31 أيار، 2025"
 */
function localizedDate(string $dateStr, ?string $lang = null): string
{
    $lang = $lang ?: (locale_get_default() ?: 'ar');   // احتياط

    /* ❶ جرّب IntlDateFormatter متى ما توفّر */
    if (class_exists('IntlDateFormatter')) {
        // ar => ar_IQ، ku => ku_IQ، en => en_US
        $localeMap = ['ar' => 'ar', 'ku' => 'ku', 'en' => 'en'];
        $locale    = $localeMap[$lang] ?? 'ar';

        $fmt = new IntlDateFormatter(
            $locale . '@calendar=gregorian',
            IntlDateFormatter::FULL,
            IntlDateFormatter::NONE,
            'Asia/Baghdad',
            IntlDateFormatter::GREGORIAN,
            'EEEE، d MMMM، y'        // مثال الناتج: السبت، 31 أيار، 2025
        );

        return $fmt->format(new DateTime($dateStr));
    }

    /* ❷ ــ مسار بديل يدوي إن لم يتوافر intl */
    $dayLists = [
        'ar' => ["الأحد","الإثنين","الثلاثاء","الأربعاء","الخميس","الجمعة","السبت"],
        'ku' => ["یه‌كشه‌ممه‌","دووشه‌ممه‌","سێشه‌ممه‌","چوارشه‌ممه‌","پێنجشه‌ممه‌","هه‌ینی","شه‌ممه‌"],
        'en' => ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
    ];

    $monthLists = [
        'ar' => ["كانون الثاني","شباط","آذار","نيسان","أيار","حزيران","تموز","آب",
                 "أيلول","تشرين الأول","تشرين الثاني","كانون الأول"],
        'ku' => ["کانونی یەکەم","شوبات","ئازار","نیسان","ئایار","حوزەیران","تەمموز","ئاب",
                 "ئەیلوول","تشرینی یەکەم","تشرینی دووەم","کانونی دووەم"],
        'en' => ["January","February","March","April","May","June",
                 "July","August","September","October","November","December"]
    ];

    // اختر القوائم مع افتراضي عربي
    $days   = $dayLists[$lang]   ?? $dayLists['ar'];
    $months = $monthLists[$lang] ?? $monthLists['ar'];

    $dt = new DateTime($dateStr);

    return sprintf(
        "%s، %d %s، %d",
        $days[$dt->format('w')],          // اسم اليوم
        $dt->format('j'),                 // رقم اليوم
        $months[$dt->format('n') - 1],    // اسم الشهر
        $dt->format('Y')                  // السنة
    );
}

function makeEmbedSrc(string $url): array
{
    // نعيد [src, extra_script]  — الثاني لإرفاق سكربت عند الحاجة
    // 1) YouTube
    if (preg_match('~(?:youtu\.be/|youtube\.com/(?:watch\\?v=|v/|embed/|shorts/))([\\w-]{11})~', $url, $m)) {
        return ["https://www.youtube.com/embed/{$m[1]}?rel=0", ''];
    }

    // 2) Facebook (فيديو أو بث مباشر)
    if (preg_match('~facebook\.com/.+/videos/[0-9]+~', $url)) {
        // التحقق من قابلية التضمين
        $embed_check = get_headers($url, 1);
        // إذا كانت النتيجة "403 Forbidden"، الفيديو لا يمكن تضمينه
        if (isset($embed_check['HTTP/1.1']) && strpos($embed_check['HTTP/1.1'], '403') !== false) {
            return [null, "<a href='{$url}' target='_blank'>يمكن مشاهدة هذا الفديو على فيسبوك من خلال هذا الرابط</a>"];
        }
        return ["https://www.facebook.com/plugins/video.php?href=" . urlencode($url) . "&show_text=0", ''];
    }

    // 3) TikTok
    if (preg_match('~tiktok\.com/@[^/]+/video/([0-9]+)~', $url, $m)) {
        return ["https://www.tiktok.com/embed/v2/{$m[1]}",  // Player
                '<script async src="https://www.tiktok.com/embed.js"></script>'];
    }

    // 4) Instagram
    if (preg_match('~instagram\.com/p/([A-Za-z0-9_-]+)/?~', $url, $m)) {
        // طريقة iframe البسيطة
        return ["https://www.instagram.com/p/{$m[1]}/embed",  // أو استخدم oEmbed API
                '<script async src="//www.instagram.com/embed.js"></script>'];
    }

    // خدمة غير مدعومة
    return ['', ''];
}
 
/**
 * دوال تحكم واجهة (تحرير اجتماعي، إعلانات، صور، أخبار... إلخ).
 */
function edit_social(): string
{
    $edit_mode = isEditMode(); 
    if ($edit_mode) {
        return '<button onclick="editSocial()" class="control-edit">تحرير</button>';
    }
    return '';
}

function edit_ads(): string
{
    $edit_mode = isEditMode(); 
    if ($edit_mode) {
        return '<button onclick="editAds()" class="control-edit">تحرير</button>';
    }
    return '';
}

function edit_image(int $i): string
{
    $edit_mode = isEditMode(); 
    if ($edit_mode) {
        return sprintf(
            '<button onclick="editImage(%d)" class="control-edit">تحرير</button>',
            $i
        );
    }
    return '';
}

function edit_image1(int $i): string
{
    $edit_mode = isEditMode(); 
    if ($edit_mode) {
        return sprintf(
            '<div style="margin-top:-26px;float:left;">
               <button onclick="editImage(%d)" class="control-edit">تحرير</button>
            </div>',
            $i
        );
    }
    return '';
}

function edit_news(int $i): string
{
    $edit_mode = isEditMode(); 
    if ($edit_mode) {
        return sprintf(
            '<button onclick="editNews(%d)" class="control-edit">تحرير</button>', $i
        );
    }
    return '';
}

function edit_details(int $i): string
{ 
    if (isEditMode()) { 
        return sprintf(
           "<button onclick='editDetails(%d)' class='control-edit'>تحرير</button>", $i
      );
    } 
    return '';
}

function edit_about(): string
{
    $edit_mode = isEditMode(); 
    if ($edit_mode) {
        return sprintf(
            '<button onclick="editAbout()" class="control-nedit">تحرير</button>'
        );
    }
    return '';
}

function edit_contact(): string
{
    $edit_mode = isEditMode(); 
    if ($edit_mode) {
        return sprintf(
            '<button onclick="editContact()" class="control-nedit">تحرير</button>'
        );
    }
    return '';
}

function edit_pdf(): string
{
    $edit_mode = isEditMode(); 
    if ($edit_mode) {
        return sprintf(
            '<button onclick="uploadPdf()" class="control-nedit">تحرير</button>'
        );
    }
    return '';
}

function edit_button(int $i, int $a, int $e, int $d): string
{
    $edit_mode = isEditMode(); 
    if ($edit_mode) {
        return sprintf(
            '<button onclick="editBlock(%d,%d,%d,%d)" class="control-nedit">تحرير</button>',
            $i, $a, $e, $d
        );
    }
    return '';
}

function logout_button(): string
{
    $edit_mode = isEditMode(); 
    if ($edit_mode) {
        return '<li class="nav-item"><a title="تسجيل الخروج"  href="logout.php" class="nav-link" > 
                                        <button  class="control-edit1">تسجيل الخروج</button>
                                    </a></li>';
    }
    return '';
}

function retern_button(): string
{
    $edit_mode = isEditMode(); 
    if ($edit_mode) {
        return '<li class="nav-item"><a title="رجــــوع"  href="dashboard.php" class="nav-link" > 
                                        <button  class="control-edit1">رجــــوع</button>
                                    </a></li>';
    }
    return '';
}

function isEditMode(){
    $functions = new Functions();  
    return   $functions->isLogined(); 
}