<?php

//  Send SMS
function sendSMS($number, $msg){
  global $advancenews;
  // Send SMS OTP
  $url = "https://api.bdbulksms.net/api.php?json";
  $data= array(
    'to'=>$number,
    'message'=>"$msg",
    'token'=>$advancenews['GREENWEB_TOCKEN'],
  );
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL,$url);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  curl_setopt($ch, CURLOPT_ENCODING, '');
  curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  $smsresult = curl_exec($ch);
  $response = json_decode($smsresult, true);
  return $response[0]['status'];
}

function sendEmailOTP($email, $otp){
  global $advancenews;
  $company_name = $advancenews['COMPANY_NAME'];
  $company_send_from = $advancenews['EMAIL_SEND_FROM'];

  $to = $email;
  $subject = "Your  $company_name Account OTP is $otp";
  $headers = "From: $company_send_from\r\n";
  $headers .= "MIME-Version: 1.0\r\n";
  $headers .= "Content-Type: text/html; charset=UTF-8\r\n";

  $message = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Your OTP</title><style>.body,.footer,.header{text-align:center}.footer a,.footer p{font-size:12px}.footer a,.otp{font-weight:700}.email-container{max-width:600px;margin:30px auto;background-color:#fff;border-radius:8px;overflow:hidden}.otp,.warning{margin-top:20px}.header{background-color:#2e86de;color:#fff;padding:20px;font-size:24px}.body{padding:30px;font-size:18px;color:#333}.otp{font-size:32px;color:#e74c3c}.footer,.warning{font-size:14px;color:#777}.footer{background-color:#f1f1f1;padding:15px}.footer a{color:#d25200;text-decoration:none}</style></head><body><div class="email-container"><div class="header">'.$company_name.'</div> <div class="body"> <p>Your account OTP is</p><div class="otp">'.$otp.'</div><div class="warning">Please do not share your OTP with anyone. '.$company_name.' will never ask for it.</div></div><div class="footer">&copy; ' . date("Y") . ' ' . $company_name . '. All rights reserved.<p>Powered by <a href="https://mf1t.com">mf1t.com</a>.</p></div></div></body></html>';

  // For test Purpose
  // $filename = "otp_email.html"; // Define the filename with timestamp or unique ID
  // file_put_contents($filename, $message); // Save the message content to an HTML file in the current directory

  if (mail($to, $subject, $message, $headers)) {
    return true;
  } else {
    return false;
  }
}
function getVideoEmbed($url) {
    $iframe = '';

    // ✅ YouTube (short & long formats)
    if (preg_match('/(?:youtu\.be\/|youtube\.com\/watch\?v=)([^&\n?#]+)/', $url, $matches)) {
        $videoID = $matches[1];
        $iframe = '<iframe width="560" height="315"
            src="https://www.youtube.com/embed/' . htmlspecialchars($videoID) . '"
            frameborder="0"
            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
            allowfullscreen></iframe>';
    }

    // ✅ Facebook
    elseif (preg_match('/facebook\.com\/.*videos\/([^\/\?&]+)/', $url, $matches)) {
        $escapedUrl = urlencode($url);
        $iframe = '<iframe width="560" height="315"
            src="https://www.facebook.com/plugins/video.php?href=' . $escapedUrl . '&show_text=false"
            style="border:none;overflow:hidden"
            scrolling="no"
            frameborder="0"
            allowfullscreen="true"
            allow="autoplay; clipboard-write; encrypted-media; picture-in-picture; web-share"></iframe>';
    }
    return $iframe ?: '<p>❌ Invalid video URL.</p>';
}
// Date to file path
function dateFilePath($date){
  // The Post Year and Month
  $date_offpost = new DateTime($date);
  $year_offpost = $date_offpost->format('Y');
  $month_offpost = $date_offpost->format('m');

  // Define the base uploads directory
  $uploads_dir =  '../uploads'; // Adjust path as needed

  // Check if the year folder exists
  $year_dir = $uploads_dir . '/' . $year_offpost;

  // Check if the month folder exists
  $month_dir = $year_dir . '/' . $month_offpost;

  // Final directory
  return $month_dir.'/';
}

function sendEmailPwd($email, $otp){
  global $advancenews;
  $company_name = $advancenews['COMPANY_NAME'];
  $company_send_from = $advancenews['EMAIL_SEND_FROM'];

  $to = $email;
  $subject = "Security update: Your $company_name account password was reset";
  $headers = "From: $company_send_from\r\n";
  $headers .= "MIME-Version: 1.0\r\n";
  $headers .= "Content-Type: text/html; charset=UTF-8\r\n";

  $message = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>mf1t.com</title><style>.body,.footer,.header{text-align:center}.footer a,.footer p{font-size:12px}.footer a,.otp{font-weight:700}.email-container{max-width:600px;margin:30px auto;background-color:#fff;border-radius:8px;overflow:hidden}.otp,.warning{margin-top:20px}.header{background-color:#2e86de;color:#fff;padding:20px;font-size:24px}.body{padding:30px;font-size:18px;color:#333}.otp{font-size:32px;color:#e74c3c}.footer,.warning{font-size:14px;color:#777}.footer{background-color:#f1f1f1;padding:15px}.footer a{color:#d25200;text-decoration:none}</style></head><body><div class="email-container"><div class="header">'.$company_name.'</div> <div class="body"> <p>Your temporary password is</p><div class="otp">'.$otp.'</div><div class="warning">Please change this password after first login. Do not share your this email with anyone. '.$company_name.' will never ask for it.</div></div><div class="footer">&copy; ' . date("Y") . ' ' . $company_name . '. All rights reserved.<p>Powered by <a href="https://mf1t.com">mf1t.com</a>.</p></div></div></body></html>';

  // For test Purpose
  // $filename = "otp_email.html"; // Define the filename with timestamp or unique ID
  // file_put_contents($filename, $message); // Save the message content to an HTML file in the current directory

  if (mail($to, $subject, $message, $headers)) {
    return true;
  } else {
    return false;
  }
}


// Mask Email
function maskEmail($email) {
    // Split the email into local part and domain
    list($local, $domain) = explode('@', $email);

    // Get the first and last characters of the local part
    $firstChar = $local[0];
    $lastChar = $local[strlen($local) - 1];

    // Create the masked version with 6 asterisks in between
    $maskedLocal = $firstChar . '******' . $lastChar;

    // Combine the masked local part with the domain
    return $maskedLocal . '@' . $domain;
}

//  Mask phone Number
function maskPhoneNumber($phone) {
    // Get the first 7 characters and the last 3 characters of the phone number
    $firstPart = substr($phone, 0, 5);
    $lastPart = substr($phone, -2);

    // Create the masked phone number with 5 asterisks in between
    $maskedPhone = $firstPart . '****' . $lastPart;

    return $maskedPhone;
}

// Create OTP
function generateTempPwd() {
    // Generate a random 4-digit number
    $otp = mt_rand(10000000, 99999999);

    // Return as a string to preserve leading zeros if any
    return strval($otp);
}

// Create OTP
function generateOTP() {
    // Generate a random 4-digit number
    $otp = mt_rand(1000, 9999);

    // Return as a string to preserve leading zeros if any
    return strval($otp);
}

// Convet Date
function dateShow($date, $tt_lang = 'bn') {

    // Define month names in Bengali
    $monthsBn = [
        'January' => 'জানুয়ারি',
        'February' => 'ফেব্রুয়ারি',
        'March' => 'মার্চ',
        'April' => 'এপ্রিল',
        'May' => 'মে',
        'June' => 'জুন',
        'July' => 'জুলাই',
        'August' => 'আগস্ট',
        'September' => 'সেপ্টেম্বর',
        'October' => 'অক্টোবর',
        'November' => 'নভেম্বর',
        'December' => 'ডিসেম্বর'
    ];

    // Define digit conversion from English to Bengali
    $digitsBn = [
        '0' => '০',
        '1' => '১',
        '2' => '২',
        '3' => '৩',
        '4' => '৪',
        '5' => '৫',
        '6' => '৬',
        '7' => '৭',
        '8' => '৮',
        '9' => '৯'
    ];

    // Parse the input date
    $timestamp = strtotime($date);

    // Format the date in English
    $formattedDateEn = date('F j, Y', $timestamp);

    if ($tt_lang === 'bn') {
        // Convert month to Bengali
        $monthEn = date('F', $timestamp);
        $day = date('j', $timestamp);
        $year = date('Y', $timestamp);

        $monthBn = $monthsBn[$monthEn];
        $formattedDateBn = "$day $monthBn, $year";

        // Convert numbers to Bengali
        $formattedDateBn = strtr($formattedDateBn, $digitsBn);

        return $formattedDateBn;
    }

    return $formattedDateEn;
}

function dateTimeShow($datetime) {
    // Month names in Bengali
    $monthsBn = [
        'January' => 'জানুয়ারি',
        'February' => 'ফেব্রুয়ারি',
        'March' => 'মার্চ',
        'April' => 'এপ্রিল',
        'May' => 'মে',
        'June' => 'জুন',
        'July' => 'জুলাই',
        'August' => 'আগস্ট',
        'September' => 'সেপ্টেম্বর',
        'October' => 'অক্টোবর',
        'November' => 'নভেম্বর',
        'December' => 'ডিসেম্বর'
    ];

    // English → Bengali digits
    $digitsBn = [
        '0' => '০',
        '1' => '১',
        '2' => '২',
        '3' => '৩',
        '4' => '৪',
        '5' => '৫',
        '6' => '৬',
        '7' => '৭',
        '8' => '৮',
        '9' => '৯'
    ];

    // AM/PM in Bengali
    $ampmBn = [
        'AM' => 'এএম',
        'PM' => 'পিএম'
    ];

    // Parse the datetime
    $timestamp = strtotime($datetime);

    // Extract parts
    $day = date('j', $timestamp);
    $monthEn = date('F', $timestamp);
    $year = date('Y', $timestamp);
    $time = date('h:i A', $timestamp);

    // Translate month & AM/PM
    $monthBn = $monthsBn[$monthEn];
    $timeBn = strtr($time, $ampmBn);

    // Combine into final format
    $formatted = "$day $monthBn $year, $timeBn";

    // Convert all digits to Bengali
    return strtr($formatted, $digitsBn);
}

function ttdShow($date) {

    // Parse the input date
    $timestamp = strtotime($date);

    // Format the date in English
    $formattedDateEn = date('F j, Y', $timestamp);

    return $formattedDateEn;
}


// Function to generate a CSRF token
function generateCSRFToken() {
    return bin2hex(random_bytes(32));
}

// Function to check if CSRF token is valid
function verifyCSRFToken($token) {
    return hash_equals($_SESSION['csrf_token'], $token);
}

// Include this function wherever you need to generate a form with CSRF token
function csrfField() {
    $csrf_token = generateCSRFToken();
    $_SESSION['csrf_token'] = $csrf_token;
    return '<input type="hidden" name="csrf_token" value="' . $csrf_token . '">';
}

// Show Single Data Array
function ttSingleData($nestedArray) {
    // Check if the array has at least one element
    if (!empty($nestedArray) && is_array($nestedArray[0])) {
        return $nestedArray[0]; // Return the first element of the nested array
    }
    return []; // Return an empty array if the input is not as expected
}

// Media Render
function renderMediaByType($fileUrl) {
    // Get the file extension
    $ext = strtolower(pathinfo($fileUrl, PATHINFO_EXTENSION));

    switch ($ext) {
        case 'jpg':
        case 'jpeg':
        case 'png':
        case 'gif':
        case 'webp':
            echo '<img src="' . $fileUrl . '" alt="Image" style="width:100%; height:auto;">';
            break;

        case 'mp3':
        case 'ogg':
        case 'wav':
            echo '<audio controls style="width:100%;">
                    <source src="' . $fileUrl . '" type="audio/' . $ext . '">
                    Your browser does not support the audio element.
                  </audio>';
            break;

        case 'mp4':
        case 'webm':
        case 'ogg': // Could be video too
            echo '<video controls style="width:100%; max-height:500px;">
                    <source src="' . $fileUrl . '" type="video/' . $ext . '">
                    Your browser does not support the video element.
                  </video>';
            break;

        case 'pdf':
            echo '<iframe src="' . $fileUrl . '" width="100%" height="600px" style="border:none;"></iframe>';
            break;

        default:
            echo '<a href="' . $fileUrl . '" target="_blank">📎 Download File</a>';
            break;
    }
}


// Count Visitor
function CountVisiter($pagetype, $pageid){

    // global $conn; // Import global variables, including the database connection
    // $userIP = $_SERVER['REMOTE_ADDR']; // User Ip Address
    // $current_url = "http".((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "s" : "")."://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; // URL Address

    // // View Count will store post, category data table and custom pages like : home, search, 404 page .
    // // Type : post, page, custom,

    // // Get Data From API
    // $device_info_json_api = file_get_contents("https://whatmyuseragent.com/api?ua=".urlencode($_SERVER['HTTP_USER_AGENT'])."&key=NOTREQUIED");
    // $device_info = json_decode($device_info_json_api, true);

    // if($device_info['device']['isBot'] != true){

    //     // Device Model Or Name
    //     if ($device_info['device']['brand'] == '' || $device_info['device']['model'] ==''){
    //         // Show Device Type
    //         $device_name = ucfirst($device_info['device']['deviceType']);
    //     }else{
    //         // Device Brand and Model
    //         $device_name = $device_info['device']['brand'].' '.$device_info['device']['model'];
    //     }
    //     $query_writer = $conn->prepare("INSERT INTO tt_visitor(ipaddress, url, jsondata, page_type, page_id) VALUES('$userIP', '$current_url', '$device_info_json_api', '$pagetype', '$pageid')");
    //     $query_writer->execute();

    //     if($pagetype == 'post'){
    //         $query_reader = $conn->prepare("UPDATE tt_post SET post_read = post_read + 1 WHERE id = '$pageid'");
    //         $query_reader->execute();
    //     }
    // }
}

// Genarete random string
function randomString() {
    $length = 8; // First 8 random characters
    $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    $randomString = '';
    $charCount = strlen($characters);

    // Generate 8 random letters
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[random_int(0, $charCount - 1)];
    }

    // Get the last 4 digits of the timestamp
    $timestamp = time(); // Current timestamp
    $last4Digits = substr($timestamp, -4);

    // Mapping for number-to-character conversion
    $map = [
        '1' => 'a', '2' => 'B', '3' => 'c', '4' => 'D',
        '5' => 'e', '6' => 'F', '7' => 'g', '8' => 'H',
        '9' => 'i', '0' => 'J'
    ];

    // Convert last 4 digits to characters
    $timestampString = '';
    for ($i = 0; $i < 4; $i++) {
        $timestampString .= $map[$last4Digits[$i]];
    }

    // Combine and return the final unique string
    return $randomString . $timestampString;
}


// Image Proccesing
function image_handler($source_image,$destination,$tn_w = 100,$tn_h = 100,$quality = 80,$wmsource = false) {

  // The getimagesize functions provides an "imagetype" string contstant, which can be passed to the image_type_to_mime_type function for the corresponding mime type
  $info = getimagesize($source_image);
  $imgtype = image_type_to_mime_type($info[2]);

  // Then the mime type can be used to call the correct function to generate an image resource from the provided image
  switch ($imgtype) {
  case 'image/jpeg':
    $source = imagecreatefromjpeg($source_image);
    break;
  case 'image/gif':
    $source = imagecreatefromgif($source_image);
    break;
  case 'image/png':
    $source = imagecreatefrompng($source_image);
    break;
  default:
    return false;
  }

  // Now, we can determine the dimensions of the provided image, and calculate the width/height ratio
  $src_w = imagesx($source);
  $src_h = imagesy($source);
  $src_ratio = $src_w/$src_h;

  // Now we can use the power of math to determine whether the image needs to be cropped to fit the new dimensions, and if so then whether it should be cropped vertically or horizontally. We're just going to crop from the center to keep this simple.
  if ($tn_w/$tn_h > $src_ratio) {
  $new_h = $tn_w/$src_ratio;
  $new_w = $tn_w;
  } else {
  $new_w = $tn_h*$src_ratio;
  $new_h = $tn_h;
  }
  $x_mid = $new_w/2;
  $y_mid = $new_h/2;

  // Now actually apply the crop and resize!
  $newpic = imagecreatetruecolor(round($new_w), round($new_h));
  imagecopyresampled($newpic, $source, 0, 0, 0, 0, $new_w, $new_h, $src_w, $src_h);
  $final = imagecreatetruecolor($tn_w, $tn_h);
  imagecopyresampled($final, $newpic, 0, 0, ($x_mid-($tn_w/2)), ($y_mid-($tn_h/2)), $tn_w, $tn_h, $tn_w, $tn_h);

  // If a watermark source file is specified, get the information about the watermark as well. This is the same thing we did above for the source image.
  if($wmsource && file_exists($wmsource)) {
  $info = @getimagesize($wmsource);
  if ($info !== false) {
    $imgtype = image_type_to_mime_type($info[2]);
    $watermark = false;
    switch ($imgtype) {
      case 'image/jpeg':
        $watermark = @imagecreatefromjpeg($wmsource);
        break;
      case 'image/gif':
        $watermark = @imagecreatefromgif($wmsource);
        break;
      case 'image/png':
        $watermark = @imagecreatefrompng($wmsource);
        break;
    }

    // Only apply watermark if successfully loaded
    if ($watermark !== false) {
      // Determine the size of the watermark, because we're going to specify the placement from the top left corner of the watermark image, so the width and height of the watermark matter.
      $wm_w = imagesx($watermark);
      $wm_h = imagesy($watermark);

      // Now, figure out the values to place the watermark in the bottom right hand corner. You could set one or both of the variables to "0" to watermark the opposite corners, or do your own math to put it somewhere else.
      $wm_x = $tn_w - $wm_w;
      $wm_y = $tn_h - $wm_h;

      // Copy the watermark onto the original image
      // The last 4 arguments just mean to copy the entire watermark
      imagecopy($final, $watermark, $wm_x, $wm_y, 0, 0, $tn_w, $tn_h);
      imagedestroy($watermark);
    }
  }
  }

  // Ok, save the output as a jpeg, to the specified destination path at the desired quality.
  // You could use imagepng or imagegif here if you wanted to output those file types instead.
  if(Imagejpeg($final,$destination,$quality)) {
  return true;
  }

  // If something went wrong
  return false;

}

function InsertData($table_name, $data) {
    global $conn;

    try {
        // Prepare column names and placeholders
        $columns = implode(', ', array_keys($data));
        $placeholders = implode(', ', array_fill(0, count($data), '?'));

        // Prepare SQL query
        $entry_sql = "INSERT INTO $table_name ($columns) VALUES ($placeholders)";
        $entry_doc = $conn->prepare($entry_sql);

        // Bind the values
        $values = array_values($data);
        foreach ($values as $index => $value) {
            $entry_doc->bindValue($index + 1, $value);
        }

        // Execute the query
        if ($entry_doc->execute()) {
            return $conn->lastInsertId();
        } else {
            return false;
        }

    } catch (PDOException $e) {
        error_log($e->getMessage());
        return false;
    }
}


// Function to check if the file is an image based on its extension
function isImage($filename) {
    // List of common image extensions, including WebP
    $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];

    // Get the file extension
    $fileExtension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));

    // Check if the extension is in the list of image extensions
    if (in_array($fileExtension, $imageExtensions)) {
      return 'image';
    }else {
      return $fileExtension;
    }
}

// Functions For ID Cards
// Function to create an image by loading the background image
function createImage($imagePath) {
    $info = getimagesize($imagePath);
    if (!$info) {
        throw new Exception("File is not a valid image: $imagePath");
    }

    switch ($info[2]) {
        case IMAGETYPE_JPEG:
            $image = imagecreatefromjpeg($imagePath);
            break;
        case IMAGETYPE_PNG:
            $image = imagecreatefrompng($imagePath);
            break;
        case IMAGETYPE_GIF:
            $image = imagecreatefromgif($imagePath);
            break;
        default:
            throw new Exception("Unsupported image type: " . $info['mime']);
    }

    if (!$image) {
        throw new Exception("Failed to create image from file: $imagePath");
    }

    return $image;
}


// Function to add text to the image
function addTextToImage($image, $text, $fontPath, $fontSize = 20, $textColor = [0, 0, 0], $x = 0, $y = 0) {
    // Get the image dimensions
    $imageWidth = imagesx($image);
    $imageHeight = imagesy($image);

    // Allocate text color
    $color = imagecolorallocate($image, $textColor[0], $textColor[1], $textColor[2]);

    // Get the bounding box of the text
    $textBoundingBox = imagettfbbox($fontSize, 0, $fontPath, $text);

    // Calculate text height and width
    $textHeight = abs($textBoundingBox[5] - $textBoundingBox[1]);
    $textWidth = abs($textBoundingBox[4] - $textBoundingBox[0]);

    // If X position is 'center', calculate the center position
    if ($x == 'center') {
        $x = ($imageWidth - $textWidth) / 2; // Center horizontally
    }

    // Adjust Y position (based on text height)
    $y = $y + $textHeight;

    // Add the text to the image
    imagettftext($image, $fontSize, 0, $x, $y, $color, $fontPath, $text);

    return $image;
}

function addImageToImage($image, $imagePath, $y = 0, $x = 0, $width = 0, $height = 0, $borderSize = 0, $borderColor = [0, 0, 0]) {
    // Load the overlay image
    $fileExtension = strtolower(pathinfo($imagePath, PATHINFO_EXTENSION));

    if ($fileExtension == 'jpg' || $fileExtension == 'jpeg') {
        $overlayImage = imagecreatefromjpeg($imagePath);
    } elseif ($fileExtension == 'png') {
        $overlayImage = imagecreatefrompng($imagePath);
    }

    $overlayWidth = imagesx($overlayImage);
    $overlayHeight = imagesy($overlayImage);

    // If width and height are not set, use original size
    if ($width == 0) {
        $width = $overlayWidth;
    }
    if ($height == 0) {
        $height = $overlayHeight;
    }

    // Center horizontally if needed
    if ($x == 'center') {
        $x = (imagesx($image) - $width) / 2;
    }

    // Resize overlay image
    $resizedOverlayImage = imagecreatetruecolor($width, $height);
    imagealphablending($resizedOverlayImage, false);
    imagesavealpha($resizedOverlayImage, true);
    imagecopyresampled($resizedOverlayImage, $overlayImage, 0, 0, 0, 0, $width, $height, $overlayWidth, $overlayHeight);

    // Add border if border size > 0
    if ($borderSize > 0) {
        $borderColorAllocated = imagecolorallocate($resizedOverlayImage, $borderColor[0], $borderColor[1], $borderColor[2]);
        // Draw rectangle around image
        imagerectangle(
            $resizedOverlayImage,
            0, 0,
            $width - 1, $height - 1,
            $borderColorAllocated
        );
    }

    // Copy overlay image onto main image
    imagecopy($image, $resizedOverlayImage, $x, $y, 0, 0, $width, $height);

    // Free memory
    imagedestroy($overlayImage);
    imagedestroy($resizedOverlayImage);

    return $image;
}


// Function to save the final image
function saveFinalImage($image, $outputPath) {
    // Save the image
    imagejpeg($image, $outputPath, 100); // 100 means highest quality

    // Free memory
    imagedestroy($image);
}


// Update data in a specified table based on conditions
// Function to update data in a specified table based on conditions
function UpdateData($table_name, $column_name_where, $column_value, $data_for_update) {
    global $conn; // Import global variables, including the database connection

    // Construct the SQL query
    $sql = "UPDATE $table_name SET ";

    $updates = [];
    foreach ($data_for_update as $column => $value) {
        $updates[] = "$column = :$column";
    }

    $sql .= implode(', ', $updates);
    $sql .= " WHERE $column_name_where = :column_value";

    // Prepare the SQL query
    $stmt = $conn->prepare($sql);

    // Bind parameters for the WHERE clause
    $stmt->bindParam(':column_value', $column_value, PDO::PARAM_STR);

    // Bind parameters for the update values
    foreach ($data_for_update as $column => &$value) {
        $stmt->bindParam(":$column", $value);
    }

    // Execute the query
    return $stmt->execute();
}


// Function to delete data from a specified table based on conditions
function deleteData($table_name, $column_name_where, $column_value_for_delete) {
    global $conn; // Import global variables, including the database connection

    // Construct the SQL query
    $sql = "DELETE FROM $table_name WHERE $column_name_where = :column_value_for_delete";

    // Prepare the SQL query
    $stmt = $conn->prepare($sql);

    // Bind the parameter for the WHERE clause
    $stmt->bindParam(':column_value_for_delete', $column_value_for_delete, PDO::PARAM_STR);

    // Execute the query
    if ($stmt->execute()) {
        $rowCount = $stmt->rowCount(); // Get the number of affected rows

        if ($rowCount > 0) {
            return true; // Deletion successful
        } else {
            return false; // No matching rows found to delete
        }
    } else {
        return false; // Error executing the query
    }
}


// Retrieve data from a specified table with custom SQL logic
// $data = showAllttdata("table_name", "cusom_query");
function showAllttdata($table_name, $custom_sql = "") {
    // Access the global $conn variable within the function
    global $conn;

    // Construct the SQL query with custom logic
    $sql = "SELECT * FROM $table_name $custom_sql";
    // Prepare and execute the query
    $stmt = $conn->prepare($sql);
    $stmt->execute();

    // Fetch all rows as an associative array
    $data = $stmt->fetchAll(PDO::FETCH_ASSOC);

    return $data;
}

// Get Post Tags
function showArticleTopic() {
    // Access the global $conn variable within the function
    global $conn;

    // Construct the SQL query with custom logic
    $sql = "SELECT PostTopic FROM mahamudfutureit_article WHERE PostTopic IS NOT NULL AND PostTopic != ''";
    // Prepare and execute the query
    $stmt = $conn->prepare($sql);
    $stmt->execute();

    // Fetch all rows as an associative array
    $data = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $mergedTopics = []; // Initialize an empty array to store merged topics

    foreach ($data as $topics) {
        $decodedTopics = json_decode($topics['PostTopic'], true); // Decode JSON to array

        if (is_array($decodedTopics)) {
            $mergedTopics = array_merge($mergedTopics, $decodedTopics); // Merge into main array
        }
    }

    // Remove duplicate values if needed
    $mergedTopics = array_unique($mergedTopics);

    return $mergedTopics;
}

// Get Post Tags
function showHotTopic() {
    // Access the global $conn variable within the function
    global $conn;

    // Construct the SQL query with custom logic
    $sql = "SELECT PostTopic FROM mahamudfutureit_article WHERE PostTopic IS NOT NULL AND PostTopic != '' ORDER BY  PostDatePublic  DESC LIMIT 50";
    // Prepare and execute the query
    $stmt = $conn->prepare($sql);
    $stmt->execute();

    // Fetch all rows as an associative array
    $data = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $mergedTopics = []; // Initialize an empty array to store merged topics

    foreach ($data as $topics) {
        $decodedTopics = json_decode($topics['PostTopic'], true); // Decode JSON to array

        if (is_array($decodedTopics)) {
            $mergedTopics = array_merge($mergedTopics, $decodedTopics); // Merge into main array
        }
    }

    // Step 1: Count frequencies of each element
    $frequency = array_count_values($mergedTopics);

    // Step 2: Sort array by frequency, descending order
    arsort($frequency);

    // Step 3: Get the sorted keys (topics) and remove duplicates
    $sorted_data = array_keys($frequency);

    $top_10 = array_slice($sorted_data, 0, 10);

    return $top_10;
}

function showSingleItem($table_name, $custom_sql = "") {
    // Access the global $conn variable within the function
    global $conn;

    // Construct the SQL query with custom logic
    $sql = "SELECT * FROM $table_name $custom_sql";
    // Prepare and execute the query
    $stmt = $conn->prepare($sql);
    $stmt->execute();

    // Fetch all rows as an associative array
    $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
    return $data[0];
}


function getRowCount($table_name, $custom_sql = "") {
    // Access the global $conn variable within the function
    global $conn;

    // Construct the SQL query with custom logic to count rows
    $sql = "SELECT COUNT(*) AS row_count FROM $table_name $custom_sql";

    // Prepare and execute the query
    $stmt = $conn->prepare($sql);
    $stmt->execute();

    // Fetch the row count as an associative array
    $result = $stmt->fetch(PDO::FETCH_ASSOC);

    // Extract and return the row count value
    return isset($result['row_count']) ? intval($result['row_count']) : 0;
}

// Retrieve a single data value from a specified table based on two columns
// getSingleValue('table_name', 'query_clumn_name', 'query_value', 'query_result_clumn_name'),
function getSingleValue($table_name, $column_name, $column_value, $target_column) {
    global $conn; // Import global variables, including the database connection

    // Construct the SQL query
    $sql = "SELECT $target_column FROM $table_name WHERE $column_name = :column_value LIMIT 1";

    // Prepare the SQL query
    $stmt = $conn->prepare($sql);

    // Bind parameters
    $stmt->bindParam(':column_value', $column_value, PDO::PARAM_STR);

    // Execute the query
    $stmt->execute();

    // Fetch a single row as an associative array
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    // Check if a result was found
    if ($row && isset($row[$target_column])) {
        // Return the value of the specified target column
        return $row[$target_column];
    } else {
        return null; // No matching record found or target column value is null
    }
}

//  Gallery
function getGallery($gallery_limit = 10, $gallery_offset = 0) {
    global $conn; // Use existing database connection

    $current_date = date('Y-m-d H:i:s');

    // Validate integers for LIMIT/OFFSET
    $gallery_limit = (int)$gallery_limit;
    $gallery_offset = (int)$gallery_offset;

    // Conditions & parameters
    $where_conditions = [
        "gallery_status = 'Published'",
        "gallery_date <= ?"
    ];
    $params = [$current_date];

    $where_sql = "WHERE " . implode(" AND ", $where_conditions);

    // Inject LIMIT/OFFSET directly
    $query = "SELECT * FROM mahamudfutureit_gallery
              $where_sql
              ORDER BY gallery_date DESC
              LIMIT $gallery_limit OFFSET $gallery_offset";

    $stmt = $conn->prepare($query);
    $stmt->execute($params);

    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}


// Gallery item// Gallery get by id or url
function isGallery($gallery_finder, $gallery_finder_type, $data_type = false) {
    global $conn; // Use existing database connection

    // Build search condition
    if ($gallery_finder_type == 'id') {
        $finder_query = "AND gallery_id = '$gallery_finder'";
    } elseif ($gallery_finder_type == 'url') {
        $finder_query = "AND gallery_url = '$gallery_finder'";
    } else {
        return $data_type ? false : null; // Invalid finder type
    }

    $current_date = date('Y-m-d H:i:s');

    // Build query
    $query = "SELECT * FROM mahamudfutureit_gallery
              WHERE gallery_status = 'Published'
              $finder_query
              AND gallery_date <= '$current_date'
              ORDER BY gallery_date DESC
              LIMIT 1";

    // Execute query
    $stmt = $conn->query($query);
    $get_gallery = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // If $data_type is true → return boolean
    if ($data_type === true) {
        return !empty($get_gallery);
    } else {
        return !empty($get_gallery) ? $get_gallery[0] : null;
    }
}


// Get Articles
// $mypost = showAllttdata("mahamudfutureit_article", "WHERE (PostCategory = '42' OR PostSubCategory LIKE '%\"42\"%') AND PostStatus  = 'published' ORDER BY PostDatePublic DESC ");
function getArticles($post_category = null, $post_limit = 10, $post_offset = 0,   $post_author = null ) {
    global $conn; // Use existing database connection

    $current_date = date('Y-m-d H:i:s'); // Get current date and time in the required format

    $where_conditions = ["PostStatus = 'published'", "PostDatePublic <= ?"];
    $params = [$current_date];

    // Check if category is set
    if ($post_category) {
        $where_conditions[] = "(PostCategory = ? OR PostSubCategory LIKE ?)";
        $params[] = $post_category;
        $params[] = '%"'.$post_category.'"%';  // Assuming JSON format
    }

    // Check if author is set
    if ($post_author) {
        $where_conditions[] = "PostAuthor = ?";
        $params[] = $post_author;
    }

    // Construct SQL query
    $where_sql = !empty($where_conditions) ? "WHERE " . implode(" AND ", $where_conditions) : "";
    $query = "SELECT * FROM mahamudfutureit_article $where_sql ORDER BY PostDatePublic DESC LIMIT $post_limit OFFSET $post_offset";

    // Prepare and execute statement
    $stmt = $conn->prepare($query);
    $stmt->execute($params);

    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Get archive
function getArchive($post_date = null, $post_limit = 10, $post_offset = 0) {
    global $conn;

    $where_conditions = [
        "PostStatus = 'published'",
        "PostDatePublic <= NOW()"  // exclude future posts
    ];
    $params = [];

    if ($post_date) {
        $where_conditions[] = "PostDayPublic = ?";
        $params[] = $post_date;
    }

    $where_sql = "WHERE " . implode(" AND ", $where_conditions);

    $query = "SELECT * FROM mahamudfutureit_article $where_sql ORDER BY PostDatePublic DESC LIMIT $post_limit OFFSET $post_offset";

    $stmt = $conn->prepare($query);
    $stmt->execute($params);

    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}


// Get Search news
function getSearchArticles($search_query, $post_limit = 10,  $post_offset = 0) {
    global $conn; // Use existing database connection

    $current_date = date('Y-m-d H:i:s'); // Get current date and time in the required format

    // Directly inserting the variables into the query
    $query = "SELECT * FROM mahamudfutureit_article WHERE PostStatus = 'published' AND (PostContent LIKE '%$search_query%' OR PostTitle LIKE '%$search_query%') AND PostDatePublic <= '$current_date' ORDER BY PostDatePublic DESC LIMIT $post_limit  OFFSET $post_offset";

    // Execute the query
    $stmt = $conn->query($query);

    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Get Search news
function getCountryArticles($location_type, $location_id, $post_limit = 10,  $post_offset = 0) {
    global $conn; // Use existing database connection

    $current_date = date('Y-m-d H:i:s'); // Get current date and time in the required format

    if ($location_type == 'upazila') {
      $country_query = "AND PostUpazila = '$location_id'";
    }elseif ($location_type == 'district') {
      $country_query = "AND PostDistrict = '$location_id'";
    }elseif ($location_type == 'division') {
      $country_query = "AND PostDivision = '$location_id'";
    }else {
      $country_query = "";
    }


    // Directly inserting the variables into the query
    $query = "SELECT * FROM mahamudfutureit_article WHERE  PostStatus = 'published' $country_query AND PostDatePublic <= '$current_date' ORDER BY PostDatePublic DESC LIMIT $post_limit  OFFSET $post_offset";

    // Execute the query
    $stmt = $conn->query($query);

    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Get Leade news
function getLeadArticles($post_limit = 10) {
    global $conn; // Use existing database connection

    $current_date = date('Y-m-d H:i:s'); // Get current date and time in the required format

    // Directly inserting the variables into the query
    $query = "SELECT * FROM mahamudfutureit_article WHERE PostStatus = 'published' AND PostLead = 'on' AND PostDatePublic <= '$current_date' ORDER BY PostDatePublic DESC LIMIT $post_limit";

    // Execute the query
    $stmt = $conn->query($query);

    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Get Spot news
function getSpotLightArticles($post_limit = 10) {
    global $conn; // Use existing database connection

    $current_date = date('Y-m-d H:i:s'); // Get current date and time in the required format

    // Directly inserting the variables into the query
    $query = "SELECT * FROM mahamudfutureit_article WHERE PostStatus = 'published' AND PostSpotlight = 'on' AND PostDatePublic <= '$current_date' ORDER BY PostDatePublic DESC LIMIT $post_limit";

    // Execute the query
    $stmt = $conn->query($query);

    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Get Most popular
function getPopularArticles($post_limit = 10) {
    global $conn; // Use existing database connection

    $current_date = date('Y-m-d H:i:s'); // Get current date and time in the required format

    // Directly inserting the variables into the query
    $query = "SELECT * FROM mahamudfutureit_article WHERE PostStatus = 'published' AND PostDatePublic <= '$current_date' ORDER BY ViewCount DESC LIMIT $post_limit";

    // Execute the query
    $stmt = $conn->query($query);

    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Get Most popular
function getRecentArticles($post_limit = 10) {
    global $conn; // Use existing database connection

    $current_date = date('Y-m-d H:i:s'); // Get current date and time in the required format

    // Directly inserting the variables into the query
    $query = "SELECT * FROM mahamudfutureit_article WHERE PostStatus = 'published' AND PostDatePublic <= '$current_date' ORDER BY PostDatePublic DESC LIMIT $post_limit";

    // Execute the query
    $stmt = $conn->query($query);

    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Get Video
function getVideos($post_limit = 10, $post_category = '') {
    global $conn; // Use existing database connection

    $current_date = date('Y-m-d H:i:s'); // Get current date and time in the required format

    if ($post_category != '') {
        $post_category_and = "AND (PostCategory = '$post_category' OR PostSubCategory LIKE '%\"$post_category\"%')";
    } else {
        $post_category_and = "";
    }

    // Directly inserting the variables into the query
    $query = "SELECT * FROM mahamudfutureit_article WHERE PostStatus = 'published' AND PageContentType = 'video' $post_category_and AND PostDatePublic <= '$current_date' ORDER BY PostDatePublic DESC LIMIT $post_limit";

    // Execute the query
    $stmt = $conn->query($query);

    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Get Topic Article
function getTopicsArticle($post_topic, $post_limit = 10, $post_offset = 0) {
    global $conn; // Use existing database connection

    $current_date = date('Y-m-d H:i:s'); // Get current date and time in the required format


    // Directly inserting the variables into the query
    $query = "SELECT * FROM mahamudfutureit_article WHERE PostStatus = 'published' AND PostTopic LIKE '%\"$post_topic\"%' AND PostDatePublic <= '$current_date' ORDER BY PostDatePublic DESC LIMIT $post_limit OFFSET $post_offset";

    // Execute the query
    $stmt = $conn->query($query);

    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Get Topic Link
function getTopicsUrl($post_topic) {
    global $conn, $site_domain; // Use existing database connection
    return $site_domain."topic/".urlencode($post_topic)."/";
}



// Get Leade news
function getTickerArticles($post_limit = 10) {
    global $conn; // Use existing database connection

    $current_date = date('Y-m-d H:i:s'); // Get current date and time in the required format

    // Directly inserting the variables into the query
    $query = "SELECT * FROM mahamudfutureit_article WHERE PostStatus = 'published' AND PostTicker = 'on' AND PostDatePublic <= '$current_date' ORDER BY PostDatePublic DESC LIMIT $post_limit";

    // Execute the query
    $stmt = $conn->query($query);

    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}


// Get Leade news
function getUserArticles($userid, $post_limit = 10, $post_offset = 0) {
    global $conn; // Use existing database connection

    $current_date = date('Y-m-d H:i:s'); // Get current date and time in the required format

    // Directly inserting the variables into the query
    $query = "SELECT * FROM mahamudfutureit_article WHERE PostStatus = 'published' AND PostAuthor = '$userid' AND PostDatePublic <= '$current_date' ORDER BY PostDatePublic DESC LIMIT $post_limit OFFSET $post_offset";

    // Execute the query
    $stmt = $conn->query($query);

    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}


// article get by id or url
function isCategory($category_finder, $category_finder_type, $data_type = false) {
    global $conn; // Use existing database connection

    if ($category_finder_type == 'id') {
      $finder_query = "AND CategoryID = '$category_finder'";
    }elseif ($category_finder_type == 'url') {
      $finder_query = "AND CategoryURL = '$category_finder'";
    }

    $current_date = date('Y-m-d H:i:s'); // Get current date and time in the required format

    // Directly inserting the variables into the query
    $query = "SELECT * FROM mahamudfutureit_category WHERE CategorySataus = 'Published' $finder_query  ORDER BY CategoryAdd DESC LIMIT 1";

    // Execute the query
    $stmt = $conn->query($query);
    $get_category = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // If Datatype Ture, return true of false
    if ($data_type == true) {
      if (!empty($get_category)) {
        return true;
      }else {
        return false;
      }
    }else {
      return $get_category[0];
    }
}

// article get by id or url
function allArticles() {
    global $conn; // Use existing database connection

    $current_date = date('Y-m-d H:i:s'); // Get current date and time in the required format

    // Directly inserting the variables into the query
    $query = "SELECT * FROM mahamudfutureit_article WHERE PostStatus = 'published' AND PostDatePublic <= '$current_date' ORDER BY PostDatePublic DESC ";

    // Execute the query
    $stmt = $conn->query($query);
    $get_article = $stmt->fetchAll(PDO::FETCH_ASSOC);
    return $get_article;
}

// article get by id or url
function isVideo($video_finder,  $data_type = false) {
    global $conn; // Use existing database connection

    // Directly inserting the variables into the query
    $query = "SELECT * FROM mahamudfutureit_video WHERE ID = '$video_finder'   LIMIT 1";

    // Execute the query
    $stmt = $conn->query($query);
    $get_video = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // If Datatype Ture, return true of false
    if ($data_type == true) {
      if (!empty($get_video)) {
        return true;
      }else {
        return false;
      }
    }else {
      return $get_video[0];
    }
}

// article get by id or url
function isArticles($article_finder, $article_finder_type, $data_type = false) {
    global $conn; // Use existing database connection

    if ($article_finder_type == 'id') {
      $finder_query = "AND PostId = '$article_finder'";
    }elseif ($article_finder_type == 'url') {
      $finder_query = "AND PostURL = '$article_finder'";
    }

    $current_date = date('Y-m-d H:i:s'); // Get current date and time in the required format

    // Directly inserting the variables into the query
    $query = "SELECT * FROM mahamudfutureit_article WHERE PostStatus = 'published' $finder_query AND PostDatePublic <= '$current_date' ORDER BY PostDatePublic DESC LIMIT 1";

    // Execute the query
    $stmt = $conn->query($query);
    $get_article = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // If Datatype Ture, return true of false
    if ($data_type == true) {
      if (!empty($get_article)) {
        return true;
      }else {
        return false;
      }
    }else {
      return $get_article[0];
    }
}

// article get by id or url
function isAuthArticles($article_finder, $article_finder_type, $data_type = false) {
    global $conn; // Use existing database connection

    if ($article_finder_type == 'id') {
      $finder_query = " PostId = '$article_finder'";
    }elseif ($article_finder_type == 'url') {
      $finder_query = " PostURL = '$article_finder'";
    }

    $current_date = date('Y-m-d H:i:s'); // Get current date and time in the required format

    // Directly inserting the variables into the query
    $query = "SELECT * FROM mahamudfutureit_article WHERE $finder_query   ORDER BY PostDatePublic DESC LIMIT 1";

    // Execute the query
    $stmt = $conn->query($query);
    $get_article = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // If Datatype Ture, return true of false
    if ($data_type == true) {
      if (!empty($get_article)) {
        return true;
      }else {
        return false;
      }
    }else {
      return $get_article[0];
    }
}

// Get Article Part
function articlePart($articles_array, $start_value, $limit_value) {
    // Convert 1-based index to 0-based index
    $start_index = $start_value - 1;

    // Extract the required portion of the array
    return array_slice($articles_array, $start_index, $limit_value);
}

// Get Feaured Image
function articleImg($article_id, $image_type = "featured"){
  global $advancenews, $site_domain;

  $article_default_image = $advancenews['ArticleDefaultFeatured']; // Default Image

  $article_date = getSingleValue('mahamudfutureit_article', 'PostId', $article_id , 'PostDate'); // Article Date

  $image_directory = "uploads/".date('Y', strtotime($article_date))."/".date('m', strtotime($article_date))."/"; // Image Directory

  // Article Featured Image
  $article_featured_image_name = getSingleValue('mahamudfutureit_article', 'PostId', $article_id , 'PostImage');

  if ($article_featured_image_name !='' && file_exists($image_directory.$article_featured_image_name)) {
    $final_featured_image = $site_domain.$image_directory.$article_featured_image_name;
  }else {
    $final_featured_image = $article_default_image;
  }


  if ($image_type == 'featured') {

    $final_image = $final_featured_image;

  }elseif ($image_type == 'og') {
    $article_og_image_name = getSingleValue('mahamudfutureit_article', 'PostId', $article_id , 'PostImageOG');

    if ($article_og_image_name !='' && file_exists($image_directory.$article_og_image_name)) {
      $final_image = $site_domain.$image_directory.$article_og_image_name;
    }else {
      $final_image = $final_featured_image;
    }
  }



  // $year = $site_domain."uploads/".date('Y', strtotime($article_date))."/".date('m', strtotime($article_date))."/".$article_featured_image;

  return $final_image;
}


function articleTime($datetime) {
    $now = new DateTime();
    $past = new DateTime($datetime);
    $diff = $now->diff($past);

    // If more than 24 hours (1 day) have passed, show the date in Bengali
    if ($diff->d >= 1) {
        return dokanDate($past->format('j F Y')); // Format like ১৫ মার্চ ২০২৫
    }

    if ($diff->h >= 1) {
        return bnNumber($diff->h) . ' ঘন্টা আগে'; // Show hours (ঘন্টা আগে)
    }

    if ($diff->i > 0) {
        return bnNumber($diff->i) . ' মিনিট আগে'; // Show minutes (মিনিট আগে)
    }

    if ($diff->s > 0) {
        return 'এখনই'; // Show "Just now" (এখনই)
    }

    return 'এখনই'; // Default if no difference
}

// Article Time EN
function articleTimeEN($datetime) {
    $now = new DateTime();
    $past = new DateTime($datetime);
    $diff = $now->diff($past);

    // Check year difference
    if ($diff->y >= 1) {
        return $diff->y . ' years';
    }

    // Check month difference
    if ($diff->m >= 1) {
        return $diff->m . ' mon';
    }

    // Check week difference
    if ($diff->d >= 7) {
        $weeks = floor($diff->d / 7);
        return $weeks . ' weeks';
    }

    // Check day difference
    if ($diff->d >= 1) {
        return $diff->d . ' day';
    }

    // Check hour difference
    if ($diff->h >= 1) {
        return $diff->h . ' hrs';
    }

    // Check minute difference
    if ($diff->i >= 1) {
        return $diff->i . ' min';
    }

    // Seconds or less
    return 'now';
}


function articleLink($article_id){
  global $site_domain, $advancenews;

  $article_slag = getSingleValue('mahamudfutureit_article', 'PostId', $article_id, 'PostURL');
  $article_cat_id = getSingleValue('mahamudfutureit_article', 'PostId', $article_id, 'PostCategory');
  $article_cat_slag = getSingleValue('mahamudfutureit_category', 'CategoryID', $article_cat_id, 'CategoryURL');

  if ($advancenews['Post_Parmalink'] == 'pl_one') {
    $post_parmalink = $site_domain.$advancenews["Post_Parmalink_text"].'/'.$article_id.'/'.$article_slag.'/';
  }elseif ($advancenews['Post_Parmalink'] == 'pl_two') {
    $post_parmalink = $site_domain.$advancenews["Post_Parmalink_text"].'/'.$article_id.'/';
  }elseif ($advancenews['Post_Parmalink'] == 'pl_three') {
    $post_parmalink = $site_domain.$advancenews["Post_Parmalink_text"].'/'.$article_slag.'/';
  }elseif ($advancenews['Post_Parmalink'] == 'pl_four') {
    $post_parmalink = $site_domain.$article_cat_slag.'/'.$article_slag.'/';
  }

  return $post_parmalink;
}
//  Article Category name, url
function articleCategory($article_id, $data_type){
  global $site_domain, $advancenews;

  $article_cat_id = getSingleValue('mahamudfutureit_article', 'PostId', $article_id , 'PostCategory');
  $article_cat_name = getSingleValue('mahamudfutureit_category', 'CategoryID', $article_cat_id , 'CategoryName');
  $article_cat_url = getSingleValue('mahamudfutureit_category', 'CategoryID', $article_cat_id , 'CategoryURL');

  if ($article_cat_name != '') {
    $article_cat_name = getSingleValue('mahamudfutureit_category', 'CategoryID', $article_cat_id , 'CategoryName');
    $article_cat_url = $site_domain.getSingleValue('mahamudfutureit_category', 'CategoryID', $article_cat_id , 'CategoryURL')."/";
  }else {
    $article_cat_name = 'আর্কাইভ';
    $article_cat_url = 'javascript:void(0)';
  }

  if ($data_type == 'name') {
    return $article_cat_name ;
  }elseif($data_type == 'url') {
    return $article_cat_url;
  }

}

//  Article Category name, url
function categoryInfo($article_cat_id, $data_type){
  global $site_domain, $advancenews;

  $article_cat_name = getSingleValue('mahamudfutureit_category', 'CategoryID', $article_cat_id , 'CategoryName');
  $article_cat_url = getSingleValue('mahamudfutureit_category', 'CategoryID', $article_cat_id , 'CategoryURL');
  $article_cat_icon = getSingleValue('mahamudfutureit_category', 'CategoryID', $article_cat_id , 'CategoryIcon');

  if ($article_cat_name != '') {
    $article_cat_name = getSingleValue('mahamudfutureit_category', 'CategoryID', $article_cat_id , 'CategoryName');
    $article_cat_url = $site_domain.getSingleValue('mahamudfutureit_category', 'CategoryID', $article_cat_id , 'CategoryURL')."/";
  }else {
    $article_cat_name = 'আর্কাইভ';
    $article_cat_url = 'javascript:void(0)';
  }

  if ($article_cat_icon != '') {
    $article_cat_icon = '<i class="'.$article_cat_icon.'"></i>';
  }else {
    $article_cat_icon = '';
  }

  if ($data_type == 'name') {
    return $article_cat_name ;
  }elseif($data_type == 'url') {
    return $article_cat_url;
  }elseif($data_type == 'icon') {
    return $article_cat_icon;
  }
}

function articleContent($content) {
    global $advancenews;

    $content = preg_replace_callback('/\[MAHAMUDFUTUREIT-([A-Z]+):(\d+)\]/i', function($matches) {
        global $advancenews;
        $type = strtoupper($matches[1]);
        $value = $matches[2];

        if ($type == 'POST') {
            if (isArticles($value , 'id', true)) {
                $this_article = isArticles($value , 'id');
                $shortCodeContent = '
                <div class="read_also_post d-print-none row justify-content-center">
                  <div class="col-md-9">
                    <div class="rmp_container p-2">
                      <a href="'.articleLink($this_article['PostId']).'" class="row align-items-center">
                        <div class="col-8">
                          <span class="fw-bold">আরো পড়ুন</span>
                          <h3 class="h2 mt-1 text-dark">'.$this_article['PostTitle'].'</h3>
                        </div>
                        <div class="col-4">
                          <img class="w-100" src="'.$advancenews['ArticlePreloader'].'"  data-src="'.articleImg($this_article['PostId'], 'featured').'" alt="'.htmlentities($this_article['PostTitle'], ENT_QUOTES, 'utf-8').'">
                        </div>
                      </a>
                    </div>
                  </div>
                </div>
                ';
                return $shortCodeContent;
            }
        }
    }, $content);

    $inPostAds1 = showAds($advancenews['inPostAds1'], $advancenews['PostAdsCtl']);
    $inPostAds2 = showAds($advancenews['inPostAds2'], $advancenews['PostAdsCtl']);
    $inPostAds3 = showAds($advancenews['inPostAds3'], $advancenews['PostAdsCtl']);

    $parts = explode('</p>', $content);
    $lastIndex = count($parts) - 2;
    $newContent = '';

    foreach ($parts as $index => $part) {
        if (trim($part) == '') continue;

        $newContent .= $part.'</p>';

        if ($index >= $lastIndex) continue;

        if ($index == 0 && $inPostAds1 != '') {
            $newContent .= '<div class="tt-white my-3">'.$inPostAds1.'</div>';
        }
        elseif ($index == 1 && $inPostAds2 != '') {
            $newContent .= '<div class="tt-white my-3">'.$inPostAds2.'</div>';
        }
        elseif ($index == 2 && $inPostAds3 != '') {
            $newContent .= '<div class="tt-white my-3">'.$inPostAds3.'</div>';
        }
        elseif ($index > 2 && $inPostAds1 != '') {
            $newContent .= '<div class="tt-white my-3">'.$inPostAds1.'</div>';
        }
    }

    return $newContent;
}


function articleContentClean($content) {
    return preg_replace_callback('/\[MAHAMUDFUTUREIT-([A-Z]+):(\d+)\]/i', function($matches) {

    }, $content);
}


function noPost(){
  return "<span class='d-block p-3 rounded-3 border tt-text text-center '>কোন পোস্ট নেই !</span>";
}

//  Poll
function pollLink($poll_id){
  global $site_domain;
  return $site_domain.'opinion-poll/'.$poll_id.'/';
}

// Poll Finder Single
function isPoll($poll_id, $data_type = false) {
    global $conn; // Use existing database connection

    $current_date = date('Y-m-d H:i:s');

    // Build query
    $query = "SELECT * FROM mahamudfutureit_poll
              WHERE PollStatus = 'Published'
              AND PollID = :poll_id
              AND PollDatePublic <= :current_date
              ORDER BY PollDatePublic DESC
              LIMIT 1";

    // Prepare & execute
    $stmt = $conn->prepare($query);
    $stmt->execute([
        ':poll_id' => $poll_id,
        ':current_date' => $current_date
    ]);
    $get_poll = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // If $data_type is true → return boolean
    if ($data_type === true) {
        return !empty($get_poll);
    } else {
        return !empty($get_poll) ? $get_poll[0] : null;
    }
}

// Get All Poll
function getPoll($poll_limit = 10, $poll_offset = 0) {
    global $conn; // Use existing database connection

    $current_date = date('Y-m-d H:i:s');

    // Validate integers for LIMIT/OFFSET
    $poll_limit = (int)$poll_limit;
    $poll_offset = (int)$poll_offset;

    // Conditions & parameters
    $where_conditions = [
        "PollStatus = 'Published'",
        "PollDatePublic <= ?"
    ];
    $params = [$current_date];

    $where_sql = "WHERE " . implode(" AND ", $where_conditions);

    // Inject LIMIT/OFFSET directly
    $query = "SELECT * FROM mahamudfutureit_poll
              $where_sql
              ORDER BY PollDatePublic DESC
              LIMIT $poll_limit OFFSET $poll_offset";

    $stmt = $conn->prepare($query);
    $stmt->execute($params);

    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}


//  Get Poll Featured Image
function getPollImage($poll_id, $og_status = false){
  global $site_domain;
  global $advancenews;

  // Get Post Info and Date
  $date_offpost = new DateTime(getSingleValue('mahamudfutureit_poll', 'PollID', $poll_id, 'PollDate'));
  $year_offpost = $date_offpost->format('Y');
  $month_offpost = $date_offpost->format('m');


  // Featured Image
  $featured_image_name = getSingleValue('mahamudfutureit_poll', 'PollID', $poll_id, 'PollImage');
  // return  $featured_image_name;
  if ($featured_image_name !='') {
    $final_featured_image = $site_domain."uploads/".$year_offpost."/".$month_offpost."/".$featured_image_name;
  }else {
    $final_featured_image = $advancenews['Poll_DF_Img'];
  }

  // OG Image
  $featured_ogimage_name = getSingleValue('mahamudfutureit_poll', 'PollID', $poll_id, 'PollImageOG');
  if ($featured_ogimage_name !='') {
    $final_featured_ogimage = $site_domain."uploads/".$year_offpost."/".$month_offpost."/".$featured_ogimage_name;
  }else {
    $final_featured_ogimage = $final_featured_image;
  }

  // SHow Target Image
  if ($og_status == true) {
    return $final_featured_ogimage;
  }else {
    return $final_featured_image;
  }
}

// Convert bangla Number
function bnNumber($number) {
    // Define arrays mapping Arabic numerals to Bengali numerals
    $arabicNumerals = range(0, 9);
    $bengaliNumerals = ['০', '১', '২', '৩', '৪', '৫', '৬', '৭', '৮', '৯'];

    // Convert the number to a string
    $numberStr = (string)$number;

    // Initialize an empty result string
    $result = '';

    // Iterate through the characters in the number string
    for ($i = 0; $i < strlen($numberStr); $i++) {
        $char = $numberStr[$i];

        // Check if the character is a numeric digit
        if (in_array($char, $arabicNumerals)) {
            // Find the corresponding Bengali numeral and append it to the result
            $bengaliDigit = $bengaliNumerals[array_search($char, $arabicNumerals)];
            $result .= $bengaliDigit;
        } else {
            // If the character is not a numeric digit, keep it unchanged
            $result .= $char;
        }
    }

    return $result;
}

// Get User Information
function getUser($value, $target_column = null) {
    global $conn; // Use the global database connection

    try {
        // Determine the target column
        $target_column = $target_column ?: 'UserID';

        // Construct the SQL query
        $sql = "SELECT * FROM tt_accounts WHERE $target_column = :value LIMIT 1";

        // Prepare the SQL query
        $stmt = $conn->prepare($sql);

        if (!$stmt) {
            return false; // Return false if the statement preparation fails
        }

        // Bind the parameter
        $stmt->bindParam(':value', $value, PDO::PARAM_STR);

        // Execute the query
        $stmt->execute();

        // Fetch a single row as an associative array
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        // Check if a result was found and return the row or false
        return $row ? $row : false;
    } catch (Exception $e) {
        return false; // Return false on failure
    }
}

// Get User ID
function isUser($user_id){
  global $site_domain;
  global $advancenews;
  global $conn;

  $user_by_url = getUser($user_id, 'UserUrl');
  $user_by_id = getUser($user_id, 'UserID');

  if (!empty($user_by_id)) {
    $user_data = $user_by_id;
  }elseif (!empty($user_by_url)) {
    $user_data = $user_by_url;
  }else {
    return false;
  }

  if ($user_data['AccountStatus'] == 'active' && $user_data['UserProfile'] == 'active') {
    return $user_data;
  }else {
    return false;
  }
}


// User Profile Link
function userProfile($user_id){
    global $site_domain;
    global $advancenews;
    global $conn;

    $user_profile_info = isUser($user_id);
    if ($user_profile_info != false) {

      if ($user_profile_info['UserUrl'] != '') {
        $user_slag = $user_profile_info['UserUrl'];
      }else {
        $user_slag = $user_profile_info['UserID'];
      }

      if ($advancenews['ttWriterAccountProfile'] == 'on') {
        return $site_domain.$advancenews['ttWriterAccountProfileParmalink'].'/'.$user_slag.'/';
      }else {
        return 'javascript:void(0)';
      }
    }else {
      return 'javascript:void(0)';
    }
}


// User Avater
function userAvater($uacc_id){
  global $conn, $site_domain, $advancenews; // Import global variables, database connection, and form data
  $uacc_avater =  getSingleValue('tt_accounts', 'UserID',  $uacc_id, 'UserAvater');
  if ($uacc_avater !='') {
    if (file_exists('uploads/user/'.$uacc_avater)) {
       return $site_domain.'uploads/user/'.$uacc_avater;
    }else {
      return $advancenews['PostWriterDefaultImage'];
    }
  }else {
    return $advancenews['PostWriterDefaultImage'];
  }
}




//  Get Featured Image
function getFeaturedImage($post_id, $og_status = false){
  global $site_domain;
  global $advancenews;

  // Get Post Info and Date
  $date_offpost = new DateTime(getSingleValue('mahamudfutureit_article', 'PostId', $post_id, 'PostDate'));
  $year_offpost = $date_offpost->format('Y');
  $month_offpost = $date_offpost->format('m');


  // Featured Image
  $featured_image_name = getSingleValue('mahamudfutureit_article', 'PostId', $post_id, 'PostImage');
  if ($featured_image_name !='') {
    $featured_image_path = $year_offpost."/".$month_offpost."/".$featured_image_name;

    // Check Featured Image hav or not
    if (file_exists("../uploads/".$featured_image_path)) {
        $final_featured_image = $site_domain."uploads/".$featured_image_path;
    }else {
      $final_featured_image = $advancenews['ArticleDefaultFeatured'];
    }
  }else {
    $final_featured_image = $advancenews['ArticleDefaultFeatured'];
  }

  // Featured Image
  $featured_ogimage_name = getSingleValue('mahamudfutureit_article', 'PostId', $post_id, 'PostImageOG');
  if ($featured_ogimage_name !='') {
    $featured_imageog_path = $year_offpost."/".$month_offpost."/".$featured_ogimage_name;

    // Check Featured Image hav or not
    if (file_exists("../uploads/".$featured_imageog_path)) {
        $final_featured_ogimage = $site_domain."uploads/".$featured_imageog_path;
    }else {
      $final_featured_ogimage = $final_featured_image;
    }
  }else {
    $final_featured_ogimage = $final_featured_image;
  }

  // SHow Target Image
  if ($og_status == true) {
    return $final_featured_ogimage;
  }else {
    return $final_featured_image;
  }
}

// Get Ads
function showAds($ads_data, $ads_control){
  global $advancenews;

  $ads_option_value = explode('<MAHAMUDFUTUREIT>', $ads_data);
  $ads_custom_code = $ads_option_value[0];
  $ads_photo_link = $ads_option_value[1];
  $ads_position_name = $ads_option_value[2];
  $ads_photo_src = $ads_option_value[3];

  if ($ads_control != 'on') {
    if ($ads_custom_code !='') {
      $ads_content = $ads_custom_code;
    }elseif ($ads_photo_src !='') {
      $ads_content = "<div>
              <a href='".$ads_photo_link."'>
                <img class='w-100' src='".$ads_photo_src."'>
              </a>
            </div>";
    }else {
      $ads_content = null;
    }
  }else {
    $ads_content = "<div style='font-family: sans-serif; background: #929292; padding: 36px; text-align: center; font-size: 22px;'>".$ads_position_name."</div>";
  }
  return $ads_content;
}

// User Activity account post lus login lust post
function userActivity($user_id, $type, $title, $information) {
    global $conn;

    try {
        $user_ip = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP) ?: 'UNKNOWN';
        $current_time = date('Y-m-d H:i:s'); // Use PHP for timestamp

        $sql = "INSERT INTO tt_account_log (user_id, type, title, description, user_ip, tt_time)
                VALUES (:user_id, :type, :title, :description, :user_ip, :tt_time)";

        $stmt = $conn->prepare($sql);
        $stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
        $stmt->bindParam(':type', $type, PDO::PARAM_STR);
        $stmt->bindParam(':title', $title, PDO::PARAM_STR);
        $stmt->bindParam(':description', $information, PDO::PARAM_STR);
        $stmt->bindParam(':user_ip', $user_ip, PDO::PARAM_STR);
        $stmt->bindParam(':tt_time', $current_time, PDO::PARAM_STR);

        return $stmt->execute(); // Returns true on success
    } catch (PDOException $e) {
        error_log("Database Error: " . $e->getMessage());
        return false;
    }
}


function countVisitor(){
  global $conn;
  $visitor_today = date('Y-m-d');
  $today_visitor = getSingleValue('mahamudfutureit_visitor', 'date', $visitor_today, 'visitor');
  if ($today_visitor !='') {
    $current_url = "http".((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "s" : "")."://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; // URL Address

    UpdateData('mahamudfutureit_visitor', 'date', $visitor_today ,array("visitor"=>$today_visitor+1 ));
  }else {
    InsertData('mahamudfutureit_visitor', array("date"=>$visitor_today,"visitor"=>1));
  }
}

// tt Popup
function ttPopaction($tt_option_id, $tt_action_link){ ?>
  <div class="modal fade" id="<?php echo $tt_option_id ?>"   data-bs-keyboard="false" tabindex="-1"  aria-hidden="true">
    <div class="modal-dialog  modal-sm modal-dialog-centered modal-dialog-scrollable">
      <div class="action_popup modal-content py-4 px-3 border-0 text-center ">
        <h5>Do you want to delete this item ? </h5>
        <span class="action_icon text-danger mb-2"><i class="bi bi-trash3"></i></span>
        <div class="row">
          <div class="col-6  text-end">
            <button data-bs-dismiss="modal" class="btn btn-secondary  btn-sm" type="button" name="button">Cancle</button>
          </div>
          <div class="col-6 text-start">
            <a href="<?php echo $tt_action_link ?>" class="btn btn-danger btn-sm">Delete</a>
          </div>
        </div>
      </div>
    </div>
  </div>
  <?php
}


// Bangla Date
function dokanDate($date){

  $month_e2b = array(
    "01" => "জানুয়ারি",
    "02" => "ফেব্রুয়ারি",
    "03" => "মার্চ",
    "04" => "এপ্রিল",
    "05" => "মে",
    "06" => "জুন",
    "07" => "জুলাই",
    "08" => "আগস্ট",
    "09" => "সেপ্টেম্বর",
    "10" => "অক্টোবর",
    "11" => "নভেম্বর",
    "12" => "ডিসেম্বর",
  );

  $date = date_create($date);

  $year = bnNumber($date->format('Y'));
  $month = $date->format('m');
  $day = bnNumber($date->format('d'));

  return $day.' '.$month_e2b[$month].' '.$year;

}

// Check Function Post Date Publish
function isPublished($date) {
    $givenDate = new DateTime($date);
    $currentDate = new DateTime();
    return $givenDate < $currentDate;
}

function dokanDateWithDay($date) {
    // Array to map English month numbers to Bengali month names
    $month_e2b = array(
        "01" => "জানুয়ারি",
        "02" => "ফেব্রুয়ারি",
        "03" => "মার্চ",
        "04" => "এপ্রিল",
        "05" => "মে",
        "06" => "জুন",
        "07" => "জুলাই",
        "08" => "আগস্ট",
        "09" => "সেপ্টেম্বর",
        "10" => "অক্টোবর",
        "11" => "নভেম্বর",
        "12" => "ডিসেম্বর",
    );

    // Array to map English day names to Bengali day names
    $day_e2b = array(
        "Sunday" => "রোববার",
        "Monday" => "সোমবার",
        "Tuesday" => "মঙ্গলবার",
        "Wednesday" => "বুধবার",
        "Thursday" => "বৃহস্পতিবার",
        "Friday" => "শুক্রবার",
        "Saturday" => "শনিবার",
    );

    // Create a DateTime object from the input date
    $dateObj = date_create($date);

    // Get the day name in English (e.g., "Sunday")
    $dayNameEnglish = $dateObj->format('l');

    // Convert the day name to Bengali
    $dayNameBengali = $day_e2b[$dayNameEnglish];

    // Extract year, month, and day
    $year = bnNumber($dateObj->format('Y')); // Convert year to Bengali numerals
    $month = $dateObj->format('m'); // Get month as two-digit string (e.g., "01" for January)
    $day = bnNumber($dateObj->format('d')); // Convert day to Bengali numerals

    // Get the Bengali month name
    $monthBengali = $month_e2b[$month];

    // Return the formatted Bangla date with day
    return $dayNameBengali . ', ' . $day . ' ' . $monthBengali . ' ' . $year;
}



// Create URl From String
function createUlink($string) {
    // Trim and limit the string to 30 characters
    $link = mb_strimwidth(trim($string), 0, 30, "");

    // Replace multiple spaces with a single hyphen
    $link = preg_replace('/\s+/', '-', $link);

    // URL encode the final result
    $p_url = rawurlencode($link);
    return $p_url;
}



// NUmber System Like K M etc
function formatNumber($number) {
    $suffix = '';

    if ($number >= 1000000) {
        $number = round($number / 1000000, 1);
        $suffix = 'M';
    } elseif ($number >= 1000) {
        $number = round($number / 1000, 1);
        $suffix = 'K';
    }

    return $number . $suffix;
}

// TT Alert
function ttAlert($alert_type, $aleart_conent){
  if ($alert_type == 'danger') {
    return '
    <div class="tt_alert danger  mt-3 mb-2">
      <p class="m-0 p-2"> <i class="pe-1 text-danger ri-settings-6-fill"></i> '.$aleart_conent.'  </p>
    </div>
    ';
  }elseif ($alert_type == 'success') {
    return '
    <div class="tt_alert success  mt-3 mb-2">
      <p class="m-0 p-2"> <i class="pe-1 text-success ri-check-double-line"></i> '.$aleart_conent.'</p>
    </div>
    ';
  }elseif ($alert_type == 'warning') {
    return '
    <div class="tt_alert warning mt-3 mb-2">
      <p class="m-0 p-2"> <i class="pe-1 text-warning ri-alert-line"></i> '.$aleart_conent.'</p>
    </div>
    ';
  }
}
//  Share Links
function shareNow(){
  ?>
  <div class="share-button">
    <div class="row align-items-center">
      <div class="col-12 col-md-3">
        <h5 class="pt-1 pb-md-0 text-center text-md-left pb-0 ">শেয়ার করুন</h5>
      </div>
      <div class="col-12 col-md-9 ">
        <!-- AddToAny BEGIN -->
        <div class="a2a_kit a2a_kit_size_32 a2a_default_style">
        <a class="a2a_button_facebook"></a>
        <a class="a2a_button_twitter"></a>
        <a class="a2a_button_email"></a>
        <a class="a2a_button_whatsapp"></a>
        <a class="a2a_button_telegram"></a>
        <a class="a2a_button_facebook_messenger"></a>
        <a class="a2a_button_copy_link"></a>
        <a class="a2a_button_print"></a>
        </div>
        <script async src="https://static.addtoany.com/menu/page.js"></script>
        <!-- AddToAny END -->
      </div>
    </div>
  </div>

  <?php
}
// Day ago
function timeAgo($datetime) {
    $now = new DateTime();
    $past = new DateTime($datetime);
    $diff = $now->diff($past);

    if ($diff->y > 0) {
        return $diff->y . ($diff->y > 1 ? ' years' : ' year');
    }
    if ($diff->m > 0) {
        return $diff->m . ($diff->m > 1 ? ' months' : ' month');
    }
    if ($diff->d > 0) {
        if ($diff->d == 1) {
            return '1 day';
        }
        return $diff->d . ' days';
    }
    if ($diff->h > 0) {
        if ($diff->h == 1) {
            return '1 hour';
        }
        return $diff->h . ' hours';
    }
    if ($diff->i > 0) {
        if ($diff->i == 1) {
            return '1 min';
        }
        return $diff->i . ' mins';
    }
    if ($diff->s > 0) {
        return 'Just now';
    }
    return 'Just now';
}



// User Avater
function userAvaterDB($uacc_id){
  global $conn, $site_domain, $advancenews; // Import global variables, database connection, and form data
  $uacc_avater =  getSingleValue('tt_accounts', 'UserID',  $uacc_id, 'UserAvater');
  if ($uacc_avater !='') {
    if (file_exists('../uploads/user/'.$uacc_avater)) {
       return $site_domain.'uploads/user/'.$uacc_avater;
    }else {
      return $advancenews['PostWriterDefaultImage'];
    }
  }else {
    return $advancenews['PostWriterDefaultImage'];
  }
}

// Video link Converter
function convertYouTubeUrlToEmbed($url) {
    // Parse the URL to get the video ID
    parse_str(parse_url($url, PHP_URL_QUERY), $query);

    // Check if the 'v' parameter exists in the query
    if (isset($query['v'])) {
        $videoId = $query['v'];
        // Create the embed link
        $embedUrl = "https://www.youtube.com/embed/{$videoId}?modestbranding=1&showinfo=0&rel=0";
        return $embedUrl;
    } else {
        return false;
    }
}

// Get Post Title
function getBlockTitle($category, $custom_title = null, $custom_link ="#", $custom_icon ="" ){
  global $site_domain, $advancenews;
  $category_content = categoryInfo($category, 'name')  ;

  // Category Icon
  $category_icon = getSingleValue('mahamudfutureit_category', 'CategoryID', $category , 'CategoryIcon');
  if ($category_icon !='') {
    $heading_icon = '<i class="'.getSingleValue('mahamudfutureit_category', 'CategoryID', $category , 'CategoryIcon').'"></i>';
  }else {
    $heading_icon = '<i class="'.$custom_icon.'"></i>';
  }


  // If Hav Valid Category
  if ($category !='') {
    $heading_title = $category_content;
    $heading_link = $site_domain.getSingleValue('mahamudfutureit_category', 'CategoryID', $category , 'CategoryURL').'/';
  }else {
    $heading_title = $custom_title;
    $heading_link = $custom_link;
  }


  // Get Layout and Show
  $heading_title_style = $advancenews['PostBlockHeaderStyle'];
  if ($heading_title_style == 1) {
    return '
    <div class="heading-postcard hp-1 d-flex justify-content-between align-items-center">
        <h2 class="m-0">
          <a class="hp-name" href="'.$heading_link.'"> '.$heading_icon.' '.$heading_title.'  </a>
        </h2>
        <a href="'.$heading_link.'" class="indicator-hp">আরো <i class="bi bi-chevron-right"></i></a>
    </div>
    ';
  }elseif ($heading_title_style == 2) {
    return '
    <div class="heading-postcard hp-2">
      <h2 class="m-0">
        <a href="'.$heading_link.'" class="flex">
          '.$heading_title.'<span class="long-line"></span>
        </a>
      </h2>
    </div>
    ';
  }elseif ($heading_title_style == 3) {
    return '
    <div class="heading-postcard hp-3">
        <h2>
          <a class="hp-name" href="'.$heading_link.'">  '.$heading_icon.' '.$heading_title.' </a>
          <a href="'.$heading_link.'" class="indicator-hp">আরো <i class="bi bi-chevron-right"></i></a>
        </h2>
    </div>
    ';
  }elseif ($heading_title_style == 4) {
    return '
    <div class="heading-postcard hp-4 d-flex justify-content-between align-items-center">
        <h2 class="m-0">
          <a class="hp-name" href="'.$heading_link.'"> '.$heading_icon.' '.$heading_title.'  </a>
        </h2>
        <a href="'.$heading_link.'" class="indicator-hp">আরো <i class="bi bi-chevron-right"></i></a>
    </div>
    ';
  }elseif ($heading_title_style == 5) {
    return '
    <a class="heading-postcard hp-5" href="'.$heading_link.'">
        <h2 class="m-0">'.$heading_title.'</h2>
        <span><i class="bi bi-chevron-right"></i> আরও</span>
    </a>
    ';
  }elseif ($heading_title_style == 6) {
    return '
    <div class="heading-postcard hp-6 d-flex justify-content-between align-items-center">
        <h2 class="m-0">
          <a class="hp-name" href="'.$heading_link.'"> '.$heading_icon.' '.$heading_title.' </a>
        </h2>
        <a href="'.$heading_link.'" class="indicator-hp">আরো <i class="bi bi-chevron-right"></i></a>
    </div>
    ';
  }elseif ($heading_title_style == 7) {
    return '
    <div class="heading-postcard hp-7 d-flex justify-content-between align-items-center">
        <h2 class="m-0">
          <a class="hp-name" href="'.$heading_link.'"> '.$heading_icon.' '.$heading_title.' </a>
        </h2>
        <a href="'.$heading_link.'" class="indicator-hp">আরো <i class="bi bi-chevron-right"></i></a>
    </div>
    ';
  }elseif ($heading_title_style == 8) {
    return '
    <div class="heading-postcard hp-8">
      <h2 class="m-0">
        <a href="'.$heading_link.'" class="flex">
            '.$heading_title.' <span class="long-line"></span>
        </a>
      </h2>
    </div>
    ';
  }elseif ($heading_title_style == 9) {
    return '
    <div class="heading-postcard hp-9 m-0">
        <h2 class="d-inline"><a href="'.$heading_link.'">  '.$heading_title.'</a></h2>
        <span class="heading-style-heading"></span>
        <span class="heading-style-heading-left"><a class="tt-text" href="'.$heading_link.'">আরও</a></span>
    </div>
    ';
  }elseif ($heading_title_style == 10) {
    return '
    <div class="heading-postcard hp-10">
         <h2 class="d-inline m-0"><a href="'.$heading_link.'">'.$heading_title.'</a></h2>
    </div>
    ';
  }


}
// Get Slider News for Homepage Slider
function getSliderArticles($post_limit = 5) {
    global $conn;
    $current_date = date('Y-m-d H:i:s');
    
    $query = "SELECT * FROM mahamudfutureit_article 
              WHERE PostStatus = 'published' 
              AND PostSlider = '1' 
              AND PostDatePublic <= '$current_date' 
              ORDER BY PostDatePublic DESC 
              LIMIT $post_limit";
    
    $stmt = $conn->query($query);
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
?>
