<?php
/*
	** URL a Function v1.0
	** Function to URL Item In a [ Function Accept Parameters ]
	** $url = The URL To url [ Example: www.google.com, www.facbook.com, www.youteup.com ]
	** $name = The Name [ Example: users, items, categories ]
	*/

function generateList($level, $parentId = null) {
    global $con;
    $whereClause = $parentId ? "AND acc_up = '$parentId'" : "";
    $sql = $con->prepare("SELECT * from level_acc WHERE lev_acc = ? $whereClause");
    $sql->execute([$level]);
    $names = $sql->fetchAll();

    if (count($names) > 0) {
        if($level == 1){
            echo "<ul class='firstLevel'>";
        } elseif($level == 2) {
            echo "<ul class='level_two'>";
        } elseif($level == 3) {
            echo "<ul class='level_three'>";
        } elseif($level == 4) {
            echo "<ul class='level_four'>";
        } else {
            echo "<ul class='level_fiv'>";
        }
        // echo "<ul class='level_$level'>";
        foreach ($names as $name) {
            echo "<li class='category'><a href='#'>{$name['name_account']} || كود ({$name['lv'.$level]})</a>";
            if ($level < 5) { // يمكنك تعديل هذا الرقم بناءً على العمق الأقصى للشجرة
                generateList($level + 1, $name['ID']);
            }
            echo "</li>";
        }
        echo "</ul>";
    }
}
function getAccountsByLevel($con, $acc_up) {
    // تأكد من أن $id_ledger آمن للاستخدام في الاستعلام لتجنب الحقن الـ SQL
    $stmt = $con->prepare("SELECT * FROM level_acc WHERE acc_up = ?");
    $stmt->execute([$acc_up]);
    $accounts = $stmt->fetchAll();
    return $accounts;
}
function getCurrency() {
    global $con;
    // تأكد من أن $id_ledger آمن للاستخدام في الاستعلام لتجنب الحقن الـ SQL
    // $stmt = $con->prepare("SELECT * FROM currency order by ID DESC");
    $stmt = $con->prepare("SELECT * FROM currency");
    $stmt->execute();
    $currency = $stmt->fetchAll();
    return $currency;
}
// دالة لجلب تفاصيل حسب معايير محددة
// دالة لجلب تفاصيل حسب معايير محددة
function getYomyaDetails($con, $startDate, $endDate, $name_lev_acc, $codeAccount, $from_or_to) {
    if (empty($endDate) && !empty($startDate)) {
        $stmt = $con->prepare("SELECT y.*, dy.* FROM yomya y INNER JOIN details_yomya dy ON y.id_yomya = dy.id_yomya WHERE y.dateinsert < ? AND $name_lev_acc = ? AND from_or_to = ?");
        $stmt->execute([$startDate, $codeAccount, $from_or_to]);
    } elseif (empty($startDate) && !empty($endDate)) {
        $stmt = $con->prepare("SELECT y.*, dy.* FROM yomya y INNER JOIN details_yomya dy ON y.id_yomya = dy.id_yomya WHERE y.dateinsert > ? AND $name_lev_acc = ? AND from_or_to = ?");
        $stmt->execute([$endDate, $codeAccount, $from_or_to]);
    } else {
        $stmt = $con->prepare("SELECT y.*, dy.* FROM yomya y INNER JOIN details_yomya dy ON y.id_yomya = dy.id_yomya WHERE y.dateinsert BETWEEN ? AND ? AND $name_lev_acc = ? AND from_or_to = ?");
        $stmt->execute([$startDate, $endDate, $codeAccount, $from_or_to]);
    }
    return $stmt->fetchAll();
}
function a($url, $name)
{
    $a_url = "<a href='" . $url . "'>" . $name . "</a>";
    echo $a_url;
}
function getCurrentLink() {
    $current_url = 'https://';
    $current_url .= $_SERVER['HTTP_HOST'];
    $current_url .= $_SERVER['REQUEST_URI'];
    return $current_url;
}
function curPageURL() {
    $current_url = 'http';
    if(isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on"){
        $current_url .= "s";
    }
    $current_url .= "://";
    if ($_SERVER["SERVER_PORT"] != "80" ) {
        $current_url .= $_SERVER['SERVER_NAME'].":".$_SERVER["SERVER_PORT"].$_SERVER['REQUEST_URI'];
    } else {
        $current_url .= $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
    }
    return $current_url;
}
function make_copy_and_save_database($dbname, $filename) {
    exec("mysqldump --user=USERNAME --password=PASSWORD --host=HOSTNAME $dbname > $filename");
}
function safe_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
function rundIdCode($length = 5){
    $rundid = substr(str_shuffle("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"), 0, $length);
    return $rundid;
}
/* 
num for number
dsm for decimals 
*/
function zerotoformat($num, $dsm = 2){
    if (!isset($num) || empty($num) || $num == 0 || $num == null) {
        $num = 0;
        // return number_format($num, 2);
        return $num;
    } else {
        return round(number_format($num, $dsm, ".", ""),5);
        // return $num;
    }
}
function strtoformat($str){
    if (!isset($str) || $str == null || $str == 'null') {
        return "";
    } else {
        return $str;
    }
}
/* 
how to use this func :
echo formatDateTimeZone('2022-12-30 11:00', 'UTC', 'egypt');
*/
function formatDateTimeZone($t, $tz_from, $tz_to){
    $date = new \DateTime($t, new \DateTimeZone($tz_from));
    $date->setTimezone(new \DateTimeZone($tz_to));
    return $date->format('Y-m-d\TH:i:s\Z');
}
/*
how to use this func :
echo formatDateTime('2022-12-30 11:00');
*/
function formatDateTime($t){
    $date = new \DateTime($t);
    return $date->format('Y-m-d\TH:i:s\Z');
}
/*
how to use this func :
echo formatDateTime('2022-12-30 11:00');
*/
function reformatDateTime($t){
    // $dateT = str_replace('T', ' ', $t);
    // $dateT = str_replace('Z', '', $dateT);
    $date = new \DateTime($t);
    return $date->format('d-m-Y H:i:s');
}
// يستخدم مع مصفوفة للتحقق من الطلب
function parseHeaders( $headers ){
    $head = array();
    foreach( $headers as $k=>$v )
    {
        $t = explode( ':', $v, 2 );
        if( isset( $t[1] ) )
            $head[ trim($t[0]) ] = trim( $t[1] );
        else
        {
            $head[] = $v;
            if( preg_match( "#HTTP/[0-9\.]+\s+([0-9]+)#",$v, $out ) )
                $head['reponse_code'] = intval($out[1]);
        }
    }
    return $head;
}
// كود يستخدم مع اى array
function display_array_recursive($json_rec){
    if($json_rec && is_array($json_rec)){
        foreach($json_rec as $key=> $value){
            if(is_array($value)){
                echo "<br>";
                echo "<br>";
                display_array_recursive($value);
            }else{
                if ($key == "error") {
                    echo $value.'<br>';
                } elseif ($key == "message") {
                    echo $value.'<br>';
                } else {
                    echo $key.' = '.$value.'<br>';
                }
            }	
        }	
    } else {
        print_r($json_rec);
    }
}

/*
    ** Check Items Function v1.0
    ** Function to Check Item In Database [ Function Accept Parameters ]
    ** $select = The Item To Select [ Example: user, item, category ]
    ** $from = The Table To Select From [ Example: users, items, categories ]
    ** $value = The Value Of Select [ Example: Osama, Box, Electronics ]
*/
function checkItem($select, $from, $value)
{
    global $con;

    $statement = $con->prepare("SELECT $select FROM $from WHERE $select = ?");

    $statement->execute(array($value));

    $count = $statement->rowCount();

    return $count;
}
/*
	** Check Items Function v1.0
	** Function to Check Item In Database [ Function Accept Parameters ]
	** $select = The Item To Select [ Example: user, item, category ]
	** $from = The Table To Select From [ Example: users, items, categories ]
	** $value = The Value Of Select [ Example: Osama, Box, Electronics ]
	*/
function sumTotal($select, $from, $where, $value, $where2 = false, $value2 = false)
{
    global $con;
    if (isset($where2) && !empty($where2)) {
        $sqlq = $con->prepare("SELECT sum($select) AS 'total' FROM $from 
                            where $where = $value AND $where2 = $value2");
    } elseif (!empty($where) || !empty($value)) {
        $sqlq = $con->prepare("SELECT sum($select) AS 'total' FROM $from 
                            where $where = '$value' ");
    } else {
        $sqlq = $con->prepare("SELECT sum($select) AS 'total' FROM $from ");
    }
    $sqlq->execute();
    $sumkqs = $sqlq->fetchAll();
    foreach ($sumkqs as $sumkq) {
        $total =  $sumkq['total']; // إجمالى التكلفة
    }
    return $total;
}

    /*
	** add in table yomya and details_yomya
	*/
    function addToYomya($mydate, $cash, $payanyomya, $lv1_f, $lv2_f, $lv3_f, $lv1_t, $lv2_t, $lv3_t, $lv4_t = false, $lv4_f = false){
        global $con;
        $sql = "INSERT INTO yomya (dateinsert, daen, madeen, payan, UserID_Insert)VALUES
                                    (:zdateinsert, :zdaen, :zmadeen, :zpayan, :zUserID_Insert)";
            $stmt = $con->prepare($sql);
            $stmt->execute(array(
                'zdateinsert' => $mydate,
                'zdaen' => $cash,
                'zmadeen' => $cash,
                'zpayan' => $payanyomya,
                'zUserID_Insert' => $_SESSION['admin']
            ));
            if ($stmt->rowCount() >= 1) {
                $id_yomya = $con->lastInsertId();
                // from = 1 = madeen
                // to   = 2 = daen
                $sql = "INSERT INTO details_yomya (id_yomya, from_or_to, lv1, lv2, lv3, lv4, cash, dateinsert)VALUES
                                            (:zid_yomya, :zfrom_or_to, :zlv1, :zlv2, :zlv3, :zlv4, :zcash, :zdateinsert)";
                $stmt = $con->prepare($sql);
                $stmt->execute(array(
                    'zid_yomya' => $id_yomya,
                    'zfrom_or_to' => 1,
                    'zlv1' => $lv1_f,
                    'zlv2' => $lv2_f,
                    'zlv3' => $lv3_f,
                    'zlv4' => $lv4_f,
                    'zcash' => $cash,
                    'zdateinsert' => $mydate
                ));
                $count = $stmt->rowCount();
                $sql = "INSERT INTO details_yomya (id_yomya, from_or_to, lv1, lv2, lv3, lv4, cash, dateinsert)VALUES
                                                (:zid_yomya, :zfrom_or_to, :zlv1, :zlv2, :zlv3, :zlv4, :zcash, :zdateinsert)";
                $stmt = $con->prepare($sql);
                $stmt->execute(array(
                    'zid_yomya' => $id_yomya,
                    'zfrom_or_to' => 2,
                    'zlv1' => $lv1_t,
                    'zlv2' => $lv2_t,
                    'zlv3' => $lv3_t,
                    'zlv4' => $lv4_t,
                    'zcash' => $cash,
                    'zdateinsert' => $mydate
                ));
                $count += $stmt->rowCount();
            }
        // $count = $stmt->rowCount();
        return intval($id_yomya);
    }
    /*
	** edit in table yomya and details_yomya
	*/
    function editToYomya($id_yomya, $mydate, $cash, $payanyomya, $lv1_f, $lv2_f, $lv3_f, $lv1_t, $lv2_t, $lv3_t, $lv4_t = false, $lv4_f = false){
        global $con;

        $stmt = $con->prepare("UPDATE yomya  SET 
											dateinsert = ?,
											daen = ?,
											madeen = ?,
											payan = ?,
											UserIDEdite = ?,
											DateEdite = now() WHERE id_yomya = ?");
            $stmt->execute(array(
                $mydate,
                $cash,
                $cash,
                $payanyomya,
                $_SESSION['admin'],
                $id_yomya
            ));

            if ($stmt->rowCount() >= 1) {
                // from = 1 = madeen
                // to   = 2 = daen
                // id_yomya, from_or_to, lv1, lv2, lv3, lv4, cash, dateinsert
                $stmt = $con->prepare("UPDATE details_yomya  SET 
											lv1 = ?,
											lv2 = ?,
											lv3 = ?,
											lv4 = ?,
											cash = ?,
											dateinsert = ?
                                            WHERE id_yomya = ? and from_or_to = ?");
                $stmt->execute(array(
                    $lv1_f,
                    $lv2_f,
                    $lv3_f,
                    $lv4_f,
                    $cash,
                    $mydate,
                    $id_yomya,
                    1
                ));
                $count = $stmt->rowCount();
                $stmt = $con->prepare("UPDATE details_yomya  SET 
											lv1 = ?,
											lv2 = ?,
											lv3 = ?,
											lv4 = ?,
											cash = ?,
											dateinsert = ?
                                            WHERE id_yomya = ? and from_or_to = ?");
                $stmt->execute(array(
                    $lv1_t,
                    $lv2_t,
                    $lv3_t,
                    $lv4_t,
                    $cash,
                    $mydate,
                    $id_yomya,
                    2
                ));
                $count += $stmt->rowCount();
            }
        // $count = $stmt->rowCount();
        return intval($count);
    }
    /*
	** DELETE in table yomya and details_yomya
	*/
    function deleteFromYomya($id_yomya) {
        global $con;
        $cash = 0;

        $stmt = $con->prepare("UPDATE yomya  SET 
											daen = ?,
											madeen = ?,
											payan = ?,
											UserIDEdite = ?,
											DateEdite = now() WHERE id_yomya = ?");
            $stmt->execute(array(
                $cash,
                $cash,
                "تم إلغاء هذه العملية",
                $_SESSION['admin'],
                $id_yomya
            ));

            if ($stmt->rowCount() >= 1) {
                // from = 1 = madeen
                // to   = 2 = daen
                // id_yomya, from_or_to, lv1, lv2, lv3, lv4, cash, dateinsert
                $stmt = $con->prepare("UPDATE details_yomya  SET 
											cash = ?
                                            WHERE id_yomya = ? and from_or_to = ?");
                $stmt->execute(array(
                    $cash,
                    $id_yomya,
                    1
                ));
                $count = $stmt->rowCount();
                $stmt = $con->prepare("UPDATE details_yomya  SET 
											cash = ?
                                            WHERE id_yomya = ? and from_or_to = ?");
                $stmt->execute(array( 
                    $cash,
                    $id_yomya,
                    2
                ));
                $count += $stmt->rowCount();
            }
        // $count = $stmt->rowCount();
        return intval($count);
    }
/*  */
function testzero($test){
    if (!isset($test) || empty($test) || !intval($test)) {
        return 0;
    } else {
        return $test;
    }
}
/*
	** Get Name v1.0
	*/

function getName($from, $select, $value, $name){
    global $con;

    $statement = $con->prepare("SELECT * FROM $from WHERE $select = ?");

    $statement->execute(array($value));

    $count = $statement->rowCount();

    if ($count > 0) {
        $rows = $statement->fetchAll();
        foreach ($rows as $row) {
            return $row[$name];
        }
    } else {
        return "لا يوجد إسم";
    }

    return $count;
}
function getId($from, $select, $value, $name){
    global $con;

    $statement = $con->prepare("SELECT * FROM $from WHERE $select = ?");

    $statement->execute(array($value));

    $count = $statement->rowCount();

    if ($count > 0) {
        $rows = $statement->fetchAll();
        foreach ($rows as $row) {
            return $row[$name];
        }
    } else {
        return NULL;
    }

    // return $count;
}
function getIdTowVal($from, $select, $value, $select2, $value2, $name){
    global $con;

    $statement = $con->prepare("SELECT * FROM $from WHERE $select = ? AND $select2 = ?");

    $statement->execute(array($value, $value2));

    $count = $statement->rowCount();

    if ($count > 0) {
        $rows = $statement->fetchAll();
        foreach ($rows as $row) {
            return $row[$name];
        }
    } else {
        return NULL;
    }

    // return $count;
}
///////////////////////
/*
 ** Start function check user id group
 */

function idGroup($id_group, $id_group_user, $id_group_on){
    if ($id_group_user <= $id_group or $id_group_user == $id_group_on) {
    } else {
    ?>
        <br>
        <div class="alert alert-danger">
            عفواُ: ليس لديك صلاحة الوصول
        </div>
    <?php
        include 'inc/temp/footer.php';

        exit("عفوا");
    }
}
/*
	** Home Redirect Function v2.0
	** This Function Accept Parameters
	** $theMsg = Echo The Message [ Error | Success | Warning ]
	** $url = The Link You Want To Redirect To
	** $seconds = Seconds Before Redirecting
	*/

function redirectHome($theMsg, $url = null, $seconds = 0){
    if ($url === null) {
        $url = 'index.php';
        $link = 'الصفحة الرئيسية';
    } else {
        if (isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER'] !== '') {
            $url = $_SERVER['HTTP_REFERER'];
            $link = 'الصفحة السابقة';
        } else {
            $url = 'index.php';
            $link = 'الصفحة الرئيسية';
        }
    }

    // echo $theMsg;
    $_SESSION['msg'] = $theMsg;
    echo "<div class='alert alert-info'> $theMsg جارى تحويلك إلى  $link بعد $seconds ثانية.</div>";
    echo "إذا لم يتم تححويل <a href='" . $url . "'>إضغط هنا</a>";
    header("refresh:$seconds;url=$url");
    exit();
}
/**
 * Undocumented function
 *
 * @param [type] $theMsg
 * @param [type] $url
 * @param [type] $name
 * @param integer $seconds
 * @return void
 */
function redirectlink($theMsg, $url = null, $name = null, $seconds = 2){
    if ($url === null) {
        $newurl = 'index.php';
        $link = 'الصفحة الرئيسية';
    } else {
        $newurl = $url;
        $link = $name;
    }

    echo $theMsg;
    $_SESSION['msg'] = $theMsg;
    echo "<div class='alert alert-info'>جارى تحويلك إلى  $link بعد $seconds ثانية.</div>";
    echo "إذا لم يتم تححويل <a href='" . $newurl . "'>إضغط هنا</a>";
    header("refresh:$seconds;url=$newurl");
    exit();
}

/* USER */
function addUser($con, $username, $password, $email) {
    try {
        $sql = "INSERT INTO users (username, password, email) VALUES ('$username', '$password', '$email')";
        $con->exec($sql);
        echo "تمت عملية إضافة المستخدم بنجاح!";
    } catch (PDOException $e) {
        echo "فشل في الإضافة: " . $e->getMessage();
    }
}

function updateUser($con, $userId, $username, $password, $email) {
    try {
        $sql = "UPDATE users SET username = '$username', password = '$password', email = '$email' WHERE user_id = $userId";
        $con->exec($sql);
        echo "تمت عملية تحديث بيانات المستخدم بنجاح!";
    } catch (PDOException $e) {
        echo "فشل في التحديث: " . $e->getMessage();
    }
}

function deleteUser($con, $userId) {
    try {
        $sql = "DELETE FROM users WHERE user_id = $userId";
        $con->exec($sql);
        echo "تمت عملية حذف المستخدم بنجاح!";
    } catch (PDOException $e) {
        echo "فشل في الحذف: " . $e->getMessage();
    }
}

function add_login_records($user_id, $lastdate_login, $ip_address, $userBrowser, $userAgent) {
    global $con;
    try {
        $sql = "INSERT INTO login_records (user_id, lastdate_login, ip_address, userBrowser, HTTP_USER_AGENT) VALUES ('$user_id', '$lastdate_login', '$ip_address', '$userBrowser', '$userAgent')";
        $con->exec($sql);
        return 1;
    } catch (PDOException $e) {
        // echo "فشل في الإضافة: " . $e->getMessage();
        return 0;
    }
}
function updatepayment_status($reservation_id)
    {
        global $con;
        // Add your validation and sanitization here before executing the SQL query

        $sql = "UPDATE reservations
                SET payment_status = 1
                WHERE id = :reservation_id";
        $stmt = $con->prepare($sql);
        $stmt->bindParam(':reservation_id', $reservation_id);
        $stmtret = $stmt->execute();
        return $stmtret;
    }
function addnotifications( $name, $disc_notifications, $date_notifications)
{
    global $con;
    // $newClientName = $_POST['new_client_name'];
    $HotelBooking = "INSERT INTO notifications (name, disc_notifications ,date_notifications ) 
                                        VALUES (:name, :disc_notifications, :date_notifications)";
    $HotelBookingStmt = $con->prepare($HotelBooking);
    $HotelBookingStmt->bindParam(':name', $name);
    $HotelBookingStmt->bindParam(':disc_notifications', $disc_notifications);
    $HotelBookingStmt->bindParam(':date_notifications', $date_notifications);
    $HotelBookingStmt->execute();
    $hotel_bookings_id = $con->lastInsertId();

    return $hotel_bookings_id;
    // استخراج معرف العميل الجديد الذي تم إضافته
    // return $HotelBooking_id = $this->conn->lastInsertId();
}
// الحصول على عنوان IP الفعلي للمستخدم
function getRealIP() {
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

// الحصول على معلومات المتصفح
function getBrowser() {
    $userAgent = $_SERVER['HTTP_USER_AGENT'];

    $browser = "غير معروف";

    if (strpos($userAgent, 'Edg') !== FALSE) {
        $browser = 'Microsoft Edge';
    }elseif (strpos($userAgent, 'MSIE') !== FALSE) {
        $browser = 'Internet Explorer';
    } elseif (strpos($userAgent, 'Firefox') !== FALSE) {
        $browser = 'Firefox';
    } elseif (strpos($userAgent, 'Chrome') !== FALSE) {
        $browser = 'Google Chrome';
    } elseif (strpos($userAgent, 'Safari') !== FALSE) {
        $browser = 'Safari';
    } elseif (strpos($userAgent, 'Opera') !== FALSE) {
        $browser = 'Opera';
    }
    return $browser;
}

function getusers($from, $select, $value, $name){
    global $con;

    $statement = $con->prepare("SELECT * FROM users");

    $statement->execute(array($value));

    $count = $statement->rowCount();

    if ($count > 0) {
        $rows = $statement->fetchAll();
        // return $rows;
        foreach ($rows as $row) {
            // return $row[$name];
            return $rows;
        }
    } else {
        return "لا يوجد مستخدمين";
    }

    return $count;
}

function checkadmin($user_id, $department_id = 1, $permission_id = 0, $or = "no") {
    global $con;

    $id_permission = 0;

    // التحقق من وجود الصلاحية المحددة
    $statement = $con->prepare("SELECT * FROM user_department_permissions WHERE user_id = ? AND department_id = ? AND permission_id = ?");
    $statement->execute(array($user_id, $department_id, $permission_id));
    $count = $statement->rowCount();

    if ($count > 0) {
        $id_permission = 1;
    } else {
        // إذا لم يكن هناك نتيجة، قم بالتحقق من الصلاحيتين الإضافيتين
        $statement = $con->prepare("SELECT * FROM user_department_permissions WHERE user_id = ? AND department_id = ? AND permission_id = ?");
        $statement->execute(array($user_id, $department_id, 1));
        $count = $statement->rowCount();

        if ($count <= 0) {
            $statement = $con->prepare("SELECT * FROM user_department_permissions WHERE user_id = ? AND department_id = ? AND permission_id = ?");
            $statement->execute(array($user_id, 1, 0));
            $count = $statement->rowCount();

            if ($count > 0) {
                $id_permission = 1;
            }
        } else {
            $id_permission = 1;
        }
    }

    return $id_permission;
}

    // دالة تسجيل التاريخ والوقت
    function getCurrentDateTime() {
        return date("Y-m-d H:i:s");
    }
/*
CREATE TABLE `history_table` (
`ID` INT NOT NULL AUTO_INCREMENT,
`table_id` INT NOT NULL,
`table_name` VARCHAR(255) NOT NULL,
`action` VARCHAR(255) NOT NULL,
`data_old` JSON DEFAULT NULL,
`data_new` JSON DEFAULT NULL,
`user_id` INT NOT NULL,
`timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`ID`)
);
 */
    // دالة تسجيل العملية في جدول التقرير
    function logToHistory($action, $tableName, $tableId, $dataOld, $dataNew, $nameID ) {
        global $con;
        $conn = $con;
        /* if (is_integer($table_id)) { */
            // if ($nameID != NULL) {
                if ($action == "insert") {
                    $stmtSelectIns = $conn->prepare("SELECT * FROM $tableName WHERE $nameID = $tableId");
                    $stmtSelectIns->execute();
                    $dataNew = $stmtSelectIns->fetch(PDO::FETCH_ASSOC);
                }
                
                $dataNew = json_encode($dataNew);
                $dataOld = json_encode($dataOld);
                
            // }
            // $tableId = $table_id;
        /* } else {
            // جلب الـ ID الخاص بالجدول
            $stmt = $conn->prepare("SELECT $table_id FROM $tableName ORDER BY table_id DESC LIMIT 1");
            $stmt->execute();
            $tableId = $stmt->fetchColumn();
        } */

        // تسجيل العملية في جدول التاريخ
        $sql = "INSERT INTO history_table (table_id, name_table_id, table_name, action, data_old, data_new, user_id, timestamp) VALUES (:tableId, :nameTableId, :tableName, :action, :dataOld, :dataNew, :userId, :timestamp)";
        $stmt = $conn->prepare($sql);
        $getCurrentDate = getCurrentDateTime();
        // تعيين القيم للمتغيرات المستعارة
        $stmt->bindParam(':tableId', $tableId, PDO::PARAM_INT);
        $stmt->bindParam(':nameTableId', $nameID, PDO::PARAM_STR);
        $stmt->bindParam(':tableName', $tableName, PDO::PARAM_STR);
        $stmt->bindParam(':action', $action, PDO::PARAM_STR);
        $stmt->bindParam(':dataOld', $dataOld, PDO::PARAM_STR);
        $stmt->bindParam(':dataNew', $dataNew, PDO::PARAM_STR);
        $stmt->bindParam(':userId', $_SESSION['admin'], PDO::PARAM_INT); // يجب تعديله بناءً على كيفية تسجيل الجلسة في تطبيقك
        $stmt->bindParam(':timestamp', $getCurrentDate, PDO::PARAM_STR);

        $stmt->execute();
    }
function insertUserPermissions($username, $department, $permissions) {
    global $con;

    // التحقق من أن المستخدم موجود في قاعدة البيانات
    $checkUserQuery = "SELECT COUNT(*) FROM users WHERE ID = :username";
    $checkUserStmt = $con->prepare($checkUserQuery);
    $checkUserStmt->bindParam(':username', $username);
    $checkUserStmt->execute();

    if ($checkUserStmt->fetchColumn() == 0) {
        // المستخدم غير موجود
        return "خطأ: المستخدم غير موجود في قاعدة البيانات";
    }

    // التحقق من أن هناك صلاحيات محددة
    /* if (empty($permissions)) {
        return "خطأ: يجب تحديد صلاحيات للمستخدم";
    } */

    // إدخال الصلاحيات في قاعدة البيانات
    try {
        $con->beginTransaction();

        // حذف الصلاحيات السابقة
        $deletePreviousQuery = "DELETE FROM user_department_permissions WHERE user_id = :user_id and department_id = :department_id and permission_id != 0";
        $deletePreviousStmt = $con->prepare($deletePreviousQuery);
        $deletePreviousStmt->bindParam(':user_id', $username);
        $deletePreviousStmt->bindParam(':department_id', $department);
        $deletePreviousStmt->execute();

        // إدراج الصلاحيات الجديدة
        $insertPermissionsQuery = "INSERT INTO user_department_permissions (user_id, department_id, permission_id) VALUES (:user_id, :department_id, :permission_id)";
        $insertPermissionsStmt = $con->prepare($insertPermissionsQuery);
        $insertPermissionsStmt->bindParam(':user_id', $username);
        $insertPermissionsStmt->bindParam(':department_id', $department);

        foreach ($permissions as $permission) {
            $insertPermissionsStmt->bindParam(':permission_id', $permission);
            $insertPermissionsStmt->execute();
        }

        $con->commit();
        return "تم إدخال الصلاحيات بنجاح!";
    } catch (PDOException $e) {
        $con->rollBack();
        return "حدث خطأ: " . $e->getMessage();
    }
}

function getUserPermissions($username, $department_id = null)
    {
        global $con;

        if ($department_id !== null) {
            $query = "SELECT permission_id FROM user_department_permissions WHERE user_id = :username AND department_id = :zdepartment_id";
            $stmt = $con->prepare($query);
            $stmt->bindParam(':zdepartment_id', $department_id);
        } else {
            $query = "SELECT permission_id FROM user_department_permissions WHERE user_id = :username";
            $stmt = $con->prepare($query);
        }
        $stmt->bindParam(':username', $username);
        
        $stmt->execute();

        return $stmt->fetchAll(PDO::FETCH_COLUMN);
    }
/* END USER */

/**
 * Undocumented function
 *
 * @param [type] $con
 * @param [string/int] $lv1
 * @param [int] $cost_centers_id
 * @param [type] $cost_center_name
 * @return int
 */
function getNextCostCenterCode($con, $lv1, $cost_centers_id, $cost_center_name) {
    $account = $con->prepare("SELECT MAX(CAST(SUBSTRING_INDEX(cost_center_code, '.', -1) AS UNSIGNED)) AS last_code_account FROM cost_centers where cc_lv = 2 AND cost_center_up = $cost_centers_id");
    $account->execute();
    $result = $account->fetch(PDO::FETCH_ASSOC);
    $last_code_account = $result['last_code_account'];

    if (!empty($last_code_account)) {
        $lv2 = $last_code_account + 1;
        $lv2 = $lv1 . "." . $lv2;
    } else {
        $lv2 = $lv1 . ".1";
    }

    $stmt = $con->prepare("INSERT INTO cost_centers(cost_center_name, cc_lv, cost_center_code, cost_center_up, description) VALUES(:cost_center_name, :cc_lv, :cost_center_code, :cost_center_up, :zdescription)");
    $stmt->execute(
        array(
            'cost_center_name' => $cost_center_name,
            'cc_lv' => 2,
            'cost_center_code' => $lv2,
            'cost_center_up' => $cost_centers_id,
            'zdescription' => ''
        )
    );

    return $con->lastInsertId();
}
/* function calculatePayment($totalPeople, $num_dis) {

    $fullGroups = floor($totalPeople / $num_dis); // عدد الدورات الكاملة
    $extraPeople = $totalPeople % $num_dis; // الأشخاص الإضافيين بعد الدورات الكاملة

    // إذا كان هناك دورات كاملة
    if ($fullGroups > 0) {
        $free = $fullGroups; // عدد الأشخاص الذين يحصلون على دخول مجاني
    } else {
        $free = 0; // لا يوجد دورات كاملة
    }

    // إضافة الأشخاص الإضافيين إذا كان هناك
    if ($extraPeople > 0) {
        // إذا كان العدد الإضافي أكبر من 5
        if ($extraPeople >= 6) {
            $free++; // يحصل الشخص الإضافي على دخول مجاني
        }
    }

    return $free;
} */

function calculatePayment($totalPeople, $num_dis) {
    // العدد الإجمالي من الأشخاص بعد احتساب الدورات الكاملة
    $totalPeopleAfterDiscount = $totalPeople - $num_dis;

    // حساب عدد الدورات الكاملة
    
    $fullGroups = floor($totalPeopleAfterDiscount / $num_dis);

    // حساب الأشخاص الإضافيين بعد الدورات الكاملة
    $extraPeople = $totalPeopleAfterDiscount % $num_dis;

    // إذا كان هناك شخص إضافي بعد الدورات الكاملة، يحصل على دخول مجاني
    if ($extraPeople > 0) {
        $fullGroups++; // نحسب الشخص الإضافي ضمن الدورة الكاملة
    }

    // إذا كانت الدورات الكاملة أكثر من صفر، نضيف شخص مجاني لكل دورة كاملة
    if ($fullGroups > 0) {
        $free = $fullGroups;
    } else {
        $free = 0; // لا يوجد دورات كاملة
    }

    return $free;
}

// استخدام الدالة
// echo calculatePayment(75, 15); // يجب أن يعود بالقيمة 3





function printAccountOptions($accounts, $level, $displayedAccounts = [])
{
    foreach ($accounts as $account) {
        $name = $account['name_account'];
        $lv = $account['lv'];
        $ID = $account['ID'];

        $indentation = str_repeat("&nbsp;&nbsp;&nbsp;&nbsp;", $level - 1);

        $subAccounts = getSubAccounts($ID, $level + 1);

        // فحص وجود حسابات فرعية
        $hasSubAccounts = !empty($subAccounts);

        // لا تطبع <option> إذا كان لديها حسابات فرعية
        if (!in_array($ID, $displayedAccounts) && !$hasSubAccounts) {
            echo "<option value='{$ID}'>{$indentation}{$name}{$lv}</option>";
            $displayedAccounts[] = $ID; // إضافة الحساب الحالي للمصفوفة
        }

        if ($hasSubAccounts) {
            echo "<optgroup label='{$name}'>";
            printAccountOptions($subAccounts, $level + 1, $displayedAccounts);
            echo "</optgroup>";
        }
    }
}

function getSubAccounts($parentId, $level)
{
    global $con;
    $stmt = $con->prepare("SELECT * FROM level_acc WHERE lev_acc = ? AND acc_up = ?");
    $stmt->execute([$level, $parentId]);
    return $stmt->fetchAll();
}

function printAccountOptionsCost($accounts, $level, $displayedAccounts = [])
{
    foreach ($accounts as $account) {
        $name = $account['cost_center_name'];
        $ID = $account['ID'];

        $indentation = str_repeat("&nbsp;&nbsp;&nbsp;&nbsp;", $level - 1);

        $subAccounts = getSubAccountsCost($ID, $level + 1);

        // فحص وجود حسابات فرعية
        $hasSubAccounts = !empty($subAccounts);

        // لا تطبع <option> إذا كان لديها حسابات فرعية
        if (!in_array($ID, $displayedAccounts) && !$hasSubAccounts) {
            echo "<option value='{$ID}'>{$indentation}{$name}</option>";
            $displayedAccounts[] = $ID; // إضافة الحساب الحالي للمصفوفة
        }

        if ($hasSubAccounts) {
            echo "<optgroup label='{$name}'>";
            printAccountOptionsCost($subAccounts, $level + 1, $displayedAccounts);
            echo "</optgroup>";
        }
    }
}

function getSubAccountsCost($parentId, $level)
{
    global $con;
    $stmt = $con->prepare("SELECT * FROM cost_centers WHERE cc_lv = ? AND cost_center_up = ?");
    $stmt->execute([$level, $parentId]);
    return $stmt->fetchAll();
}
function getTotalCash($con, $ID, $start_date_sql, $end_date_sql, $code_account, $from_or_to)
{
    $allcash = 0;

    $sqlaccounts = $con->prepare("SELECT * FROM cost_centers WHERE cost_center_up = $ID");
    $sqlaccounts->execute();
    $accounts = $sqlaccounts->fetchAll();

    foreach ($accounts as $account) {
        $cost_center_code = $account['cost_center_code'];

        $sqldetails_yomya = $con->prepare("SELECT SUM(cash) AS 'total_cash' FROM details_yomya WHERE dateinsert BETWEEN '$start_date_sql' AND '$end_date_sql' AND cost_center_code = '$cost_center_code' AND from_or_to = $from_or_to");
        $sqldetails_yomya->execute();
        $details_yomyas = $sqldetails_yomya->fetchAll();

        foreach ($details_yomyas as $details_yomya) {
            $allcash += $details_yomya['total_cash'];
        }
    }

    return $allcash;
}
function getTotalCashAllCostYear($con, $ID, $start_date_sql, $end_date_sql, $from_or_to)
{
    $allcash = 0;

    $sqlaccounts = $con->prepare("SELECT * FROM cost_centers WHERE cost_center_up = $ID");
    $sqlaccounts->execute();
    $accounts = $sqlaccounts->fetchAll();

    foreach ($accounts as $account) {
        $cost_center_code = $account['cost_center_code'];

        $sqldetails_yomya = $con->prepare("SELECT * from details_yomya WHERE dateinsert BETWEEN '$start_date_sql' AND '$end_date_sql' AND cost_center_code = '$cost_center_code' AND from_or_to = $from_or_to");
        $sqldetails_yomya->execute();
        $details_yomyas = $sqldetails_yomya->fetchAll();
        $countfrom = $sqldetails_yomya->rowCount();
        $cashfrom = 0;
        $cashto = 0;
        foreach ($details_yomyas as $details_yomya) {
            $from_or_to = $details_yomya['from_or_to'];
            $cash = $details_yomya['cash'];
            $id_currency_codes = $details_yomya['id_currency_codes'];
            $amountSold = $details_yomya['amountSold'];
            $currencyExchangeRate = $details_yomya['currencyExchangeRate'];

                if($id_currency_codes != 1){
                    $cash = $amountSold;
                } else {
                    $cash = $currencyExchangeRate * $cash;
                }
                $allcash += $cash;
        }

        /* $sqldetails_yomya = $con->prepare("SELECT SUM(cash) AS 'total_cash' FROM details_yomya WHERE dateinsert BETWEEN '$start_date_sql' AND '$end_date_sql' AND cost_center_code = '$cost_center_code' AND from_or_to = $from_or_to");
        $sqldetails_yomya->execute();
        $details_yomyas = $sqldetails_yomya->fetchAll();

        foreach ($details_yomyas as $details_yomya) {
            $allcash += $details_yomya['total_cash'];
        } */
    }

    return $allcash;
}
function calculateCashFlow($con, $lv, $code, $fromOrTo, $firstDayOfMonth, $lastDayOfMonth) {
    $amasaref = 0;
    $query = "SELECT * FROM details_yomya WHERE $lv = ? AND from_or_to = ? AND dateinsert BETWEEN ? AND ?";
    $stmt = $con->prepare($query);
    $stmt->execute([$code, $fromOrTo, $firstDayOfMonth, $lastDayOfMonth]);
    $results = $stmt->fetchAll();

    foreach ($results as $row) {
        $cash = $row['id_currency_codes'] != 1 ? $row['amountSold'] : $row['currencyExchangeRate'] * $row['cash'];
        $amasaref += $cash;
    }

    return $amasaref;
}
function convertNumberToWords($number, $currency = 'Dollars', $centsCurrency = 'Cents') {
    $words = array(
        'Zero',
        'One',
        'Two',
        'Three',
        'Four',
        'Five',
        'Six',
        'Seven',
        'Eight',
        'Nine',
        'Ten',
        'Eleven',
        'Twelve',
        'Thirteen',
        'Fourteen',
        'Fifteen',
        'Sixteen',
        'Seventeen',
        'Eighteen',
        'Nineteen'
    );

    $tens = array(
        '',
        '',
        'Twenty',
        'Thirty',
        'Forty',
        'Fifty',
        'Sixty',
        'Seventy',
        'Eighty',
        'Ninety'
    );

    $units = array(
        '',
        'Thousand',
        'Million',
        'Billion',
        'Trillion',
        'Quadrillion',
        'Quintillion',
        'Sextillion',
        'Septillion',
        'Octillion',
        'Nonillion'
    );

    $number = number_format($number, 2, '.', '');
    list($integer_part, $decimal_part) = array_map('intval', explode('.', $number));

    $integer_words = array();
    if ($integer_part == 0) {
        $integer_words[] = $words[0];
    } else {
        // تحويل الجزء الصحيح إلى أجزاء
        $chunks = array_chunk(array_reverse(str_split($integer_part)), 3, true);
        foreach ($chunks as $i => $chunk) {
            $intValue = (int)implode('', $chunk);
            if ($intValue != 0) {
                $isPlural = ($intValue != 1);
                $chunkWords = array();

                if ($intValue >= 100) {
                    $chunkWords[] = $words[floor($intValue / 100)] . ' Hundred';
                    $intValue %= 100;
                }

                if ($intValue >= 10 && $intValue <= 19) {
                    $chunkWords[] = $words[$intValue];
                } else {
                    if ($intValue >= 20) {
                        $chunkWords[] = $tens[floor($intValue / 10)];
                        $intValue %= 10;
                    }

                    if ($intValue > 0) {
                        $chunkWords[] = $words[$intValue];
                    }
                }

                $chunkWords[] = $isPlural ? $units[$i] . 's' : $units[$i];
                $integer_words[] = implode(' ', $chunkWords);
            }
        }
    }

    // تحويل الجزء العشري إلى كلمات
    $decimal_words = array();
    if ($decimal_part > 0) {
        $decimal_words[] = 'and';
        $decimal_chunks = array_chunk(str_split($decimal_part), 3, true);
        foreach ($decimal_chunks as $i => $chunk) {
            $intValue = (int)implode('', $chunk);
            if ($intValue != 0) {
                $isPlural = ($intValue != 1);
                $chunkWords = array();

                if ($intValue >= 100) {
                    $chunkWords[] = $words[floor($intValue / 100)] . ' Hundred';
                    $intValue %= 100;
                }

                if ($intValue >= 10 && $intValue <= 19) {
                    $chunkWords[] = $words[$intValue];
                } else {
                    if ($intValue >= 20) {
                        $chunkWords[] = $tens[floor($intValue / 10)];
                        $intValue %= 10;
                    }

                    if ($intValue > 0) {
                        $chunkWords[] = $words[$intValue];
                    }
                }

                $decimal_words[] = implode(' ', $chunkWords);
            }
        }
    }

    // تجميع النتيجة
    $result = implode(' ', $integer_words) . ' ' . $currency;
    if (!empty($decimal_words)) {
        $result .= ' ' . implode(' ', $decimal_words) . ' ' . $centsCurrency;
    }

    return $result;
}



function numtoarb($total){
    $total = explode(".", $total);
    $j = strlen($total[0]);
    $je = $j;
    $je--;
    $de = 1;
    for ($i = 1; $i < $j; $i++)
        $de = $de * 10;
    $t = $total[0];

    for ($i = 0; $i < $j; $i++) {
        $te[$je] = $t / $de;
        $t = $t % $de;
        $de = $de / 10;
        $temp = explode(".", $te[$je]);
        $te[$je] = $temp[0];
        $je--;
    }
    for ($i = 0; $i < $j; $i++) {
        if ($i == 0) {
            if ($j < 3)
                switch ($te[$i]) {
                    case "0":
                        $arb[0] = " ";
                        break;
                    case "1":
                        $arb[0] = " واحد";
                        break;
                    case "2":
                        if ($te[1] == "1") $arb[0] = " اثنا ";
                        else $arb[0] = " اثنان";
                        break;
                    case "3":
                        $arb[0] = " ثلاثة";
                        break;
                    case "4":
                        $arb[0] = " اربعة";
                        break;
                    case "5":
                        $arb[0] = " خمسة";
                        break;
                    case "6":
                        $arb[0] = " ستة";
                        break;
                    case "7":
                        $arb[0] = " سبعة";
                        break;
                    case "8":
                        $arb[0] = " ثمانية";
                        break;
                    case "9":
                        $arb[0] = " تسعة";
                        break;
                }
            else
                switch ($te[$i]) {
                    case "0":
                        $arb[0] = " ";
                        break;
                    case "1":
                        $arb[0] = " وواحد";
                        break;
                    case "2":
                        if ($te[1] == "1") $arb[0] = " واثنا ";
                        else $arb[0] = " واثنان";
                        break;
                    case "3":
                        $arb[0] = " وثلاثة";
                        break;
                    case "4":
                        $arb[0] = " واربعة";
                        break;
                    case "5":
                        $arb[0] = " وخمسة";
                        break;
                    case "6":
                        $arb[0] = " وستة";
                        break;
                    case "7":
                        $arb[0] = " وسبعة";
                        break;
                    case "8":
                        $arb[0] = " وثمانية";
                        break;
                    case "9":
                        $arb[0] = " وتسعة";
                        break;
                }
        }
        if ($i == 1) {
            if ($j <= 2) {
                if ($te[$i] == 1) {
                    if ($te[0] == "1") {
                        $arb[0] = " ";
                        $arb[1] = " أحد عشر";
                    } elseif ($te[0] == "0") $arb[1] = " عشرة";
                    else $arb[1] = " عشر";
                }
                if ($te[0] == "0")
                    switch ($te[$i]) {
                        case "0":
                            $arb[1] = " ";
                            break;
                        case "1":
                            if ($te[0] == "1") {
                                $arb[0] = " ";
                                $arb[1] = " أحد عشر";
                            } elseif ($te[0] == "0") $arb[1] = " عشرة";
                            else $arb[1] = "عشر";
                            break;
                        case "2":
                            $arb[1] = " عشرون";
                            break;
                        case "3":
                            $arb[1] = " ثلاثون";
                            break;
                        case "4":
                            $arb[1] = " اربعون";
                            break;
                        case "5":
                            $arb[1] = " خمسون";
                            break;
                        case "6":
                            $arb[1] = " ستون";
                            break;
                        case "7":
                            $arb[1] = " سبعون";
                            break;
                        case "8":
                            $arb[1] = " ثمانون";
                            break;
                        case "9":
                            $arb[1] = " تسعون";
                            break;
                    }
            } else
                switch ($te[$i]) {
                    case "0":
                        $arb[1] = " ";
                        break;
                    case "1":
                        if ($te[0] == "1") {
                            $arb[0] = " ";
                            $arb[1] = " وأحد عشر";
                        } elseif ($te[0] == "0") $arb[1] = " وعشرة";
                        else $arb[1] = " عشر";
                        break;
                    case "2":
                        $arb[1] = " وعشرون";
                        break;
                    case "3":
                        $arb[1] = " وثلاثون";
                        break;
                    case "4":
                        $arb[1] = " واربعون";
                        break;
                    case "5":
                        $arb[1] = " وخمسون";
                        break;
                    case "6":
                        $arb[1] = " وستون";
                        break;
                    case "7":
                        $arb[1] = " وسبعون";
                        break;
                    case "8":
                        $arb[1] = " وثمانون";
                        break;
                    case "9":
                        $arb[1] = " وتسعون";
                        break;
                }
        }


        if ($i == 2) {
            if ($j == 3)
                switch ($te[$i]) {
                    case "0":
                        $arb[2] = " ";
                        break;
                    case "1":
                        $arb[2] = " مائة";
                        break;
                    case "2":
                        $arb[2] = " مائتان";
                        break;
                    case "3":
                        $arb[2] = " ثلاثمائة";
                        break;
                    case "4":
                        $arb[2] = " اربعمائة";
                        break;
                    case "5":
                        $arb[2] = " خمسمائة";
                        break;
                    case "6":
                        $arb[2] = " ستمائة";
                        break;
                    case "7":
                        $arb[2] = " سبعمائة";
                        break;
                    case "8":
                        $arb[2] = " ثمانمائة";
                        break;
                    case "9":
                        $arb[2] = " تسعمائة";
                        break;
                }
            else
                switch ($te[$i]) {
                    case "0":
                        $arb[2] = " ";
                        break;
                    case "1":
                        $arb[2] = " ومائة";
                        break;
                    case "2":
                        $arb[2] = " ومائتان";
                        break;
                    case "3":
                        $arb[2] = " وثلاثمائة";
                        break;
                    case "4":
                        $arb[2] = " واربعمائة";
                        break;
                    case "5":
                        $arb[2] = " وخمسمائة";
                        break;
                    case "6":
                        $arb[2] = " وستمائة";
                        break;
                    case "7":
                        $arb[2] = " وسبعمائة";
                        break;
                    case "8":
                        $arb[2] = " وثمانمائة";
                        break;
                    case "9":
                        $arb[2] = " وتسعمائة";
                        break;
                }
        }

        if ($i == 3) {
            if ($j == 4)
                switch ($te[$i]) {
                    case "0":
                        $arb[$i] = " ";
                        break;
                    case "1":
                        $arb[$i] = " ألف";
                        break;
                    case "2":
                        $arb[$i] = " ألفان";
                        break;
                    case "3":
                        $arb[$i] = " ثلاثة آلاف";
                        break;
                    case "4":
                        $arb[$i] = " اربعة آلاف";
                        break;
                    case "5":
                        $arb[$i] = " خمسة آلاف";
                        break;
                    case "6":
                        $arb[$i] = " ستة آلاف";
                        break;
                    case "7":
                        $arb[$i] = " سبعة آلاف";
                        break;
                    case "8":
                        $arb[$i] = " ثمانية آلاف ";
                        break;
                    case "9":
                        $arb[$i] = " تسعة آلاف ";
                        break;
                }
            elseif ($j == 5)

                switch ($te[$i]) {
                    case "0":
                        $arb[$i] = " ";
                        break;
                    case "1":
                        $arb[$i] = " واحد ";
                        break;
                    case "2":
                        if ($te[6] == "1") $arb[$i] = " اثنا ";
                        else $arb[$i] = " اثنان";
                        break;
                    case "3":
                        $arb[$i] = " ثلاثة ";
                        break;
                    case "4":
                        $arb[$i] = " اربعة ";
                        break;
                    case "5":
                        $arb[$i] = " خمسة ";
                        break;
                    case "6":
                        $arb[$i] = " ستة ";
                        break;
                    case "7":
                        $arb[$i] = " سبعة ";
                        break;
                    case "8":
                        $arb[$i] = " ثمانية ";
                        break;
                    case "9":
                        $arb[$i] = " تسعة ";
                }

            else
                switch ($te[$i]) {
                    case "0":
                        $arb[$i] = " ";
                        break;
                    case "1":
                        $arb[$i] = " وواحد ";
                        break;
                    case "2":
                        if ($te[4] == "1") $arb[$i] = " واثنا ";
                        else $arb[$i] = " واثنان";
                        break;
                    case "3":
                        $arb[$i] = " وثلاثة ";
                        break;
                    case "4":
                        $arb[$i] = " واربعة ";
                        break;
                    case "5":
                        $arb[$i] = " وخمسة ";
                        break;
                    case "6":
                        $arb[$i] = " وستة ";
                        break;
                    case "7":
                        $arb[$i] = " وسبعة ";
                        break;
                    case "8":
                        $arb[$i] = " وثمانية ";
                        break;
                    case "9":
                        $arb[$i] = " وتسعة ";
                }
        }
        if ($i == 4) {
            if ($j == 5)
                switch ($te[$i]) {
                    case "0":
                        $arb[$i] = " ";
                        break;
                    case "1":
                        if ($te[3] == "1") {
                            $arb[3] = " ";
                            $arb[4] = " أحد عشر الفا";
                        } elseif ($te[3] == "0") $arb[4] = " عشرة آلاف";
                        else $arb[$i] = " عشر الفا";
                        break;
                    case "2":
                        $arb[$i] = " عشرون ";
                        break;
                    case "3":
                        $arb[$i] = " ثلاثون ";
                        break;
                    case "4":
                        $arb[$i] = " اربعون ";
                        break;
                    case "5":
                        $arb[$i] = " خمسون ";
                        break;
                    case "6":
                        $arb[$i] = " ستون ";
                        break;
                    case "7":
                        $arb[$i] = " سبعون ";
                        break;
                    case "8":
                        $arb[$i] = " ثمانون ";
                        break;
                    case "9":
                        $arb[$i] = " تسعون ";
                        break;
                }
            else
                switch ($te[$i]) {
                    case "0":
                        $arb[$i] = " ";
                        break;
                    case "1":
                        if ($te[3] == "1") {
                            $arb[3] = " ";
                            $arb[4] = " وأحد عشر الفا";
                        } elseif ($te[3] == "0") $arb[4] = " وعشرة آلاف";
                        else $arb[$i] = " عشر الفا";
                        break;
                    case "2":
                        $arb[$i] = " وعشرون ";
                        break;
                    case "3":
                        $arb[$i] = " وثلاثون ";
                        break;
                    case "4":
                        $arb[$i] = " واربعون ";
                        break;
                    case "5":
                        $arb[$i] = " وخمسون ";
                        break;
                    case "6":
                        $arb[$i] = " وستون ";
                        break;
                    case "7":
                        $arb[$i] = " وسبعون ";
                        break;
                    case "8":
                        $arb[$i] = " وثمانون ";
                        break;
                    case "9":
                        $arb[$i] = " وتسعون ";
                        break;
                }
        }
        if ($i == 5) {
            if ($j == 6)
                switch ($te[$i]) {
                    case "0":
                        $arb[$i] = " ";
                        break;
                    case "1":
                        $arb[$i] = " مائة ";
                        break;
                    case "2":
                        $arb[$i] = " مائتان ";
                        break;
                    case "3":
                        $arb[$i] = " ثلاثمائة ";
                        break;
                    case "4":
                        $arb[$i] = " اربعمائة ";
                        break;
                    case "5":
                        $arb[$i] = " خمسمائة ";
                        break;
                    case "6":
                        $arb[$i] = " ستمائة ";
                        break;
                    case "7":
                        $arb[$i] = " سبعمائة ";
                        break;
                    case "8":
                        $arb[$i] = " ثمانمائة ";
                        break;
                    case "9":
                        $arb[$i] = " تسعمائة ";
                        break;
                }
            else
                switch ($te[$i]) {
                    case "0":
                        $arb[$i] = " ";
                        break;
                    case "1":
                        $arb[$i] = " ومائة ";
                        break;
                    case "2":
                        $arb[$i] = " ومائتان ";
                        break;
                    case "3":
                        $arb[$i] = " وثلاثمائة ";
                        break;
                    case "4":
                        $arb[$i] = " واربعمائة ";
                        break;
                    case "5":
                        $arb[$i] = " وخمسمائة ";
                        break;
                    case "6":
                        $arb[$i] = " وستمائة ";
                        break;
                    case "7":
                        $arb[$i] = " وسبعمائة ";
                        break;
                    case "8":
                        $arb[$i] = " وثمانمائة ";
                        break;
                    case "9":
                        $arb[$i] = " وتسعمائة ";
                        break;
                }
        }

        if ($i == 6)
            switch ($te[$i]) {
                case "0":
                    $arb[$i] = " ";
                    break;
                case "1":
                    $arb[$i] = " مليون ";
                    break;
                case "2":
                    $arb[$i] = " مليونان ";
                    break;
                case "3":
                    $arb[$i] = " ثلاثة ملايين ";
                    break;
                case "4":
                    $arb[$i] = " اربعة ملايين ";
                    break;
                case "5":
                    $arb[$i] = " خمسة ملايين ";
                    break;
                case "6":
                    $arb[$i] = " تة ملايين ";
                    break;
                case "7":
                    $arb[$i] = " سبعة ملايين ";
                    break;
                case "8":
                    $arb[$i] = " ثمانية ملايين ";
                    break;
                case "9":
                    $arb[$i] = " تسعة ملايين ";
                    break;
            }
    }

    if ($j > 4 && $te[4] != "1") {
        $arb[4] = $arb[4] . " الف ";
    }

    isset($arb[0]) ? $arb0 = $arb[0] : $arb0 = "";
    isset($arb[1]) ? $arb1 = $arb[1] : $arb1 = "";
    isset($arb[2]) ? $arb2 = $arb[2] : $arb2 = "";
    isset($arb[3]) ? $arb3 = $arb[3] : $arb3 = "";
    isset($arb[4]) ? $arb4 = $arb[4] : $arb4 = "";
    isset($arb[5]) ? $arb5 = $arb[5] : $arb5 = "";
    isset($arb[6]) ? $arb6 = $arb[6] : $arb6 = "";

    $strarb = $arb6 . $arb5 . $arb3 . $arb4 . $arb2 . $arb0 . $arb1;
    //echo $arb[6] . $arb[5] . $arb[3] . $arb[4] . $arb[2] . $arb[0] . $arb[1];
    return $strarb;
}
?>

