Base Directory:
/home/ecedu/public_html/cce/api
$status, 'message' => $message], JSON_UNESCAPED_UNICODE);
exit;
}
try{
$typeId = filter_input(INPUT_POST, 'type_id', FILTER_VALIDATE_INT);
$imgUrl = filter_input(INPUT_POST, 'img_url', FILTER_SANITIZE_URL);
$file = $_FILES['image'] ?? null;
if (!$userId || !$typeId || !$file || $file['error'] !== UPLOAD_ERR_OK) {
throw new Exception( "error-1: فشل تحميل ملف الصورة !");
}
// 3. التحقق من امتداد الملف
$allowedExt = ['jpeg','jpg','png','gif','bmp'];
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if (!in_array($ext, $allowedExt, true)) {
throw new Exception( "error-2: نوع ملف الصورة غير مدعوم");
}
// 4. تحديد مجلد التحميل
$baseDir = __DIR__ . '/../service/images';
$subDir = in_array($typeId, [1,2,3,4], true) ? 'ads' : '';
$uploadDir = $baseDir . ($subDir ? "/$subDir" : '');
if (!is_dir($uploadDir) && !mkdir($uploadDir, 0755, true)) {
throw new Exception( "error-3: فشل حفظ ملف الصورة !");
}
require_once __DIR__ . '/../Models/ImageManager.php';
$imageMgr = new ImageManager();
// 6) نفس المنطق السابق:
$imageRow = $imageMgr->getAdsByType($typeId);
$imgId = (int)($imageRow['img_id'] ?? 0);
$oldUrl = $imageRow['img_url'] ?? '';
$oldExt = $imageRow['img_ext'] ?? '';
// 7. حذف الصورة القديمة إن وجدت
if ($imgId>0) {
$oldPath = "$uploadDir/img_{$imgId}.{$oldExt}";
if (is_file($oldPath)) {
@chmod($oldPath, 0644);
@unlink($oldPath);
}
}
// 8) إدراج أو تحديث السجل
if ($imgId>0) {
$updated = $imageMgr->updateAdsRecord($imgId,$imgUrl, $ext, $userId);
if (!$updated) {
throw new Exception( "error-4: فشل التحديث في قاعدة البيانات");
}
} else {
$newId = $imageMgr->insertAdsRecord($typeId,$imgUrl, $ext, $userId);
if (!$newId) {
throw new Exception( "error-5: فشل الإدراج في قاعدة البيانات");
}
$imgId = $newId;
}
// 9. حفظ الملف المرفوع
$newName = "img_{$imgId}.{$ext}";
$destination = "$uploadDir/$newName";
if (!move_uploaded_file($file['tmp_name'], $destination)) {
throw new Exception( "error-6: فشل حفظ ملف الصورة !");
}
respond(true, 'تم تحديث البيانات بنجاح');
} catch (Exception $e) {
$db->rollBack();
respond(false, $e->getMessage());
}