<?php
require __DIR__ . '/_common.php';

$action = $_GET['action'] ?? 'upload';
$owner_type = $_GET['owner_type'] ?? '';
$owner_id = intval($_GET['owner_id'] ?? 0);
$back = $_POST['back'] ?? ($_GET['back'] ?? url('/index.php?page=dashboard'));

function owner_perm(string $ownerType): string {
  if ($ownerType==='asset') return 'manage_assets';
  if ($ownerType==='farm') return 'manage_farms';
  return 'manage_assets';
}

function owner_exists(string $ownerType, int $id): bool {
  if ($ownerType==='asset') return (bool)db_one("SELECT id FROM assets WHERE id=? LIMIT 1", [$id]);
  if ($ownerType==='farm') return (bool)db_one("SELECT id FROM farms WHERE id=? LIMIT 1", [$id]);
  return false;
}

function allowed_upload(string $mime, string $ext): bool {
  $mime = strtolower(trim($mime));
  $ext = strtolower(trim($ext));

  // Accept by extension first (strong allowlist)
  $allowedExt  = ['pdf','jpg','jpeg','png','webp'];
  if (!in_array($ext, $allowedExt, true)) return false;

  // MIME can vary by OS/server; be tolerant
  $allowedMime = [
    'application/pdf',
    'application/octet-stream', // sometimes PDFs come as octet-stream on Windows
    'image/jpeg',
    'image/jpg',
    'image/png',
    'image/webp',
  ];

  if ($mime === '' || $mime === 'application/octet-stream') return true;
  return in_array($mime, $allowedMime, true);
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  redirect($back);
}

csrf_check();

if ($owner_type==='' || $owner_id<=0) {
  flash_set('error','بيانات المرفق غير مكتملة.');
  redirect($back);
}

require_perm(owner_perm($owner_type));

if (!owner_exists($owner_type, $owner_id)) {
  flash_set('error','العنصر غير موجود.');
  redirect($back);
}

if ($action === 'upload') {
  if (empty($_FILES['file']) || !isset($_FILES['file']['tmp_name'])) {
    flash_set('error','اختر ملفاً للرفع.');
    redirect($back);
  }

  $f = $_FILES['file'];
  if (($f['error'] ?? UPLOAD_ERR_OK) !== UPLOAD_ERR_OK) {
    flash_set('error','تعذر رفع الملف.');
    redirect($back);
  }

  $orig = (string)($f['name'] ?? 'file');
  $tmp  = (string)($f['tmp_name'] ?? '');
  $size = intval($f['size'] ?? 0);

  if ($size <= 0 || $size > 10*1024*1024) {
    flash_set('error','حجم الملف يجب أن يكون أقل من 10MB.');
    redirect($back);
  }

  $ext = pathinfo($orig, PATHINFO_EXTENSION);
  $mime = '';
if (function_exists('finfo_open')) {
  $fi = finfo_open(FILEINFO_MIME_TYPE);
  if ($fi) { $mime = (string)finfo_file($fi, $tmp); finfo_close($fi); }
}
if ($mime === '' && function_exists('mime_content_type')) {
  $mime = (string)mime_content_type($tmp);
}
$mime = (string)$mime;


  if (!allowed_upload($mime, $ext)) {
    flash_set('error','نوع الملف غير مدعوم. المسموح: PDF أو صورة. (امتداد: ' . e($ext) . ' | MIME: ' . e($mime) . ')');
    redirect($back);
  }

  $sub = date('Y/m');
  $dir = __DIR__ . '/../../storage/uploads/' . $sub;
  if (!is_dir($dir)) @mkdir($dir, 0777, true);

  $safeExt = strtolower($ext ?: 'bin');
  $name = bin2hex(random_bytes(16)) . '.' . $safeExt;
  $rel = $sub . '/' . $name;
  $dst = $dir . '/' . $name;

  if (!move_uploaded_file($tmp, $dst)) {
    flash_set('error','فشل حفظ الملف.');
    redirect($back);
  }

  $uid = intval($_SESSION['uid'] ?? 0) ?: null;
  $newId = db_insert("INSERT INTO attachments (owner_type,owner_id,stored_name,original_name,mime,size_bytes,uploaded_by,created_at)
                      VALUES (?,?,?,?,?,?,?,?)",
                      [$owner_type,$owner_id,$rel,$orig,$mime,$size,$uid, now_dt()]);
  audit_log('upload_attachment','attachments',$newId,null,db_one("SELECT * FROM attachments WHERE id=?",[$newId]));
  flash_set('ok','تم رفع المرفق.');
  redirect($back);
}

if ($action === 'delete') {
  $attach_id = intval($_POST['id'] ?? 0);
  if ($attach_id<=0) { flash_set('error','مرفق غير صالح.'); redirect($back); }

  $row = db_one("SELECT * FROM attachments WHERE id=?", [$attach_id]);
  if (!$row) { flash_set('error','المرفق غير موجود.'); redirect($back); }

  // Ensure owner matches
  if ((string)$row['owner_type'] !== $owner_type || intval($row['owner_id']) !== $owner_id) {
    flash_set('error','طلب غير صالح.');
    redirect($back);
  }

  $old = $row;
  // Delete file
  $full = __DIR__ . '/../../storage/uploads/' . $row['stored_name'];
  if (is_file($full)) @unlink($full);

  db_exec("DELETE FROM attachments WHERE id=?", [$attach_id]);
  audit_log('delete_attachment','attachments',$attach_id,$old,null);
  flash_set('ok','تم حذف المرفق.');
  redirect($back);
}

redirect($back);
