<?php

/*
 * this function created to used easy class upload
 * every function have job
 * you can add more function and modied without damage other
 * function used in files
 */

require_once 'class.upload.php';

function uploadnew($filename, $boolresize, $width, $height, $uploadfolder, $uploadtype = 1, $lang = 'ar')
{
    // رسائل متعددة اللغات
    $messages = [
        'ar' => [
            'no_file' => 'لم يتم رفع أي ملف أو حدث خطأ أثناء الرفع.',
            'large_file' => 'حجم الملف أكبر من 1 ميجابايت.',
            'success' => 'تم رفع الصورة بنجاح.',
            'process_fail' => 'فشل في معالجة الملف: ',
            'upload_fail' => 'فشل في رفع الملف.',
        ],
        'en' => [
            'no_file' => 'No file uploaded or an error occurred during upload.',
            'large_file' => 'The file size exceeds 1 MB.',
            'success' => 'Image uploaded successfully.',
            'process_fail' => 'Failed to process the file: ',
            'upload_fail' => 'File upload failed.',
        ]
    ];

    // اختيار اللغة (افتراضي عربي)
    $t = isset($messages[$lang]) ? $messages[$lang] : $messages['ar'];


    // تحقق من وجود الملف
    if (!isset($_FILES[$filename]) || $_FILES[$filename]['error'] !== UPLOAD_ERR_OK) {
        return [
            'code' => 400,
            'success' => false,
            'message' => $t['no_file']
        ];
    }

    // تحقق من حجم الصورة (أقل من 1 ميجابايت)
    $maxSize = 1 * 1024 * 1024; // 1MB
    if ($_FILES[$filename]['size'] > $maxSize) {
        return [
            'code' => 413,
            'success' => false,
            'message' => $t['large_file']
        ];
    }

    // الاسم الأصلي
    $originalName = $_FILES[$filename]['name'];
    $randomname = md5(uniqid(mt_rand(), true));
    $handle = new upload($_FILES[$filename]);
    $imageNewName = "no image";

    if ($handle->uploaded) {
        $handle->image_interlace = true;
        $handle->image_resize = $boolresize;
        $handle->image_x = $width;
        $handle->image_y = $height;

        // أنواع الملفات المسموح بها
        if ($uploadtype == 1) {
            $handle->allowed = array('image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp', 'image/*');
        } elseif ($uploadtype == 2) {
            $handle->allowed = array('application/pdf');
        } elseif ($uploadtype == 7) {
            // allow all
        } else {
            $handle->allowed = array('application/pdf', 'application/msword', 'application/x-zip', 'image/*');
        }

        $handle->file_new_name_body = $randomname;
        $handle->process("../../upload/" . $uploadfolder);

        if ($handle->processed) {
            $handle->clean();
            $imageNewName = $randomname . "." . $handle->file_src_name_ext;

            $data = [
                'original' => $originalName,
                'new' => $imageNewName,
                'status' => 'success'
            ];

            return [
                'code' => 200,
                'success' => true,
                'message' => $t['success'],
                'data' => $data
            ];
        } else {
            return [
                'code' => 415,
                'success' => false,
                'message' => $t['process_fail'] . $handle->error
            ];
        }
    }

    return [
        'code' => 500,
        'success' => false,
        'message' => $t['upload_fail']
    ];
}


// رفع أكثر من ملف
function uploadMultiNew($filename, $boolresize, $width, $height, $uploadfolder, $uploadtype = true, $lang = 'ar')
{
    // رسائل اللغات
    $messages = array(
        'ar' => array(
            'no_file' => 'لم يتم رفع أي ملف أو حدث خطأ أثناء الرفع.',
            'large_file' => 'حجم الملف أكبر من 1 ميجابايت.',
            'success' => 'تم رفع الصور بنجاح.',
            'process_fail' => 'فشل في معالجة الملف: ',
            'upload_fail' => 'فشل في رفع الملف.',
        ),
        'en' => array(
            'no_file' => 'No file uploaded or an error occurred during upload.',
            'large_file' => 'The file size exceeds 1 MB.',
            'success' => 'Images uploaded successfully.',
            'process_fail' => 'Failed to process file: ',
            'upload_fail' => 'File upload failed.',
        )
    );

    $t = isset($messages[$lang]) ? $messages[$lang] : $messages['ar'];

    // تحقق من الملفات
    if (!isset($_FILES[$filename]) || !is_array($_FILES[$filename]['name'])) {
        return array('code' => 400, 'success' => false, 'message' => $t['no_file']);
    }

    // ترتيب الملفات في مصفوفة مفهومة
    $files = array();
    foreach ($_FILES[$filename] as $k => $l) {
        foreach ($l as $i => $v) {
            if (!array_key_exists($i, $files))
                $files[$i] = array();
            $files[$i][$k] = $v;
        }
    }

    $uploadedFiles = array();
    $maxSize = 1 * 1024 * 1024; // 1MB

    foreach ($files as $file) {
        if ($file['error'] !== UPLOAD_ERR_OK) {
            $uploadedFiles[] = array('original' => $file['name'], 'status' => 'error', 'message' => $t['no_file']);
            continue;
        }

        if ($file['size'] > $maxSize) {
            $uploadedFiles[] = array('original' => $file['name'], 'status' => 'error', 'message' => $t['large_file']);
            continue;
        }

        $randomname = md5(uniqid(mt_rand(), true));
        $handle = new upload($file);

        if ($handle->uploaded) {
            $handle->image_interlace = true;
            $handle->image_resize = $boolresize;
            $handle->image_x = $width;
            $handle->image_y = $height;

            if ($uploadtype) {
                $handle->allowed = array('image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp', 'image/*');
            } else {
                $handle->allowed = array(
                    'application/pdf', 'application/msword', 'application/x-zip', 'image/*',
                    'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                );
            }

            $handle->file_new_name_body = $randomname;
            $handle->process("../../upload/" . $uploadfolder);

            if ($handle->processed) {
                $handle->clean();
                $imageNewName = $randomname . "." . $handle->file_src_name_ext;
                $uploadedFiles[] = array(
                    'original' => $file['name'],
                    'new' => $imageNewName,
                    'status' => 'success'
                );
            } else {
                $uploadedFiles[] = array('original' => $file['name'], 'status' => 'error', 'message' => $t['process_fail'] . $handle->error);
            }
        } else {
            $uploadedFiles[] = array('original' => $file['name'], 'status' => 'error', 'message' => $t['upload_fail']);
        }
    }

    return array(
        'code' => 200,
        'success' => true,
        'message' => $t['success'],
        'data' => $uploadedFiles
    );
}






// تحديث ملف قديم واستبداله بجديد
function uploadupdate($filename, $oldname, $boolresize, $width, $height, $uploadfolder, $uploadtype = 1, $lang = 'ar')
{
    $messages = array(
        'ar' => array(
            'no_file' => 'لم يتم رفع أي ملف أو حدث خطأ أثناء الرفع.',
            'large_file' => 'حجم الملف أكبر من 1 ميجابايت.',
            'success' => 'تم تحديث الصورة بنجاح.',
            'process_fail' => 'فشل في معالجة الملف: ',
            'upload_fail' => 'فشل في رفع الملف.',
            'deleted' => 'تم حذف الصورة القديمة.'
        ),
        'en' => array(
            'no_file' => 'No file uploaded or an error occurred during upload.',
            'large_file' => 'The file size exceeds 1 MB.',
            'success' => 'Image updated successfully.',
            'process_fail' => 'Failed to process the file: ',
            'upload_fail' => 'File upload failed.',
            'deleted' => 'Old image deleted.'
        )
    );

    $t = isset($messages[$lang]) ? $messages[$lang] : $messages['ar'];

    // تحقق من وجود الملف
    if (!isset($_FILES[$filename]) || $_FILES[$filename]['error'] !== UPLOAD_ERR_OK) {
        return array('code' => 400, 'success' => false, 'message' => $t['no_file']);
    }

    // تحقق من الحجم
    $maxSize = 1 * 1024 * 1024; // 1MB
    if ($_FILES[$filename]['size'] > $maxSize) {
        return array('code' => 413, 'success' => false, 'message' => $t['large_file']);
    }

    $imageUrl = isset($_POST[$oldname]) ? $_POST[$oldname] : '';
    $randomname = md5(uniqid(mt_rand(), true));
    $handle = new upload($_FILES[$filename]);
    $imageNewName = $imageUrl;

    if ($handle->uploaded) {
        $handle->image_interlace = true;
        $handle->image_resize = $boolresize;
        $handle->image_x = $width;
        $handle->image_y = $height;

        if ($uploadtype == 1) {
            $handle->allowed = array('image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp', 'image/*');
        } elseif ($uploadtype == 2) {
            $handle->allowed = array('application/pdf');
        } else {
            $handle->allowed = array('application/pdf', 'application/msword', 'application/x-zip', 'image/*');
        }

        $handle->file_new_name_body = $randomname;
        $handle->process("../../upload/" . $uploadfolder);

        if ($handle->processed) {
            $handle->clean();
            // حذف الصورة القديمة إن وُجدت
            if ($imageNewName != "no image" && $imageNewName != '' && file_exists("../../upload/" . $uploadfolder . "/" . $imageNewName)) {
                @chmod("../../upload/" . $uploadfolder . "/" . $imageNewName, 0777);
                @unlink("../../upload/" . $uploadfolder . "/" . $imageNewName);
            }

            $imageNewName = $randomname . "." . $handle->file_src_name_ext;
            return array('code' => 200, 'success' => true, 'message' => $t['success'], 'new_name' => $imageNewName);
        } else {
            return array('code' => 415, 'success' => false, 'message' => $t['process_fail'] . $handle->error);
        }
    }

    return array('code' => 500, 'success' => false, 'message' => $t['upload_fail']);
}



