<?php
header('Content-Type: application/json; charset=utf-8');

$uploadDir = __DIR__ . "/uploads/files/";
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

$response = [];
$allowedExt = ['pdf','doc','docx','xls','xlsx'];
$allowedMime = [
    'application/pdf',
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'application/vnd.ms-excel',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
];

// الحجم الأقصى (5MB)
$maxSize = 5 * 1024 * 1024;

if (!isset($_FILES['files'])) {
    echo json_encode(['success' => false, 'msg' => 'لم يتم استقبال أي ملف']);
    exit;
}

foreach ($_FILES['files']['tmp_name'] as $i => $tmpName) {
    if (!is_uploaded_file($tmpName)) {
        $response[] = ['success' => false, 'msg' => 'ملف غير صالح'];
        continue;
    }

    // تحقق من الحجم
    if ($_FILES['files']['size'][$i] > $maxSize) {
        $response[] = ['success' => false, 'msg' => 'الحجم أكبر من 5MB'];
        continue;
    }

    $name = $_FILES['files']['name'][$i];
    $ext  = strtolower(pathinfo($name, PATHINFO_EXTENSION));
    $mime = mime_content_type($tmpName);

    if (!in_array($ext, $allowedExt) || !in_array($mime, $allowedMime)) {
        $response[] = ['success' => false, 'msg' => "امتداد أو نوع غير مسموح: $ext"];
        continue;
    }

    // تنظيف الاسم (السماح بالعربي والإنجليزي + الأرقام + - + _)
    $filenameOnly = pathinfo($name, PATHINFO_FILENAME);
    $safeName = preg_replace('/[^\p{Arabic}A-Za-z0-9_\-]/u','_',str_replace('.', '_', $filenameOnly));

    // المعرف الفريد
    $uniqueId = uniqid();

    // الاسم الجديد
    $newName = $safeName . "_" . $uniqueId . "." . $ext;
    $dest = $uploadDir . $newName;

    if (move_uploaded_file($tmpName, $dest)) {
        $response[] = ['success' => true, 'file' => $newName, 'file_title' => $name];
    } else {
        $response[] = ['success' => false, 'msg' => 'فشل نقل الملف'];
    }
}

echo json_encode($response, JSON_UNESCAPED_UNICODE);
